Search in sources :

Example 26 with Mediation

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

the class MediationPoliciesApiServiceImpl method getGlobalMediationPolicyContent.

/**
 * Returns content of a global Mediation policy
 *
 * @param mediationPolicyId       search condition
 * @param ifNoneMatch If-None-Match header value
 * @return Matched global mediation policies for given search condition
 */
@Override
public Response getGlobalMediationPolicyContent(String mediationPolicyId, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    try {
        // Get registry resource correspond to identifier
        Resource mediationResource = apiProvider.getCustomMediationResourceFromUuid(mediationPolicyId);
        if (mediationResource != null) {
            // get the registry resource path
            String resource = mediationResource.getPath();
            resource = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + resource;
            Map<String, Object> mediationPolicyResourceMap = APIUtil.getDocument(username, resource, tenantDomain);
            Object fileDataStream = mediationPolicyResourceMap.get(APIConstants.DOCUMENTATION_RESOURCE_MAP_DATA);
            Object contentType = mediationPolicyResourceMap.get(APIConstants.DOCUMENTATION_RESOURCE_MAP_CONTENT_TYPE);
            contentType = contentType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : contentType;
            String name = mediationPolicyResourceMap.get(APIConstants.DOCUMENTATION_RESOURCE_MAP_NAME).toString();
            return Response.ok(fileDataStream).header(RestApiConstants.HEADER_CONTENT_TYPE, contentType).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"").build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving global mediation policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
        return null;
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.api.Resource) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 27 with Mediation

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

the class ExportUtils method addMultipleAPISpecificSequencesToArchive.

/**
 * Retrieve multiple API specific sequences for API export, and store it in the archive
 * directory.
 *
 * @param archivePath File path to export the sequences
 * @param api         API
 * @param apiProvider API Provider
 * @throws APIManagementException   If an error occurs while retrieving sequences and writing those
 * @throws APIImportExportException If an error occurs while creating the directory to export sequences
 */
private static void addMultipleAPISpecificSequencesToArchive(String archivePath, API api, APIProvider apiProvider) throws APIManagementException, APIImportExportException {
    String seqArchivePath = archivePath.concat(File.separator + ImportExportConstants.SEQUENCES_RESOURCE);
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    if (!CommonUtil.checkFileExistence(seqArchivePath)) {
        CommonUtil.createDirectory(seqArchivePath);
    }
    // Getting list of API specific custom mediation policies
    List<Mediation> apiSpecificMediationList = apiProvider.getAllApiSpecificMediationPolicies(api.getUuid(), tenantDomain);
    if (!apiSpecificMediationList.isEmpty()) {
        for (Mediation mediation : apiSpecificMediationList) {
            Mediation mediationResource = apiProvider.getApiSpecificMediationPolicyByPolicyId(api.getUuid(), mediation.getUuid(), tenantDomain);
            String individualSequenceExportPath = seqArchivePath + File.separator + mediation.getType().toLowerCase() + ImportExportConstants.SEQUENCE_LOCATION_POSTFIX + File.separator + ImportExportConstants.CUSTOM_TYPE;
            if (!CommonUtil.checkFileExistence(individualSequenceExportPath)) {
                CommonUtil.createDirectory(individualSequenceExportPath);
            }
            writeSequenceToArchive(mediationResource.getConfig(), individualSequenceExportPath, mediation.getName());
        }
    }
}
Also used : Mediation(org.wso2.carbon.apimgt.api.model.Mediation)

Example 28 with Mediation

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

the class JsonSchemaValidator method mediate.

/**
 * This mediate method validates the message body.
 *
 * @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 a boolean true if the message content is passed the json schema criteria.
 */
public boolean mediate(MessageContext messageContext) {
    if (logger.isDebugEnabled()) {
        logger.debug("JSON schema validation mediator is activated...");
    }
    Map<String, InputStream> inputStreams = null;
    org.apache.axis2.context.MessageContext axis2MC;
    String apiContext;
    String requestMethod;
    String contentType;
    Boolean isValid = true;
    axis2MC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    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();
    requestMethod = axis2MC.getProperty(ThreatProtectorConstants.HTTP_REQUEST_METHOD).toString();
    if (!APIConstants.SupportedHTTPVerbs.GET.name().equalsIgnoreCase(requestMethod) && (ThreatProtectorConstants.APPLICATION_JSON.equals(contentType) || ThreatProtectorConstants.TEXT_JSON.equals(contentType))) {
        JSONConfig jsonConfig = configureSchemaProperties(messageContext);
        ConfigurationHolder.addJsonConfig(jsonConfig);
        APIMThreatAnalyzer apimThreatAnalyzer = AnalyzerHolder.getAnalyzer(contentType);
        try {
            inputStreams = GatewayUtils.cloneRequestMessage(messageContext);
            if (inputStreams != null) {
                InputStream inputStreamJson = inputStreams.get(ThreatProtectorConstants.JSON);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamJson);
                apimThreatAnalyzer.analyze(bufferedInputStream, apiContext);
                isValid = true;
            }
        } catch (APIMThreatAnalyzerException e) {
            String message = "Request is failed due to a JSON schema validation failure: ";
            logger.error(message, e);
            isValid = GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, message + e.getMessage());
        } catch (IOException e) {
            String message = "Error occurred while building the request: ";
            logger.error(message, e);
            isValid = GatewayUtils.handleThreat(messageContext, ThreatProtectorConstants.HTTP_SC_CODE, message + e.getMessage());
        } finally {
            // return analyzer to the pool
            AnalyzerHolder.returnObject(apimThreatAnalyzer);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("JSON Schema Validator: " + APIMgtGatewayConstants.REQUEST_TYPE_FAIL_MSG);
        }
    }
    GatewayUtils.setOriginalInputStream(inputStreams, axis2MC);
    if (isValid) {
        try {
            RelayUtils.buildMessage(axis2MC);
        } catch (IOException | XMLStreamException e) {
            isValid = GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE, e.getMessage());
        }
    }
    return isValid;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) BufferedInputStream(java.io.BufferedInputStream) JSONConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.JSONConfig) APIMThreatAnalyzer(org.wso2.carbon.apimgt.gateway.threatprotection.analyzer.APIMThreatAnalyzer) APIMThreatAnalyzerException(org.wso2.carbon.apimgt.gateway.threatprotection.APIMThreatAnalyzerException)

Example 29 with Mediation

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

the class XMLSchemaValidator method configureSchemaProperties.

/**
 * This method binds the properties of the json validator sequence with the XMLConfig object.
 *
 * @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 XMLConfig contains the xml schema properties need to be validated.
 */
XMLConfig configureSchemaProperties(MessageContext messageContext) {
    Object messageProperty;
    boolean dtdEnabled = false;
    boolean externalEntitiesEnabled = false;
    int maxXMLDepth = 0;
    int elementCount = 0;
    int attributeLength = 0;
    int attributeCount = 0;
    int entityExpansionLimit = 0;
    int childrenPerElement = 0;
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.DTD_ENABLED);
    if (messageProperty != null) {
        dtdEnabled = Boolean.valueOf(messageProperty.toString());
    } else {
        String message = "XML schema dtdEnabled property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.EXTERNAL_ENTITIES_ENABLED);
    if (messageProperty != null) {
        externalEntitiesEnabled = Boolean.valueOf(messageProperty.toString());
    } else {
        String message = "XML schema externalEntitiesEnabled property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_ELEMENT_COUNT);
    if (messageProperty != null) {
        elementCount = Integer.parseInt(messageProperty.toString());
    } else {
        String message = "XML schema elementCount property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_ATTRIBUTE_LENGTH);
    if (messageProperty != null) {
        attributeLength = Integer.parseInt(messageProperty.toString());
    } else {
        String message = "XML schema maxAttributeLength property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_XML_DEPTH);
    if (messageProperty != null) {
        maxXMLDepth = Integer.parseInt(messageProperty.toString());
    } else {
        String message = "XML schema xmlDepth property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.MAX_ATTRIBUTE_COUNT);
    if (messageProperty != null) {
        attributeCount = Integer.parseInt(messageProperty.toString());
    } else {
        String message = "XML schema attributeCount property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.ENTITY_EXPANSION_LIMIT);
    if (messageProperty != null) {
        entityExpansionLimit = Integer.parseInt(messageProperty.toString());
    } else {
        String message = "XML schema entityExpansionLimit property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    }
    messageProperty = messageContext.getProperty(ThreatProtectorConstants.CHILDREN_PER_ELEMENT);
    if (messageProperty == null) {
        String message = "XML schema childrenElement property value is missing.";
        ThreatExceptionHandler.handleException(messageContext, message);
    } else {
        childrenPerElement = Integer.parseInt(messageProperty.toString());
    }
    if (log.isDebugEnabled()) {
        log.debug(("DTD enable:" + dtdEnabled) + ", " + "External entities: " + externalEntitiesEnabled + ", " + "Element Count:" + elementCount + ", " + "Max AttributeLength:" + attributeLength + ", " + "Max xml Depth:" + maxXMLDepth + ", " + "Attribute count:" + attributeCount + ", " + "Entity Expansion Limit" + attributeCount + ". " + "childrenElement:" + attributeCount);
    }
    XMLConfig xmlConfig = new XMLConfig();
    xmlConfig.setDtdEnabled(dtdEnabled);
    xmlConfig.setExternalEntitiesEnabled(externalEntitiesEnabled);
    xmlConfig.setMaxDepth(maxXMLDepth);
    xmlConfig.setMaxElementCount(elementCount);
    xmlConfig.setMaxAttributeCount(attributeCount);
    xmlConfig.setMaxAttributeLength(attributeLength);
    xmlConfig.setEntityExpansionLimit(entityExpansionLimit);
    xmlConfig.setMaxChildrenPerElement(childrenPerElement);
    return xmlConfig;
}
Also used : XMLConfig(org.wso2.carbon.apimgt.gateway.threatprotection.configuration.XMLConfig)

Example 30 with Mediation

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

the class AbstractAPIManager method getApiSpecificMediationResourceFromUuid.

/**
 * Returns Registry resource matching given mediation policy identifier
 *
 * @param identifier   API identifier
 * @param uuid         mediation policy identifier
 * @param resourcePath registry path to the API resource
 * @return Registry resource matches given identifier or null
 * @throws APIManagementException If fails to get the resource matching given identifier
 */
@Override
public Resource getApiSpecificMediationResourceFromUuid(Identifier identifier, String uuid, String resourcePath) throws APIManagementException {
    try {
        Resource resource = registry.get(resourcePath);
        if (resource instanceof Collection) {
            Collection typeCollection = (Collection) resource;
            String[] typeArray = typeCollection.getChildren();
            for (String type : typeArray) {
                // Check for mediation policy resource
                if ((type.equalsIgnoreCase(resourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN)) || (type.equalsIgnoreCase(resourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT)) || (type.equalsIgnoreCase(resourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT))) {
                    Resource sequenceType = registry.get(type);
                    // sequenceType eg: in / out /fault
                    if (sequenceType instanceof Collection) {
                        String[] mediationPolicyArr = ((Collection) sequenceType).getChildren();
                        for (String mediationPolicy : mediationPolicyArr) {
                            Resource mediationResource = registry.get(mediationPolicy);
                            String resourceId = mediationResource.getUUID();
                            if (resourceId.equalsIgnoreCase(uuid)) {
                                return mediationResource;
                            }
                        }
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while obtaining registry objects";
        throw new APIManagementException(msg, e);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) Collection(org.wso2.carbon.registry.core.Collection) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

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