Search in sources :

Example 6 with Mediation

use of org.wso2.carbon.apimgt.api.model.Mediation in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method addMediationPolicy.

@Override
public Mediation addMediationPolicy(Organization org, String apiId, Mediation mediation) throws MediationPolicyPersistenceException {
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        BasicAPI api = getbasicAPIInfo(apiId, registry);
        if (api == null) {
            throw new MediationPolicyPersistenceException("API not foud ", ExceptionCodes.API_NOT_FOUND);
        }
        String resourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + api.apiProvider + RegistryConstants.PATH_SEPARATOR + api.apiName + RegistryConstants.PATH_SEPARATOR + api.apiVersion + RegistryConstants.PATH_SEPARATOR + mediation.getType() + RegistryConstants.PATH_SEPARATOR + mediation.getName();
        if (registry.resourceExists(resourcePath)) {
            throw new MediationPolicyPersistenceException("Mediation policy already exists for the given name " + mediation.getName(), ExceptionCodes.MEDIATION_POLICY_API_ALREADY_EXISTS);
        }
        Resource policy = registry.newResource();
        policy.setContent(mediation.getConfig());
        policy.setMediaType("application/xml");
        registry.put(resourcePath, policy);
        mediation.setId(policy.getUUID());
        return mediation;
    } catch (RegistryException | APIPersistenceException e) {
        String msg = "Error while adding the mediation to the registry";
        throw new MediationPolicyPersistenceException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 7 with Mediation

use of org.wso2.carbon.apimgt.api.model.Mediation in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method getMediationPolicy.

@Override
public Mediation getMediationPolicy(Organization org, String apiId, String mediationPolicyId) throws MediationPolicyPersistenceException {
    boolean isTenantFlowStarted = false;
    Mediation mediation = null;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        BasicAPI api = getbasicAPIInfo(apiId, registry);
        if (api == null) {
            throw new MediationPolicyPersistenceException("API not foud ", ExceptionCodes.API_NOT_FOUND);
        }
        String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
        int prependIndex = apiPath.lastIndexOf("/api");
        String apiResourcePath = apiPath.substring(0, prependIndex);
        String policyPath = GovernanceUtils.getArtifactPath(registry, mediationPolicyId);
        if (!policyPath.startsWith(apiResourcePath)) {
            throw new MediationPolicyPersistenceException("Policy not foud ", ExceptionCodes.POLICY_NOT_FOUND);
        }
        Resource mediationResource = registry.get(policyPath);
        if (mediationResource != null) {
            String contentString = IOUtils.toString(mediationResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
            // Extracting name specified in the mediation config
            OMElement omElement = AXIOMUtil.stringToOM(contentString);
            OMAttribute attribute = omElement.getAttribute(new QName("name"));
            String mediationPolicyName = attribute.getAttributeValue();
            String[] path = policyPath.split(RegistryConstants.PATH_SEPARATOR);
            String resourceType = path[(path.length - 2)];
            mediation = new Mediation();
            mediation.setConfig(contentString);
            mediation.setType(resourceType);
            mediation.setId(mediationResource.getUUID());
            mediation.setName(mediationPolicyName);
        }
    } catch (RegistryException | APIPersistenceException | IOException | XMLStreamException e) {
        String msg = "Error occurred  while getting Api Specific mediation policies ";
        throw new MediationPolicyPersistenceException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return mediation;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) OMElement(org.apache.axiom.om.OMElement) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) IOException(java.io.IOException) Mediation(org.wso2.carbon.apimgt.persistence.dto.Mediation) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) XMLStreamException(javax.xml.stream.XMLStreamException) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 8 with Mediation

use of org.wso2.carbon.apimgt.api.model.Mediation in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method deleteMediationPolicy.

@Override
public void deleteMediationPolicy(Organization org, String apiId, String mediationPolicyId) throws MediationPolicyPersistenceException {
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        BasicAPI api = getbasicAPIInfo(apiId, registry);
        if (api == null) {
            throw new MediationPolicyPersistenceException("API not foud ", ExceptionCodes.API_NOT_FOUND);
        }
        String apiResourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + api.apiProvider + RegistryConstants.PATH_SEPARATOR + api.apiName + RegistryConstants.PATH_SEPARATOR + api.apiVersion;
        String policyPath = GovernanceUtils.getArtifactPath(registry, mediationPolicyId);
        if (!policyPath.startsWith(apiResourcePath)) {
            throw new MediationPolicyPersistenceException("Policy not foud ", ExceptionCodes.POLICY_NOT_FOUND);
        }
        if (registry.resourceExists(policyPath)) {
            registry.delete(policyPath);
        }
    } catch (RegistryException | APIPersistenceException e) {
        String msg = "Error occurred  while getting Api Specific mediation policies ";
        throw new MediationPolicyPersistenceException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 9 with Mediation

use of org.wso2.carbon.apimgt.api.model.Mediation in project carbon-apimgt by wso2.

the class OAS3Parser method generateExample.

/**
 * This method  generates Sample/Mock payloads for Open API Specification (3.0) definitions
 *
 * @param apiDefinition API Definition
 * @return swagger Json
 */
@Override
public Map<String, Object> generateExample(String apiDefinition) throws APIManagementException {
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(apiDefinition, null, null);
    if (CollectionUtils.isNotEmpty(parseAttemptForV3.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    OpenAPI swagger = parseAttemptForV3.getOpenAPI();
    // return map
    Map<String, Object> returnMap = new HashMap<>();
    // List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, PathItem> entry : swagger.getPaths().entrySet()) {
        int minResponseCode = 0;
        int responseCode = 0;
        String path = entry.getKey();
        Map<String, Schema> definitions = swagger.getComponents().getSchemas();
        // operation map to get verb
        Map<PathItem.HttpMethod, Operation> operationMap = entry.getValue().readOperationsMap();
        List<Operation> operations = swagger.getPaths().get(path).readOperations();
        for (int i = 0, operationsSize = operations.size(); i < operationsSize; i++) {
            Operation op = operations.get(i);
            // initializing apiResourceMediationPolicyObject
            APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
            // setting path for apiResourceMediationPolicyObject
            apiResourceMediationPolicyObject.setPath(path);
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            // for each HTTP method get the verb
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            // for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            Object[] operationsArray = operationMap.entrySet().toArray();
            if (operationsArray.length > i) {
                Map.Entry<PathItem.HttpMethod, Operation> operationEntry = (Map.Entry<PathItem.HttpMethod, Operation>) operationsArray[i];
                apiResourceMediationPolicyObject.setVerb(String.valueOf(operationEntry.getKey()));
            } else {
                throw new APIManagementException("Cannot find the HTTP method for the API Resource Mediation Policy");
            }
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                Content content = op.getResponses().get(responseEntry).getContent();
                if (content != null) {
                    MediaType applicationJson = content.get(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
                    MediaType applicationXml = content.get(APIConstants.APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        Schema jsonSchema = applicationJson.getSchema();
                        if (jsonSchema != null) {
                            String jsonExample = getJsonExample(jsonSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                            respCodeInitialized = true;
                            hasJsonPayload = true;
                        }
                    }
                    if (applicationXml != null) {
                        Schema xmlSchema = applicationXml.getSchema();
                        if (xmlSchema != null) {
                            String xmlExample = getXmlExample(xmlSchema, definitions);
                            genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                            hasXmlPayload = true;
                        }
                    }
                } else {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            // inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            // gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            // sets script to each resource in the swagger
            op.addExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
        }
        checkAndSetEmptyScope(swagger);
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathItem(io.swagger.v3.oas.models.PathItem) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MediaType(io.swagger.v3.oas.models.media.MediaType) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Content(io.swagger.v3.oas.models.media.Content) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 10 with Mediation

use of org.wso2.carbon.apimgt.api.model.Mediation in project carbon-apimgt by wso2.

the class PoliciesApiServiceImpl method policiesMediationMediationPolicyIdGet.

/**
 * Returns a specific global mediation policy by identifier
 *
 * @param mediationPolicyId Mediation policy uuid
 * @param accept            Accept header value
 * @return returns the matched mediation
 */
@Override
public Response policiesMediationMediationPolicyIdGet(String mediationPolicyId, String accept, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // Get given global mediation policy
        Mediation mediation = apiProvider.getGlobalMediationPolicy(mediationPolicyId);
        if (mediation != null) {
            MediationDTO mediationDTO = MediationMappingUtil.fromMediationToDTO(mediation);
            return Response.ok().entity(mediationDTO).build();
        } else {
            // If global mediation policy not exists
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving the global mediation policy with id " + mediationPolicyId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MediationDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.MediationDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Mediation(org.wso2.carbon.apimgt.api.model.Mediation)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)35 Mediation (org.wso2.carbon.apimgt.api.model.Mediation)23 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)22 IOException (java.io.IOException)21 Resource (org.wso2.carbon.registry.core.Resource)19 XMLStreamException (javax.xml.stream.XMLStreamException)12 QName (javax.xml.namespace.QName)11 OMElement (org.apache.axiom.om.OMElement)11 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)11 MediationPolicyPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException)11 InputStream (java.io.InputStream)10 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)10 ArrayList (java.util.ArrayList)9 Collection (org.wso2.carbon.registry.core.Collection)9 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)8 OMAttribute (org.apache.axiom.om.OMAttribute)7 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)6 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)6 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)6 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)6