use of org.wso2.carbon.apimgt.persistence.dto.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();
}
}
}
use of org.wso2.carbon.apimgt.persistence.dto.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;
}
use of org.wso2.carbon.apimgt.persistence.dto.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();
}
}
}
use of org.wso2.carbon.apimgt.persistence.dto.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;
}
use of org.wso2.carbon.apimgt.persistence.dto.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;
}
Aggregations