Search in sources :

Example 16 with Mediation

use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.

the class APIProviderImpl method createNewAPIVersion.

public API createNewAPIVersion(String existingApiId, String newVersion, Boolean isDefaultVersion, String organization) throws APIManagementException {
    API existingAPI = getAPIbyUUID(existingApiId, organization);
    if (existingAPI == null) {
        throw new APIMgtResourceNotFoundException("API not found for id " + existingApiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, existingApiId));
    }
    if (newVersion.equals(existingAPI.getId().getVersion())) {
        throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName());
    }
    existingAPI.setOrganization(organization);
    APIIdentifier existingAPIId = existingAPI.getId();
    String existingAPICreatedTime = existingAPI.getCreatedTime();
    String existingAPIStatus = existingAPI.getStatus();
    boolean isExsitingAPIdefaultVersion = existingAPI.isDefaultVersion();
    String existingContext = existingAPI.getContext();
    String existingVersionTimestamp = existingAPI.getVersionTimestamp();
    APIIdentifier newApiId = new APIIdentifier(existingAPI.getId().getProviderName(), existingAPI.getId().getApiName(), newVersion);
    existingAPI.setUuid(null);
    existingAPI.setId(newApiId);
    existingAPI.setStatus(APIConstants.CREATED);
    existingAPI.setDefaultVersion(isDefaultVersion);
    existingAPI.setVersionTimestamp("");
    // We need to change the context by setting the new version
    // This is a change that is coming with the context version strategy
    String existingAPIContextTemplate = existingAPI.getContextTemplate();
    existingAPI.setContext(existingAPIContextTemplate.replace("{version}", newVersion));
    Map<String, List<OperationPolicy>> operationPoliciesMap = extractAndDropOperationPoliciesFromURITemplate(existingAPI.getUriTemplates());
    API newAPI = addAPI(existingAPI);
    String newAPIId = newAPI.getUuid();
    if (!operationPoliciesMap.isEmpty()) {
        // clone common or API specific operation policy.
        Map<String, String> clonedOperationPolicyMap = cloneOperationPoliciesToAPI(existingApiId, newAPI, operationPoliciesMap);
        // attach policy to uri template.
        attachOperationPoliciesToAPI(newAPI, clonedOperationPolicyMap, operationPoliciesMap);
    }
    // copy docs
    List<Documentation> existingDocs = getAllDocumentation(existingApiId, organization);
    if (existingDocs != null) {
        for (Documentation documentation : existingDocs) {
            Documentation newDoc = addDocumentation(newAPIId, documentation, organization);
            DocumentationContent content = getDocumentationContent(existingApiId, documentation.getId(), // TODO see whether we can optimize this
            organization);
            if (content != null) {
                addDocumentationContent(newAPIId, newDoc.getId(), organization, content);
            }
        }
    }
    // copy icon
    ResourceFile icon = getIcon(existingApiId, organization);
    if (icon != null) {
        setThumbnailToAPI(newAPIId, icon, organization);
    }
    // copy sequences
    List<Mediation> mediationPolicies = getAllApiSpecificMediationPolicies(existingApiId, organization);
    if (mediationPolicies != null) {
        for (Mediation mediation : mediationPolicies) {
            Mediation policy = getApiSpecificMediationPolicyByPolicyId(existingApiId, mediation.getUuid(), organization);
            addApiSpecificMediationPolicy(newAPIId, policy, organization);
        }
    }
    // copy wsdl
    if (!APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType()) && existingAPI.getWsdlUrl() != null) {
        ResourceFile wsdl = getWSDL(existingApiId, organization);
        if (wsdl != null) {
            addWSDLResource(newAPIId, wsdl, null, organization);
        }
    }
    // copy graphql definition
    String graphQLSchema = getGraphqlSchemaDefinition(existingApiId, organization);
    if (graphQLSchema != null) {
        saveGraphqlSchemaDefinition(newAPIId, graphQLSchema, organization);
    }
    // update old api
    // revert back to old values before update.
    existingAPI.setUuid(existingApiId);
    existingAPI.setStatus(existingAPIStatus);
    existingAPI.setId(existingAPIId);
    existingAPI.setContext(existingContext);
    existingAPI.setCreatedTime(existingAPICreatedTime);
    // update existing api with the original timestamp
    existingAPI.setVersionTimestamp(existingVersionTimestamp);
    if (isDefaultVersion) {
        existingAPI.setDefaultVersion(false);
    } else {
        existingAPI.setDefaultVersion(isExsitingAPIdefaultVersion);
    }
    try {
        apiPersistenceInstance.updateAPI(new Organization(organization), APIMapper.INSTANCE.toPublisherApi(existingAPI));
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while updating API details", e);
    }
    return getAPIbyUUID(newAPIId, organization);
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ArrayList(java.util.ArrayList) List(java.util.List)

Example 17 with Mediation

use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.

the class APIProviderImpl method addApiSpecificMediationPolicy.

@Override
public Mediation addApiSpecificMediationPolicy(String apiId, Mediation mediationPolicy, String organization) throws APIManagementException {
    if (StringUtils.isNotBlank(mediationPolicy.getName()) && mediationPolicy.getName().length() > APIConstants.MAX_LENGTH_MEDIATION_POLICY_NAME) {
        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.MEDIATION_POLICY_NAME_TOO_LONG, APIConstants.MAX_LENGTH_MEDIATION_POLICY_NAME + ""));
    }
    try {
        org.wso2.carbon.apimgt.persistence.dto.Mediation mappedPolicy = new org.wso2.carbon.apimgt.persistence.dto.Mediation();
        mappedPolicy.setConfig(mediationPolicy.getConfig());
        mappedPolicy.setName(mediationPolicy.getName());
        mappedPolicy.setType(mediationPolicy.getType());
        org.wso2.carbon.apimgt.persistence.dto.Mediation returnedMappedPolicy = apiPersistenceInstance.addMediationPolicy(new Organization(organization), apiId, mappedPolicy);
        if (returnedMappedPolicy != null) {
            mediationPolicy.setUuid(returnedMappedPolicy.getId());
            return mediationPolicy;
        }
    } catch (MediationPolicyPersistenceException e) {
        if (e.getErrorHandler() == ExceptionCodes.API_NOT_FOUND) {
            throw new APIMgtResourceNotFoundException(e);
        } else if (e.getErrorHandler() == ExceptionCodes.MEDIATION_POLICY_API_ALREADY_EXISTS) {
            throw new APIManagementException(ExceptionCodes.MEDIATION_POLICY_API_ALREADY_EXISTS);
        } else {
            throw new APIManagementException("Error while saving mediation policy ", e);
        }
    }
    return null;
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) Mediation(org.wso2.carbon.apimgt.api.model.Mediation)

Example 18 with Mediation

use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.

the class XMLSchemaValidator method mediate.

/**
 * This mediate method validates the xml request message.
 *
 * @param messageContext This message context contains the request message properties of the relevant
 *                       API which was enabled the XML_Validator message mediation in flow.
 * @return A boolean value.True if successful and false if not.
 */
public boolean mediate(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.debug("XML validation mediator is activated...");
    }
    InputStream inputStreamSchema;
    InputStream inputStreamXml;
    Map<String, InputStream> inputStreams = null;
    Boolean xmlValidationStatus;
    Boolean schemaValidationStatus;
    APIMThreatAnalyzer apimThreatAnalyzer = null;
    String apiContext;
    String requestMethod;
    String contentType;
    boolean validRequest = true;
    org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    requestMethod = axis2MC.getProperty(ThreatProtectorConstants.HTTP_REQUEST_METHOD).toString();
    Object contentTypeObject = axis2MC.getProperty(ThreatProtectorConstants.CONTENT_TYPE);
    if (contentTypeObject != null) {
        contentType = contentTypeObject.toString();
    } else {
        contentType = axis2MC.getProperty(ThreatProtectorConstants.SOAP_CONTENT_TYPE).toString();
    }
    apiContext = messageContext.getProperty(ThreatProtectorConstants.API_CONTEXT).toString();
    if (!APIConstants.SupportedHTTPVerbs.GET.name().equalsIgnoreCase(requestMethod) && (ThreatProtectorConstants.APPLICATION_XML.equals(contentType) || ThreatProtectorConstants.TEXT_XML.equals(contentType))) {
        try {
            inputStreams = GatewayUtils.cloneRequestMessage(messageContext);
            if (inputStreams != null) {
                Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XML_VALIDATION);
                if (messageProperty != null) {
                    xmlValidationStatus = Boolean.valueOf(messageProperty.toString());
                    if (xmlValidationStatus.equals(true)) {
                        XMLConfig xmlConfig = configureSchemaProperties(messageContext);
                        ConfigurationHolder.addXmlConfig(xmlConfig);
                        apimThreatAnalyzer = AnalyzerHolder.getAnalyzer(contentType);
                        inputStreamXml = inputStreams.get(ThreatProtectorConstants.XML);
                        apimThreatAnalyzer.analyze(inputStreamXml, apiContext);
                    }
                }
                messageProperty = messageContext.getProperty(APIMgtGatewayConstants.SCHEMA_VALIDATION);
                if (messageProperty != null) {
                    schemaValidationStatus = Boolean.valueOf(messageProperty.toString());
                    if (schemaValidationStatus.equals(true)) {
                        inputStreamSchema = inputStreams.get(ThreatProtectorConstants.SCHEMA);
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamSchema);
                        validateSchema(messageContext, bufferedInputStream);
                    }
                }
            }
        } catch (APIMThreatAnalyzerException e) {
            validRequest = false;
            logger.error(APIMgtGatewayConstants.BAD_REQUEST, e);
            GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, e.getMessage());
        } catch (IOException e) {
            logger.error(APIMgtGatewayConstants.BAD_REQUEST, e);
            GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, e.getMessage());
        }
        // return analyzer to the pool
        AnalyzerHolder.returnObject(apimThreatAnalyzer);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("XML Schema Validator: " + APIMgtGatewayConstants.REQUEST_TYPE_FAIL_MSG);
        }
    }
    GatewayUtils.setOriginalInputStream(inputStreams, axis2MC);
    if (validRequest) {
        try {
            RelayUtils.buildMessage(axis2MC);
        } catch (IOException | XMLStreamException e) {
            logger.error("Error occurred while parsing the payload.", e);
            GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE, e.getMessage());
        }
    }
    return true;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) XMLConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.XMLConfig) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) APIMThreatAnalyzer(org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 19 with Mediation

use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.

the class XMLSchemaValidator method validateSchema.

/**
 * This method validates the request payload xml with the relevant xsd.
 *
 * @param messageContext      This message context contains the request message properties of the relevant
 *                            API which was enabled the XML_Validator message mediation in flow.
 * @param bufferedInputStream Buffered input stream to be validated.
 * @throws APIMThreatAnalyzerException Exception might be occurred while parsing the xml payload.
 */
private boolean validateSchema(MessageContext messageContext, BufferedInputStream bufferedInputStream) throws APIMThreatAnalyzerException {
    String xsdURL;
    Schema schema;
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Object messageProperty = messageContext.getProperty(APIMgtGatewayConstants.XSD_URL);
        if (messageProperty == null) {
            return true;
        } else {
            if (String.valueOf(messageProperty).isEmpty()) {
                return true;
            } else {
                xsdURL = String.valueOf(messageProperty);
                URL schemaFile = new URL(xsdURL);
                schema = schemaFactory.newSchema(schemaFile);
                Source xmlFile = new StreamSource(bufferedInputStream);
                Validator validator = schema.newValidator();
                validator.validate(xmlFile);
            }
        }
    } catch (SAXException | IOException e) {
        throw new APIMThreatAnalyzerException("Error occurred while parsing XML payload : " + e);
    }
    return true;
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) URL(java.net.URL) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Validator(javax.xml.validation.Validator) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException) SAXException(org.xml.sax.SAXException)

Example 20 with Mediation

use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.

the class JsonSchemaValidator method configureSchemaProperties.

/**
 * This method binds the properties of the json validator sequence with the JsonConfig object.
 *
 * @param messageContext This message context contains the request message properties of the relevant
 *                       API which was enabled the JSON_Validator message mediation in flow.
 * @return JSONConfig contains the json schema properties need to be validated.
 */
public JSONConfig configureSchemaProperties(MessageContext messageContext) {
    Object messageProperty;
    int propertyCount = 0;
    int stringLength = 0;
    int arrayElementCount = 0;
    int keyLength = 0;
    int maxJSONDepth = 0;
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_PROPERTY_COUNT);
    if (messageProperty != null) {
        propertyCount = Integer.parseInt(messageProperty.toString());
    } else {
        String errorMessage = "Json schema maxProperty count is missing.";
        ThreatExceptionHandler.handleException(messageContext, errorMessage);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_STRING_LENGTH);
    if (messageProperty != null) {
        stringLength = Integer.parseInt(messageProperty.toString());
    } else {
        String errorMessage = "Json schema Max String length is missing";
        ThreatExceptionHandler.handleException(messageContext, errorMessage);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_ARRAY_ELEMENT_COUNT);
    if (messageProperty != null) {
        arrayElementCount = Integer.parseInt(messageProperty.toString());
    } else {
        String errorMessage = "Json schema max array element count is missing";
        ThreatExceptionHandler.handleException(messageContext, errorMessage);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_KEY_LENGTH);
    if (messageProperty != null) {
        keyLength = Integer.parseInt(messageProperty.toString());
    } else {
        String errorMessage = "Json schema maximum key length is missing";
        ThreatExceptionHandler.handleException(messageContext, errorMessage);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_JSON_DEPTH);
    if (messageProperty != null) {
        maxJSONDepth = Integer.parseInt(messageProperty.toString());
    } else {
        String errorMessage = "Json schema maximum JSON depth is missing";
        ThreatExceptionHandler.handleException(messageContext, errorMessage);
    }
    if (logger.isDebugEnabled()) {
        logger.debug(("Max Priority count is:" + propertyCount) + ", " + "Max String length is: " + stringLength + ", " + "Max Array element count: " + arrayElementCount + ", " + "Max Key Length: " + keyLength + ", " + "Max JSON depth is:" + maxJSONDepth + ", ");
    }
    JSONConfig jsonConfig = new JSONConfig();
    jsonConfig.setMaxPropertyCount(propertyCount);
    jsonConfig.setMaxStringLength(stringLength);
    jsonConfig.setMaxArrayElementCount(arrayElementCount);
    jsonConfig.setMaxKeyLength(keyLength);
    jsonConfig.setMaxJsonDepth(maxJSONDepth);
    return jsonConfig;
}
Also used : JSONConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.JSONConfig)

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