Example usage for org.json.simple JSONObject entrySet

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

Introduction

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

Prototype

Set<Map.Entry<K, V>> entrySet();

Source Link

Document

Returns a Set view of the mappings contained in this map.

Usage

From source file:org.wso2.carbon.apimgt.impl.soaptorest.util.SequenceUtils.java

/**
 * Gets parameter definitions from swagger
 *
 * @param swaggerObj swagger json//  w  ww  . j a va  2  s  . c  om
 * @param resource   rest resource object
 * @param method     http method
 * @return parameter mapping for a resource from the swagger definitions
 */
public static List<JSONObject> getResourceParametersFromSwagger(JSONObject swaggerObj, JSONObject resource,
        String method) {
    Map content = (HashMap) resource.get(method);
    JSONArray parameters = (JSONArray) content.get(SOAPToRESTConstants.Swagger.PARAMETERS);
    List<JSONObject> mappingList = new ArrayList<>();
    for (Object param : parameters) {
        String inputType = String.valueOf(((JSONObject) param).get(SOAPToRESTConstants.Swagger.IN));
        if (inputType.equals(SOAPToRESTConstants.Swagger.BODY)) {
            JSONObject schema = (JSONObject) ((JSONObject) param).get(SOAPToRESTConstants.Swagger.SCHEMA);
            String definitionPath = String.valueOf(schema.get(SOAPToRESTConstants.Swagger.REF));
            String definition = definitionPath.replaceAll(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT,
                    SOAPToRESTConstants.EMPTY_STRING);
            JSONObject definitions = (JSONObject) ((JSONObject) swaggerObj
                    .get(SOAPToRESTConstants.Swagger.DEFINITIONS)).get(definition);
            JSONObject properties = (JSONObject) definitions.get(SOAPToRESTConstants.Swagger.PROPERTIES);

            for (Object property : properties.entrySet()) {
                Map.Entry entry = (Map.Entry) property;
                String paramName = String.valueOf(entry.getKey());
                JSONObject value = (JSONObject) entry.getValue();
                JSONArray propArray = new JSONArray();
                if (value.get(SOAPToRESTConstants.Swagger.REF) != null) {
                    String propDefinitionRef = String.valueOf(value.get(SOAPToRESTConstants.Swagger.REF))
                            .replaceAll(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT,
                                    SOAPToRESTConstants.EMPTY_STRING);
                    getNestedDefinitionsFromSwagger(
                            (JSONObject) swaggerObj.get(SOAPToRESTConstants.Swagger.DEFINITIONS),
                            propDefinitionRef, propDefinitionRef, propArray);
                    JSONObject refObj = new JSONObject();
                    refObj.put(paramName, propArray);
                    if (log.isDebugEnabled()) {
                        log.debug("Properties for from resource parameter: " + paramName + " are: "
                                + propArray.toJSONString());
                    }
                    mappingList.add(refObj);
                } else if (String.valueOf(value.get(SOAPToRESTConstants.Swagger.TYPE))
                        .equals(SOAPToRESTConstants.ParamTypes.ARRAY)) {
                    JSONObject arrObj = new JSONObject();
                    arrObj.put(((Map.Entry) property).getKey(), ((Map.Entry) property).getValue());
                    mappingList.add(arrObj);
                    if (log.isDebugEnabled()) {
                        log.debug("Properties for from array type resource parameter: "
                                + ((Map.Entry) property).getKey() + " are: " + arrObj.toJSONString());
                    }
                }
            }
        } else {
            JSONObject queryObj = new JSONObject();
            queryObj.put(((JSONObject) param).get(SOAPToRESTConstants.Swagger.NAME), param);
            mappingList.add(queryObj);
            if (log.isDebugEnabled()) {
                log.debug("Properties for from query type resource parameter: " + queryObj.toJSONString());
            }
        }
    }
    return mappingList;
}

From source file:org.wso2.carbon.apimgt.impl.soaptorest.util.SequenceUtils.java

/**
 * Gets nested swagger definitions for the complex types
 *
 * @param definitions swagger definition json
 * @param definition  parent definition// w w  w. j av  a  2s  .  co  m
 * @param jsonPath    json path to be construct
 * @param propArray   properties for the nested definition
 */
private static void getNestedDefinitionsFromSwagger(JSONObject definitions, String definition, String jsonPath,
        JSONArray propArray) {
    JSONObject propDefinitions = (JSONObject) (definitions).get(definition);
    JSONObject props;
    if (SOAPToRESTConstants.ParamTypes.ARRAY.equals(propDefinitions.get(SOAPToRESTConstants.TYPE_ATTRIBUTE))) {
        props = (JSONObject) propDefinitions.get(SOAPToRESTConstants.Swagger.ITEMS);
        if (props.get(SOAPToRESTConstants.Swagger.REF) == null) {
            JSONObject arrayProperty = new JSONObject();
            String key = jsonPath + "." + props.get(SOAPToRESTConstants.TYPE_ATTRIBUTE);
            arrayProperty.put(key, props.get(SOAPToRESTConstants.TYPE_ATTRIBUTE));
            arrayProperty.put(SOAPToRESTConstants.TYPE_ATTRIBUTE, SOAPToRESTConstants.ParamTypes.ARRAY);
            arrayProperty.put(SOAPToRESTConstants.SequenceGen.PARAMETER_NAME,
                    props.get(SOAPToRESTConstants.TYPE_ATTRIBUTE));
            arrayProperty.put(SOAPToRESTConstants.SequenceGen.XPATH, jsonPath);
            propArray.add(arrayProperty);
            return;
        }
    } else {
        props = (JSONObject) propDefinitions.get(SOAPToRESTConstants.Swagger.PROPERTIES);
    }
    for (Object property : props.entrySet()) {
        Map.Entry entry = (Map.Entry) property;
        String paramName = String.valueOf(entry.getKey());
        JSONObject value = (JSONObject) entry.getValue();
        if (value.get(SOAPToRESTConstants.Swagger.REF) != null) {
            String propDefinitionRef = String.valueOf(value.get(SOAPToRESTConstants.Swagger.REF))
                    .replaceAll(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT, SOAPToRESTConstants.EMPTY_STRING);
            jsonPath = definition + "." + propDefinitionRef;
            getNestedDefinitionsFromSwagger(definitions, propDefinitionRef, jsonPath, propArray);
        } else {
            JSONObject nestedProp = new JSONObject();
            String key;
            if (jsonPath.endsWith(definition)) {
                key = jsonPath + "." + paramName;
            } else {
                key = definition + "." + paramName;
            }
            nestedProp.put(key, value);
            propArray.add(nestedProp);
        }
        if (log.isDebugEnabled()) {
            log.debug("json path for definition: " + definition + " is: " + jsonPath);
        }
    }
}

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

/**
 * Returns a map of gateway / store domains for the tenant
 *
 * @return a Map of domain names for tenant
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if an error occurs when loading tiers from the registry
 *//*from   w  w  w . j ava2  s .c om*/
public static Map<String, String> getDomainMappings(String tenantDomain, String appType)
        throws APIManagementException {
    Map<String, String> domains = new HashMap<String, String>();
    String resourcePath;
    try {
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService()
                .getGovernanceSystemRegistry();
        resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace("<tenant-id>", tenantDomain);
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
            JSONParser parser = new JSONParser();
            JSONObject mappings = (JSONObject) parser.parse(content);
            if (mappings.get(appType) != null) {
                mappings = (JSONObject) mappings.get(appType);
                for (Object o : mappings.entrySet()) {
                    Entry thisEntry = (Entry) o;
                    String key = (String) thisEntry.getKey();
                    String value = (String) thisEntry.getValue();
                    domains.put(key, value);
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while retrieving gateway domain mappings from registry";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    } catch (ClassCastException e) {
        String msg = "Invalid JSON found in the gateway tenant domain mappings";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Malformed JSON found in the gateway tenant domain mappings";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return domains;
}

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   ww  w  .j  ava 2  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.appmgt.hostobjects.APIProviderHostObject.java

/**
 * Update business owner.//from  ww w .ja  va2  s .  c  om
 *
 * @param context Rhino context
 * @param thisObj Scriptable object
 * @param args    Arguments
 * @param funObj  Function object
 * @throws AppManagementException on error while trying to update business owner
 */
public static void jsFunction_updateBusinessOwner(Context context, Scriptable thisObj, Object[] args,
        Function funObj) throws AppManagementException {
    if (args == null || args.length != 6) {
        handleException("Invalid number of input parameters.");
    }
    if (args[0] == null || args[1] == null) {
        handleException("Error occurred while updating business owner. Business owner content is null");
    }
    BusinessOwner businessOwner = new BusinessOwner();
    List<BusinessOwnerProperty> businessOwnerPropertiesList = new ArrayList<BusinessOwnerProperty>();

    businessOwner.setBusinessOwnerId(Integer.parseInt(args[0].toString()));
    businessOwner.setBusinessOwnerName(args[1].toString());
    businessOwner.setBusinessOwnerEmail(args[2].toString());
    businessOwner.setBusinessOwnerDescription(args[3].toString());
    businessOwner.setBusinessOwnerSite(args[4].toString());

    JSONParser parser = new JSONParser();
    JSONObject businessOwnerDetailObject = null;
    try {
        businessOwnerDetailObject = (JSONObject) parser.parse(args[5].toString());
    } catch (ParseException e) {
        handleException("Error while parsing JSON", e);
    }
    Set<Map.Entry> entries = businessOwnerDetailObject.entrySet();
    for (Map.Entry entry : entries) {
        String key = (String) entry.getKey();
        JSONArray businessOwnerValuesObject = (JSONArray) entry.getValue();
        String propertyValue = businessOwnerValuesObject.get(0).toString();
        String showInStore = businessOwnerValuesObject.get(1).toString();
        BusinessOwnerProperty businessOwnerProperty = new BusinessOwnerProperty();
        businessOwnerProperty.setPropertyKey(key);
        businessOwnerProperty.setPropertyValue(propertyValue);
        businessOwnerProperty.setShowingInStore(Boolean.parseBoolean(showInStore));

        businessOwnerPropertiesList.add(businessOwnerProperty);
    }
    businessOwner.setBusinessOwnerPropertiesList(businessOwnerPropertiesList);
    APIProvider apiProvider = getAPIProvider(thisObj);
    apiProvider.updateBusinessOwner(businessOwner);
}

From source file:org.wso2.carbon.appmgt.hostobjects.APIProviderHostObject.java

/**
 * Save business owner.//  ww w .  ja va2  s . c  o  m
 *
 * @param context Rhino context
 * @param thisObj Scriptable object
 * @param args    Arguments
 * @param funObj  Function object
 * @return Saved business owner id
 * @throws AppManagementException on error while trying to save business owner
 */
public static int jsFunction_saveBusinessOwner(Context context, Scriptable thisObj, Object[] args,
        Function funObj) throws AppManagementException {
    BusinessOwner businessOwner = new BusinessOwner();
    List<BusinessOwnerProperty> businessOwnerProperties = null;

    if (args == null || args.length != 5) {
        handleException("Invalid number of input parameters.");
    }
    if (args[0] == null || args[1] == null) {
        handleException("Error occurred while saving business owner. Business owner content is null");
    }

    businessOwner.setBusinessOwnerName(args[0].toString());
    businessOwner.setBusinessOwnerEmail(args[1].toString());
    String businessOwnerDescription = args[2].toString();
    if (StringUtils.isEmpty(businessOwnerDescription)) {
        businessOwnerDescription = null;
    }
    String businessOwnerSite = args[3].toString();
    if (StringUtils.isEmpty(businessOwnerSite)) {
        businessOwnerSite = null;
    }
    businessOwner.setBusinessOwnerDescription(businessOwnerDescription);
    businessOwner.setBusinessOwnerSite(businessOwnerSite);

    JSONParser parser = new JSONParser();
    JSONObject businessOwnerPropertyObject = null;
    try {
        businessOwnerPropertyObject = (JSONObject) parser.parse(args[4].toString());
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON", e);
    }

    Set<Map.Entry> entries = businessOwnerPropertyObject.entrySet();
    if (entries.size() > 0) {
        businessOwnerProperties = new ArrayList<BusinessOwnerProperty>();
        for (Map.Entry entry : entries) {
            String key = (String) entry.getKey();
            JSONArray businessOwnerValuesObject = (JSONArray) entry.getValue();
            String propertyValue = businessOwnerValuesObject.get(0).toString();
            Boolean showInStore = Boolean.parseBoolean(businessOwnerValuesObject.get(1).toString());
            BusinessOwnerProperty businessOwnerPropertiesValues = new BusinessOwnerProperty();
            businessOwnerPropertiesValues.setPropertyKey(key);
            businessOwnerPropertiesValues.setPropertyValue(propertyValue);
            businessOwnerPropertiesValues.setShowingInStore(showInStore);

            businessOwnerProperties.add(businessOwnerPropertiesValues);
        }
    }
    businessOwner.setBusinessOwnerPropertiesList(businessOwnerProperties);
    APIProvider apiProvider = getAPIProvider(thisObj);
    int businessOwnerId = apiProvider.saveBusinessOwner(businessOwner);
    return businessOwnerId;
}

From source file:pl.nask.hsn2.unicorn.commands.JobDescriptorLoopedCommand.java

private String[] parseServiceParameters(String parametersAsString) {
    if ("{}".equals(parametersAsString)) {
        return new String[] {};
    }//  w ww  .j ava 2s  . c om

    List<String> params = new ArrayList<>();
    JSONObject jsonServices = (JSONObject) JSONValue.parse(parametersAsString);
    Iterator it = jsonServices.entrySet().iterator();
    while (it.hasNext()) {
        Object obj = it.next();
        if (obj instanceof Entry) {
            Entry entry = (Entry) obj;
            String serviceName = (String) entry.getKey();
            JSONObject jsonServiceParams = (JSONObject) entry.getValue();
            Iterator it2 = jsonServiceParams.entrySet().iterator();
            while (it2.hasNext()) {
                Object obj2 = it2.next();
                if (obj2 instanceof Entry) {
                    Entry entry2 = (Entry) obj2;
                    String paramName = (String) entry2.getKey();
                    String paramValue = (String) entry2.getValue();
                    params.add(serviceName + "." + paramName + "=" + paramValue);
                }
            }
        }
    }
    return params.toArray(new String[params.size()]);
}

From source file:report.builder.ImageBuilder.java

/**
 * Initializes the FieldsMetaData for all images,
 * creates them with the paths from the JSON and adds it to the report's context.
 *///from   w  w  w  .j a va 2 s  .com
@Override
public void build(JSONObject json, FieldsMetadata metadata, IContext context) {
    // iterate on all images
    Iterator<?> iter = json.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
        // set the FieldsMetaData
        metadata.addFieldAsImage(entry.getKey().toString());
        // create the image
        IImageProvider img = new FileImageProvider(new File(entry.getValue().toString()));
        img.setUseImageSize(true);
        // add it to the report's context
        context.put(entry.getKey().toString(), img);
    }
}

From source file:report.builder.ListBuilder.java

/**
 * Initializes the FieldsMetaData with the key of the JSON data
 * and adds the list to the report's context.
 * @param listObject The JSON list object.
 *//*from  www  .j av  a 2 s . c om*/
@Override
public void build(JSONObject json, FieldsMetadata metadata, IContext context) {
    // Iterates on all the list:
    Iterator<?> iter = json.entrySet().iterator();
    while (iter.hasNext()) {
        // Gets the key and the array:
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
        String key = entry.getKey().toString();
        JSONArray array = (JSONArray) entry.getValue();

        // Gets the FieldsMetaData, searching for all different keys on the Map:
        HashSet<String> metaData = new HashSet<String>();
        Iterator<?> iterArray = array.iterator();
        while (iterArray.hasNext()) {
            JSONObject map = (JSONObject) iterArray.next();
            Iterator<?> iterMap = map.entrySet().iterator();
            while (iterMap.hasNext()) {
                Map.Entry<?, ?> entryMap = (Map.Entry<?, ?>) iterMap.next();
                metaData.add(entryMap.getKey().toString());
            }
        }

        // Sets the FieldsMetaData:
        Iterator<?> iterMetaData = metaData.iterator();
        while (iterMetaData.hasNext()) {
            metadata.addFieldAsList(key + "." + iterMetaData.next().toString());
        }

        // Adds the array to the report's context.
        // array can be directly passed as a value for contextMap because it inherits from ArrayList.
        context.put(key, array);
    }
}

From source file:report.builder.TextBuilder.java

/**
 * Adds the text data from the JSON to the report's context.
 *///ww w .ja v  a 2s.  co m
@Override
public void build(JSONObject json, FieldsMetadata metadata, IContext context) {
    // iterate on all the simple text
    Iterator<?> iter = json.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
        // add the text to the report's context
        context.put(entry.getKey().toString(), entry.getValue().toString());
    }
}