Example usage for org.json.simple JSONObject keySet

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

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

Usage

From source file:org.wso2.carbon.apimgt.hostobjects.APIStoreHostObject.java

/**
 * this method used to iterate environments according to type
 *  @param environments json/* w w  w  .j av  a2  s  .  c om*/
 * @param api API object of selected api .
 * @param version version of API
 * @param myn
 * @param envCount count parameter
 * @param type type of environment
 */
private static int createAPIEndpointsPerType(JSONObject environments, API api, String version, NativeArray myn,
        int envCount, String type) {
    for (Object prodKeys : environments.keySet()) {
        JSONObject environmentObject = (JSONObject) environments.get(prodKeys);
        NativeObject appObj = new NativeObject();
        appObj.put("environmentName", appObj, prodKeys);
        appObj.put("environmentType", appObj, type);
        NativeArray envs = new NativeArray(0);
        int index = 0;
        for (Object envURL : environmentObject.entrySet()) {
            envs.put(index, envs, envURL + api.getContext());
            if (api.isDefaultVersion()) {
                String apiContext = api.getContext();
                apiContext = apiContext.replace(version + "/", "");
                envs.put(++index, envs, envURL + apiContext);
            }
            index++;
            appObj.put("environmentURLs", appObj, envs);
            myn.put(envCount, myn, appObj);
        }
    }
    envCount++;
    return envCount;
}

From source file:org.wso2.carbon.apimgt.impl.definitions.APIDefinitionFromOpenAPISpec.java

/**
 * This method returns URI templates according to the given swagger file
 *
 * @param api                 API/*from  w w w .j  ava  2  s.c  om*/
 * @param resourceConfigsJSON swaggerJSON
 * @return URI Templates
 * @throws APIManagementException
 */
@Override
public Set<URITemplate> getURITemplates(API api, String resourceConfigsJSON) throws APIManagementException {
    JSONParser parser = new JSONParser();
    JSONObject swagger;
    Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
    Set<Scope> scopes = getScopes(resourceConfigsJSON);
    try {
        swagger = (JSONObject) parser.parse(resourceConfigsJSON);
        if (swagger.get("paths") != null) {
            JSONObject paths = (JSONObject) swagger.get("paths");
            for (Object o : paths.keySet()) {
                String uriTempVal = (String) o;
                //if url template is a custom attribute "^x-" ignore.
                if (uriTempVal.startsWith("x-") || uriTempVal.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTempVal);
                // Following code check is done to handle $ref objects supported by swagger spec
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    log.info(
                            "Reference " + uriTempVal + " path object was ignored when generating URL template "
                                    + "for api \"" + api.getId().getApiName() + '\"');
                    continue;
                }

                boolean isHttpVerbDefined = false;

                for (Object o1 : path.keySet()) {
                    String httpVerb = (String) o1;

                    if (APIConstants.SWAGGER_SUMMARY.equals(httpVerb.toLowerCase())
                            || APIConstants.SWAGGER_DESCRIPTION.equals(httpVerb.toLowerCase())
                            || APIConstants.SWAGGER_SERVERS.equals(httpVerb.toLowerCase())
                            || APIConstants.PARAMETERS.equals(httpVerb.toLowerCase())
                            || httpVerb.startsWith("x-") || httpVerb.startsWith("X-")) {
                        // openapi 3.x allow 'summary', 'description' and extensions in PathItem Object.
                        // which we are not interested at this point
                        continue;
                    }
                    //Only continue for supported operations
                    else if (APIConstants.SUPPORTED_METHODS.contains(httpVerb.toLowerCase())) {
                        isHttpVerbDefined = true;
                        JSONObject operation = (JSONObject) path.get(httpVerb);
                        URITemplate template = new URITemplate();
                        Scope scope = APIUtil.findScopeByKey(scopes,
                                (String) operation.get(APIConstants.SWAGGER_X_SCOPE));
                        String authType = (String) operation.get(APIConstants.SWAGGER_X_AUTH_TYPE);
                        if ("Application & Application User".equals(authType)) {
                            authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                        } else if ("Application User".equals(authType)) {
                            authType = APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN;
                        } else if ("None".equals(authType)) {
                            authType = APIConstants.AUTH_NO_AUTHENTICATION;
                        } else if ("Application".equals(authType)) {
                            authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN;
                        } else {
                            authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                        }
                        template.setThrottlingTier(
                                (String) operation.get(APIConstants.SWAGGER_X_THROTTLING_TIER));
                        template.setThrottlingTiers(
                                (String) operation.get(APIConstants.SWAGGER_X_THROTTLING_TIER));
                        template.setMediationScript(
                                (String) operation.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT));
                        template.setMediationScripts(httpVerb.toUpperCase(),
                                (String) operation.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT));
                        template.setUriTemplate(uriTempVal);
                        template.setHTTPVerb(httpVerb.toUpperCase());
                        template.setHttpVerbs(httpVerb.toUpperCase());
                        template.setAuthType(authType);
                        template.setAuthTypes(authType);
                        template.setScope(scope);
                        template.setScopes(scope);

                        uriTemplates.add(template);
                    } else {
                        handleException("The HTTP method '" + httpVerb + "' provided for resource '"
                                + uriTempVal + "' is invalid");
                    }
                }

                if (!isHttpVerbDefined) {
                    handleException(
                            "Resource '" + uriTempVal + "' has global parameters without " + "HTTP methods");
                }
            }
        }
    } catch (ParseException e) {
        handleException("Invalid resource configuration ", e);
    }
    return uriTemplates;
}

From source file:org.wso2.carbon.apimgt.impl.definitions.APIDefinitionFromOpenAPISpec.java

/**
 * Called using the jaggery api. Checks if the swagger contains valid api scopes.
 *
 * @param swagger Swagger definition/*from   ww w .java 2  s.co  m*/
 * @return true if the scope definition is valid
 * @throws APIManagementException
 */
public Boolean validateScopesFromSwagger(String swagger) throws APIManagementException {

    try {
        Set<Scope> scopes = getScopes(swagger);
        JSONParser parser = new JSONParser();
        JSONObject swaggerJson;
        swaggerJson = (JSONObject) parser.parse(swagger);
        if (swaggerJson.get("paths") != null) {
            JSONObject paths = (JSONObject) swaggerJson.get("paths");
            for (Object uriTempKey : paths.keySet()) {
                String uriTemp = (String) uriTempKey;
                //if url template is a custom attribute "^x-" ignore.
                if (uriTemp.startsWith("x-") || uriTemp.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTemp);
                // Following code check is done to handle $ref objects supported by swagger spec
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    continue;
                }

                for (Object httpVerbKey : path.keySet()) {
                    String httpVerb = (String) httpVerbKey;
                    JSONObject operation = (JSONObject) path.get(httpVerb);
                    String operationScope = (String) operation.get(APIConstants.SWAGGER_X_SCOPE);

                    Scope scope = APIUtil.findScopeByKey(scopes, operationScope);

                    if (scope == null && operationScope != null) {
                        return false;
                    }
                }
            }
        }
        return true;
    } catch (APIManagementException e) {
        handleException("Error when validating scopes", e);
        return false;
    } catch (ParseException e) {
        handleException("Error when validating scopes", e);
        return false;
    }
}

From source file:org.wso2.carbon.apimgt.impl.definitions.APIDefinitionFromSwagger20.java

/**
 * This method returns URI templates according to the given swagger file
 *
 * @param api                 API//from ww  w  . j a  v  a2 s  . co m
 * @param resourceConfigsJSON swaggerJSON
 * @return URI Templates
 * @throws APIManagementException
 */
@Override
public Set<URITemplate> getURITemplates(API api, String resourceConfigsJSON) throws APIManagementException {
    JSONParser parser = new JSONParser();
    JSONObject swagger;
    Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
    Set<Scope> scopes = getScopes(resourceConfigsJSON);
    try {
        swagger = (JSONObject) parser.parse(resourceConfigsJSON);
        if (swagger.get("paths") != null) {
            JSONObject paths = (JSONObject) swagger.get("paths");
            for (Object o : paths.keySet()) {
                String uriTempVal = (String) o;
                //if url template is a custom attribute "^x-" ignore.
                if (uriTempVal.startsWith("x-") || uriTempVal.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTempVal);
                // Following code check is done to handle $ref objects supported by swagger spec
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    log.info(
                            "Reference " + uriTempVal + " path object was ignored when generating URL template "
                                    + "for api \"" + api.getId().getApiName() + '\"');
                    continue;
                }
                for (Object o1 : path.keySet()) {
                    String httpVerb = (String) o1;

                    //Only continue for supported operations
                    if (APIConstants.SUPPORTED_METHODS.contains(httpVerb.toLowerCase())) {
                        JSONObject operation = (JSONObject) path.get(httpVerb);
                        URITemplate template = new URITemplate();
                        Scope scope = APIUtil.findScopeByKey(scopes,
                                (String) operation.get(APIConstants.SWAGGER_X_SCOPE));
                        String authType = (String) operation.get(APIConstants.SWAGGER_X_AUTH_TYPE);
                        if ("Application & Application User".equals(authType)) {
                            authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                        } else if ("Application User".equals(authType)) {
                            authType = APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN;
                        } else if ("None".equals(authType)) {
                            authType = APIConstants.AUTH_NO_AUTHENTICATION;
                        } else if ("Application".equals(authType)) {
                            authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN;
                        } else {
                            authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
                        }
                        template.setThrottlingTier(
                                (String) operation.get(APIConstants.SWAGGER_X_THROTTLING_TIER));
                        template.setThrottlingTiers(
                                (String) operation.get(APIConstants.SWAGGER_X_THROTTLING_TIER));
                        template.setMediationScript(
                                (String) operation.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT));
                        template.setMediationScripts(httpVerb.toUpperCase(),
                                (String) operation.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT));
                        template.setUriTemplate(uriTempVal);
                        template.setHTTPVerb(httpVerb.toUpperCase());
                        template.setHttpVerbs(httpVerb.toUpperCase());
                        template.setAuthType(authType);
                        template.setAuthTypes(authType);
                        template.setScope(scope);
                        template.setScopes(scope);

                        uriTemplates.add(template);
                    }
                }
            }
        }
    } catch (ParseException e) {
        handleException("Invalid resource configuration ", e);
    }
    return uriTemplates;
}

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

/**
 * Updates the api sequences where user will be able to edits the generated sequences
 * <p>//from   w  ww.  j a  v  a2 s. co  m
 * Note: this method is directly invoked from the jaggery layer
 *
 * @param name     api name
 * @param version  api version
 * @param provider api provider
 * @param seqType  to identify the sequence is whether in/out sequence
 * @param content  sequence content
 * @throws APIManagementException throws exceptions on unsuccessful persistence in registry or json parsing of the content
 */
public static void updateRestToSoapConvertedSequences(String name, String version, String provider,
        String seqType, String content) throws APIManagementException {
    provider = (provider != null ? provider.trim() : null);
    name = (name != null ? name.trim() : null);
    version = (version != null ? version.trim() : null);

    boolean isTenantFlowStarted = false;

    JSONParser jsonParser = new JSONParser();
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
        int tenantId;
        UserRegistry registry;
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomain);
        APIUtil.loadTenantRegistry(tenantId);
        registry = registryService.getGovernanceSystemRegistry(tenantId);

        JSONObject sequences = (JSONObject) jsonParser.parse(content);
        for (Object sequence : sequences.keySet()) {
            String sequenceContent = (String) ((JSONObject) sequences.get(sequence)).get("content");
            String resourcePath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + provider
                    + RegistryConstants.PATH_SEPARATOR + name + RegistryConstants.PATH_SEPARATOR + version
                    + RegistryConstants.PATH_SEPARATOR + SOAPToRESTConstants.SOAP_TO_REST_RESOURCE
                    + RegistryConstants.PATH_SEPARATOR + seqType + RegistryConstants.PATH_SEPARATOR + sequence
                    + ".xml";

            Resource regResource;
            if (registry.resourceExists(resourcePath)) {
                regResource = registry.get(resourcePath);
                regResource.setContent(sequenceContent);
                if (log.isDebugEnabled()) {
                    log.debug("Api sequence content for " + resourcePath + " is: " + sequenceContent);
                }
                regResource.setMediaType("text/xml");
                registry.put(resourcePath, regResource);
            }
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing the sequence json", e);
    } catch (UserStoreException e) {
        handleException("Error while reading tenant information", e);
    } catch (RegistryException e) {
        handleException("Error when create registry instance", e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        handleException("Error while creating registry resource", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}

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 ava2 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.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//  ww  w .  j av a  2  s  .c  o m
 * @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.rest.api.publisher.v1.utils.mappings.APIMappingUtil.java

/**
 * This method creates the API monetization information DTO
 *
 * @param apiIdentifier API identifier//  w ww  .j  ava 2s . c  o m
 * @return monetization information DTO
 * @throws APIManagementException if failed to construct the DTO
 */
public static APIMonetizationInfoDTO getMonetizationInfoDTO(APIIdentifier apiIdentifier)
        throws APIManagementException {

    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    API api = apiProvider.getAPI(apiIdentifier);
    APIMonetizationInfoDTO apiMonetizationInfoDTO = new APIMonetizationInfoDTO();
    //set the information relatated to monetization to the DTO
    apiMonetizationInfoDTO.setEnabled(api.getMonetizationStatus());
    Map<String, String> monetizationPropertiesMap = new HashMap<>();

    if (api.getMonetizationProperties() != null) {
        JSONObject monetizationProperties = api.getMonetizationProperties();
        for (Object propertyKey : monetizationProperties.keySet()) {
            String key = (String) propertyKey;
            monetizationPropertiesMap.put(key, (String) monetizationProperties.get(key));
        }
    }
    apiMonetizationInfoDTO.setProperties(monetizationPropertiesMap);
    return apiMonetizationInfoDTO;
}

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

public static APIDTO fromAPItoDTO(API model) throws APIManagementException {

    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();

    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getApiName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUUID());// www  .  j  a v  a2s  .c  o  m
    String context = model.getContextTemplate();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    dto.setContext(context);
    dto.setDescription(model.getDescription());

    dto.setIsDefaultVersion(model.isDefaultVersion());
    dto.setResponseCaching(model.getResponseCache());
    dto.setCacheTimeout(model.getCacheTimeout());
    try {
        dto.setEndpoint(getAPIEndpointDTO(model));
    } catch (ParseException e) {
        //logs the error and continues as this is not a blocker
        log.error("Cannot convert endpoint configurations when setting endpoint for API +" + "API ID = "
                + model.getId(), e);
    }
    /*  if (!StringUtils.isBlank(model.getThumbnailUrl())) {todo
    dto.setThumbnailUri(getThumbnailUri(model.getUUID()));
      }*/
    /*        List<SequenceDTO> sequences = new ArrayList<>();todo
            
            String inSequenceName = model.getInSequence();
            if (inSequenceName != null && !inSequenceName.isEmpty()) {
    String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN;
    boolean sharedStatus = getSharedStatus(inSequenceName,type,dto);
    String uuid = getSequenceId(inSequenceName,type,dto);
    SequenceDTO inSequence = new SequenceDTO();
    inSequence.setName(inSequenceName);
    inSequence.setType(type);
    inSequence.setShared(sharedStatus);
    inSequence.setId(uuid);
    sequences.add(inSequence);
            }
            
            String outSequenceName = model.getOutSequence();
            if (outSequenceName != null && !outSequenceName.isEmpty()) {
    String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT;
    boolean sharedStatus = getSharedStatus(outSequenceName,type,dto);
    String uuid = getSequenceId(outSequenceName,type,dto);
    SequenceDTO outSequence = new SequenceDTO();
    outSequence.setName(outSequenceName);
    outSequence.setType(type);
    outSequence.setShared(sharedStatus);
    outSequence.setId(uuid);
    sequences.add(outSequence);
            }
            
            String faultSequenceName = model.getFaultSequence();
            if (faultSequenceName != null && !faultSequenceName.isEmpty()) {
    String type = APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT;
    boolean sharedStatus = getSharedStatus(faultSequenceName,type,dto);
    String uuid = getSequenceId(faultSequenceName,type,dto);
    SequenceDTO faultSequence = new SequenceDTO();
    faultSequence.setName(faultSequenceName);
    faultSequence.setType(type);
    faultSequence.setShared(sharedStatus);
    faultSequence.setId(uuid);
    sequences.add(faultSequence);
            }
            
            dto.setSequences(sequences);*/

    dto.setLifeCycleStatus(model.getStatus());

    String subscriptionAvailability = model.getSubscriptionAvailability();
    if (subscriptionAvailability != null) {
        dto.setSubscriptionAvailability(mapSubscriptionAvailabilityFromAPItoDTO(subscriptionAvailability));
    }

    if (model.getSubscriptionAvailableTenants() != null) {
        dto.setSubscriptionAvailableTenants(Arrays.asList(model.getSubscriptionAvailableTenants().split(",")));
    }

    //Get Swagger definition which has URL templates, scopes and resource details
    String apiSwaggerDefinition = apiProvider.getOpenAPIDefinition(model.getId());
    List<APIOperationsDTO> operationsDTOs = getOperationsFromSwaggerDef(model, apiSwaggerDefinition);
    dto.setOperations(operationsDTOs);

    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);

    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<String> tiersToReturn = new ArrayList<>();
    for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
        tiersToReturn.add(tier.getName());
    }
    dto.setPolicies(tiersToReturn);
    dto.setApiThrottlingPolicy(model.getApiLevelPolicy());

    //APIs created with type set to "NULL" will be considered as "HTTP"
    if (model.getType() == null || model.getType().toLowerCase().equals("null")) {
        dto.setType(APIDTO.TypeEnum.HTTP);
    } else {
        dto.setType(APIDTO.TypeEnum.fromValue(model.getType()));
    }

    if (!APIConstants.APIType.WS.toString().equals(model.getType())) {
        if (StringUtils.isEmpty(model.getTransports())) {
            List<String> transports = new ArrayList<>();
            transports.add(APIConstants.HTTPS_PROTOCOL);

            dto.setTransport(transports);
        }
        dto.setTransport(Arrays.asList(model.getTransports().split(",")));
    }
    if (StringUtils.isEmpty(model.getTransports())) {
        dto.setVisibility(APIDTO.VisibilityEnum.PUBLIC);
    }
    dto.setVisibility(mapVisibilityFromAPItoDTO(model.getVisibility()));

    if (model.getVisibleRoles() != null) {
        dto.setVisibleRoles(Arrays.asList(model.getVisibleRoles().split(",")));
    }

    if (model.getVisibleTenants() != null) {
        dto.setVisibleRoles(Arrays.asList(model.getVisibleTenants().split(",")));
    }

    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        Map<String, String> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            String key = (String) propertyKey;
            additionalPropertiesMap.put(key, (String) additionalProperties.get(key));
        }
        dto.setAdditionalProperties(additionalPropertiesMap);
    }

    dto.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY.equals(model.getAccessControl())
            ? APIDTO.AccessControlEnum.RESTRICTED
            : APIDTO.AccessControlEnum.NONE);
    if (model.getAccessControlRoles() != null) {
        dto.setAccessControlRoles(Arrays.asList(model.getAccessControlRoles().split(",")));
    }
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    List<String> environmentsList = new ArrayList<String>();
    environmentsList.addAll(model.getEnvironments());
    dto.setGatewayEnvironments(environmentsList);
    APICorsConfigurationDTO apiCorsConfigurationDTO = new APICorsConfigurationDTO();
    CORSConfiguration corsConfiguration = model.getCorsConfiguration();
    if (corsConfiguration == null) {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAccessControlAllowOrigins());
    apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAccessControlAllowHeaders());
    apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAccessControlAllowMethods());
    apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isCorsConfigurationEnabled());
    apiCorsConfigurationDTO
            .setAccessControlAllowCredentials(corsConfiguration.isAccessControlAllowCredentials());
    dto.setCorsConfiguration(apiCorsConfigurationDTO);
    dto.setWsdlUri(model.getWsdlUrl());
    setEndpointSecurityFromModelToApiDTO(model, dto);
    setMaxTpsFromModelToApiDTO(model, dto);

    //setting micro-gateway labels if there are any
    if (model.getGatewayLabels() != null) {
        List<LabelDTO> labels = new ArrayList<>();
        List<Label> gatewayLabels = model.getGatewayLabels();
        for (Label label : gatewayLabels) {
            LabelDTO labelDTO = new LabelDTO();
            labelDTO.setName(label.getName());
            labelDTO.setAccessUrls(label.getAccessUrls());
            labelDTO.setDescription(label.getDescription());
            labels.add(labelDTO);
        }
        dto.setLabels(labels);
    }
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    if (model.getApiSecurity() != null) {
        dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
    }
    return dto;
}

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

public static APIDTO fromAPItoDTO(API model, String tenantDomain) throws APIManagementException {

    APIConsumer apiConsumer = RestApiUtil.getLoggedInUserConsumer();

    APIDTO dto = new APIDTO();
    dto.setName(model.getId().getApiName());
    dto.setVersion(model.getId().getVersion());
    String providerName = model.getId().getProviderName();
    dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    dto.setId(model.getUUID());//from w  w  w .j a v a  2 s  . c  o  m
    dto.setContext(model.getContext());
    dto.setDescription(model.getDescription());
    dto.setIsDefaultVersion(model.isDefaultVersion());
    dto.setStatus(model.getStatus());

    if (null != model.getLastUpdated()) {
        Date lastUpdateDate = model.getLastUpdated();
        Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
        dto.setLastUpdatedTime(String.valueOf(timeStamp));
    }

    String createdTimeStamp = model.getCreatedTime();
    if (null != createdTimeStamp) {
        Date date = new Date(Long.valueOf(createdTimeStamp));
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dateFormatted = formatter.format(date);
        dto.setCreatedTime(dateFormatted);
    }

    //Get Swagger definition which has URL templates, scopes and resource details
    String apiSwaggerDefinition = null;

    if (!APIConstants.APIType.WS.toString().equals(model.getType())) {
        apiSwaggerDefinition = apiConsumer.getOpenAPIDefinition(model.getId());
        if (apiSwaggerDefinition != null) {
            apiSwaggerDefinition = APIUtil.removeXMediationScriptsFromSwagger(apiSwaggerDefinition);
        }
    }
    dto.setApiDefinition(apiSwaggerDefinition);

    Set<String> apiTags = model.getTags();
    List<String> tagsToReturn = new ArrayList<>();
    tagsToReturn.addAll(apiTags);
    dto.setTags(tagsToReturn);

    Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
    List<String> tiersToReturn = new ArrayList<>();
    for (org.wso2.carbon.apimgt.api.model.Tier tier : apiTiers) {
        tiersToReturn.add(tier.getName());
    }
    dto.setTiers(tiersToReturn);

    dto.setTransport(Arrays.asList(model.getTransports().split(",")));

    dto.setEndpointURLs(extractEnpointURLs(model, tenantDomain));

    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
    dto.setBusinessInformation(apiBusinessInformationDTO);
    if (!StringUtils.isBlank(model.getThumbnailUrl())) {
        dto.setThumbnailUrl(getThumbnailUri(model.getUUID()));
    }
    if (model.getAdditionalProperties() != null) {
        JSONObject additionalProperties = model.getAdditionalProperties();
        Map<String, String> additionalPropertiesMap = new HashMap<>();
        for (Object propertyKey : additionalProperties.keySet()) {
            String key = (String) propertyKey;
            additionalPropertiesMap.put(key, (String) additionalProperties.get(key));
        }
        dto.setAdditionalProperties(additionalPropertiesMap);
    }
    dto.setWsdlUri(model.getWsdlUrl());

    //setting micro-gateway labels if there are any
    if (model.getGatewayLabels() != null) {
        List<LabelDTO> labels = new ArrayList<>();
        List<Label> gatewayLabels = model.getGatewayLabels();
        for (Label label : gatewayLabels) {
            LabelDTO labelDTO = new LabelDTO();
            labelDTO.setName(label.getName());
            labelDTO.setAccessUrls(label.getAccessUrls());
            labels.add(labelDTO);
        }
        dto.setLabels(labels);
    }

    //setting environment list configured with non empty endpoint URLs
    if (model.getEnvironmentList() != null) {
        List<String> environmentListToReturn = new ArrayList<>();
        environmentListToReturn.addAll(model.getEnvironmentList());
        dto.setEnvironmentList(environmentListToReturn);
    }
    dto.setAuthorizationHeader(model.getAuthorizationHeader());
    dto.setApiSecurity(model.getApiSecurity());
    return dto;
}