Search in sources :

Example 51 with Mediation

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

the class AbstractAPIManager method getGlobalMediationPolicy.

/**
 * Return mediation policy corresponds to the given identifier
 *
 * @param mediationPolicyId uuid of the registry resource
 * @return Mediation object related to the given identifier or null
 * @throws APIManagementException If failed to get specified mediation policy
 */
@Override
public Mediation getGlobalMediationPolicy(String mediationPolicyId) throws APIManagementException {
    Mediation mediation = null;
    // Get registry resource correspond to identifier
    Resource mediationResource = this.getCustomMediationResourceFromUuid(mediationPolicyId);
    if (mediationResource != null) {
        // Get mediation config details
        try {
            // extracting content stream of mediation policy in to  string
            String contentString = IOUtils.toString(mediationResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
            // Get policy name from the mediation config
            OMElement omElement = AXIOMUtil.stringToOM(contentString);
            OMAttribute attribute = omElement.getAttribute(new QName(PolicyConstants.MEDIATION_NAME_ATTRIBUTE));
            String mediationPolicyName = attribute.getAttributeValue();
            mediation = new Mediation();
            mediation.setUuid(mediationResource.getUUID());
            mediation.setName(mediationPolicyName);
            String resourcePath = mediationResource.getPath();
            // Extracting mediation type from the registry resource path
            String[] path = resourcePath.split(RegistryConstants.PATH_SEPARATOR);
            String resourceType = path[(path.length - 2)];
            mediation.setType(resourceType);
            mediation.setConfig(contentString);
        } catch (RegistryException e) {
            log.error("Error occurred while getting content stream of the ,mediation policy ", e);
        } catch (IOException e) {
            log.error("Error occurred while converting content stream of mediation policy " + "into string ", e);
        } catch (XMLStreamException e) {
            log.error("Error occurred while getting omElement out of mediation content ", e);
        }
    }
    return mediation;
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) OMAttribute(org.apache.axiom.om.OMAttribute) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 52 with Mediation

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

the class AbstractAPIManager method getAllApiSpecificMediationPolicies.

/**
 * Returns a list of API specific mediation policies from registry
 *
 * @param apiIdentifier API identifier
 * @return List of api specific mediation objects available
 * @throws APIManagementException If unable to get mediation policies of specified API Id
 */
@Override
public List<Mediation> getAllApiSpecificMediationPolicies(APIIdentifier apiIdentifier) throws APIManagementException {
    List<Mediation> mediationList = new ArrayList<Mediation>();
    Mediation mediation;
    String apiResourcePath = APIUtil.getAPIPath(apiIdentifier);
    apiResourcePath = apiResourcePath.substring(0, apiResourcePath.lastIndexOf("/"));
    try {
        // Getting API registry resource
        Resource resource = registry.get(apiResourcePath);
        // resource eg: /_system/governance/apimgt/applicationdata/provider/admin/calculatorAPI/2.0
        if (resource instanceof Collection) {
            Collection typeCollection = (Collection) resource;
            String[] typeArray = typeCollection.getChildren();
            for (String type : typeArray) {
                // Check for mediation policy sequences
                if ((type.equalsIgnoreCase(apiResourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN)) || (type.equalsIgnoreCase(apiResourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT)) || (type.equalsIgnoreCase(apiResourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT))) {
                    Resource typeResource = registry.get(type);
                    // typeResource : in / out / fault
                    if (typeResource instanceof Collection) {
                        String[] mediationPolicyArr = ((Collection) typeResource).getChildren();
                        if (mediationPolicyArr.length > 0) {
                            for (String mediationPolicy : mediationPolicyArr) {
                                Resource policyResource = registry.get(mediationPolicy);
                                // policyResource eg: custom_in_message
                                // Get uuid of the registry resource
                                String resourceId = policyResource.getUUID();
                                // Get mediation policy config
                                try {
                                    String contentString = IOUtils.toString(policyResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
                                    // Extract name from the policy config
                                    OMElement omElement = AXIOMUtil.stringToOM(contentString);
                                    OMAttribute attribute = omElement.getAttribute(new QName("name"));
                                    String mediationPolicyName = attribute.getAttributeValue();
                                    mediation = new Mediation();
                                    mediation.setUuid(resourceId);
                                    mediation.setName(mediationPolicyName);
                                    // Extracting mediation policy type from the registry resource path
                                    String resourceType = type.substring(type.lastIndexOf("/") + 1);
                                    mediation.setType(resourceType);
                                    mediationList.add(mediation);
                                } catch (XMLStreamException e) {
                                    // If exception been caught flow will continue with next mediation policy
                                    log.error("Error occurred while getting omElement out of" + " mediation content", e);
                                } catch (IOException e) {
                                    log.error("Error occurred while converting the content " + "stream of mediation " + mediationPolicy + " to string", e);
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error occurred  while getting Api Specific mediation policies ";
        throw new APIManagementException(msg, e);
    }
    return mediationList;
}
Also used : QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) OMElement(org.apache.axiom.om.OMElement) IOException(java.io.IOException) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) XMLStreamException(javax.xml.stream.XMLStreamException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(org.wso2.carbon.registry.core.Collection) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 53 with Mediation

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

the class APIUtil method getMediationSequenceUuid.

/**
 * Returns uuid correspond to the given sequence name and direction
 *
 * @param sequenceName name of the  sequence
 * @param tenantId     logged in user's tenantId
 * @param direction    in/out/fault
 * @param identifier   API identifier
 * @return uuid of the given mediation sequence or null
 * @throws APIManagementException If failed to get the uuid of the mediation sequence
 */
public static String getMediationSequenceUuid(String sequenceName, int tenantId, String direction, APIIdentifier identifier) throws APIManagementException {
    org.wso2.carbon.registry.api.Collection seqCollection = null;
    String seqCollectionPath;
    try {
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        if ("in".equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
        } else if ("out".equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
        } else if ("fault".equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
        }
        if (seqCollection == null) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        }
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource sequence = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
                String seqElmentName = seqElment.getAttributeValue(new QName("name"));
                if (sequenceName.equals(seqElmentName)) {
                    return sequence.getUUID();
                }
            }
        }
        // If the sequence not found the default sequences, check in custom sequences
        seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource sequence = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
                if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) {
                    return sequence.getUUID();
                }
            }
        }
    } catch (Exception e) {
        String msg = "Issue is in accessing the Registry";
        log.error(msg);
        throw new APIManagementException(msg, e);
    }
    return null;
}
Also used : QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ExceptionException(org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) RemoteException(java.rmi.RemoteException) CertificateEncodingException(javax.security.cert.CertificateEncodingException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ValidationException(org.everit.json.schema.ValidationException) CryptoException(org.wso2.carbon.core.util.CryptoException) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SocketException(java.net.SocketException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(java.util.Collection)

Example 54 with Mediation

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

the class PoliciesApiServiceImpl method policiesMediationPost.

/**
 * Add a global mediation policy
 *
 * @param body              Mediation DTO as request body
 * @param contentType       Content-Type header
 * @return created mediation DTO as response
 */
@Override
public Response policiesMediationPost(String contentType, MediationDTO body, MessageContext messageContext) {
    InputStream contentStream = null;
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String content = body.getConfig();
        contentStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
        ResourceFile contentFile = new ResourceFile(contentStream, contentType);
        // Extracting mediation policy name from the mediation config
        String fileName = this.getMediationNameFromConfig(content);
        // constructing the registry resource path
        String mediationPolicyPath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION + RegistryConstants.PATH_SEPARATOR + body.getType() + RegistryConstants.PATH_SEPARATOR + fileName;
        if (apiProvider.checkIfResourceExists(mediationPolicyPath)) {
            RestApiUtil.handleConflict("Mediation policy already exists", log);
        }
        // Adding new global mediation sequence
        // No need to check API permission, hence null as api identifier
        String mediationPolicyUrl = apiProvider.addResourceFile(null, mediationPolicyPath, contentFile);
        if (StringUtils.isNotBlank(mediationPolicyUrl)) {
            // Getting the uuid of the created global mediation policy
            String uuid = apiProvider.getCreatedResourceUuid(mediationPolicyPath);
            // Getting created mediation policy
            Mediation createdMediation = apiProvider.getGlobalMediationPolicy(uuid);
            MediationDTO createdPolicy = MediationMappingUtil.fromMediationToDTO(createdMediation);
            URI uploadedMediationUri = new URI(mediationPolicyUrl);
            return Response.created(uploadedMediationUri).entity(createdPolicy).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding the global mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while getting location header for created " + "mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
    return null;
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) 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) URI(java.net.URI)

Example 55 with Mediation

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

the class PoliciesApiServiceImpl method policiesMediationMediationPolicyIdPut.

/**
 * Updates an existing global mediation policy
 *
 * @param mediationPolicyId uuid of mediation policy
 * @param body              updated MediationDTO
 * @param contentType       Content-Type header
 * @return updated mediation DTO as response
 */
@Override
public Response policiesMediationMediationPolicyIdPut(String mediationPolicyId, String contentType, MediationDTO body, MessageContext messageContext) {
    InputStream contentStream = null;
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // Get registry resource correspond to given uuid
        Resource mediationResource = apiProvider.getCustomMediationResourceFromUuid(mediationPolicyId);
        if (mediationResource != null) {
            // extracting already existing name of the mediation policy
            String contentString = IOUtils.toString(mediationResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
            // Get policy name from the mediation config
            OMElement omElement = AXIOMUtil.stringToOM(contentString);
            OMAttribute attribute = omElement.getAttribute(new QName(PolicyConstants.MEDIATION_NAME_ATTRIBUTE));
            String existingMediationPolicyName = attribute.getAttributeValue();
            // replacing the name of the body with existing name
            body.setName(existingMediationPolicyName);
            // Getting mediation config to be update from the body
            contentStream = new ByteArrayInputStream(body.getConfig().getBytes(StandardCharsets.UTF_8));
            // Creating new resource file
            ResourceFile contentFile = new ResourceFile(contentStream, contentType);
            // Getting registry path of the existing resource
            String resourcePath = mediationResource.getPath();
            // Updating the existing global mediation policy
            // No need to check API permission, hence null as api identifier
            String updatedPolicyUrl = apiProvider.addResourceFile(null, resourcePath, contentFile);
            if (StringUtils.isNotBlank(updatedPolicyUrl)) {
                // Getting uuid of updated global mediation policy
                String uuid = apiProvider.getCreatedResourceUuid(resourcePath);
                // Getting updated mediation
                Mediation updatedMediation = apiProvider.getGlobalMediationPolicy(uuid);
                MediationDTO updatedMediationDTO = MediationMappingUtil.fromMediationToDTO(updatedMediation);
                URI uploadedMediationUri = new URI(updatedPolicyUrl);
                return Response.ok(uploadedMediationUri).entity(updatedMediationDTO).build();
            }
        } else {
            // If resource not exists
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while updating the global mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while getting location header for uploaded " + "mediation policy " + body.getName();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (XMLStreamException e) {
        String errorMessage = "Error occurred while converting the existing content stream of " + " mediation " + "policy to string";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (RegistryException e) {
        String errorMessage = "Error occurred while getting the existing content stream ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (IOException e) {
        String errorMessage = "Error occurred while converting content stream in to string ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.api.Resource) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) 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) URI(java.net.URI) RegistryException(org.wso2.carbon.registry.api.RegistryException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) OMAttribute(org.apache.axiom.om.OMAttribute)

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