use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.
the class AbstractAPIManager method getAllGlobalMediationPolicies.
/**
* Returns list of global mediation policies available
*
* @return List of Mediation objects of global mediation policies
* @throws APIManagementException If failed to get global mediation policies
*/
@Override
public List<Mediation> getAllGlobalMediationPolicies() throws APIManagementException {
List<Mediation> mediationList = new ArrayList<Mediation>();
Mediation mediation;
String resourcePath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION;
try {
// Resource : customsequences
Resource resource = registry.get(resourcePath);
if (resource instanceof Collection) {
Collection typeCollection = (Collection) resource;
String[] typeArray = typeCollection.getChildren();
for (String type : typeArray) {
// Resource : in / out / fault
Resource typeResource = registry.get(type);
if (typeResource instanceof Collection) {
String[] sequenceArray = ((Collection) typeResource).getChildren();
if (sequenceArray.length > 0) {
for (String sequence : sequenceArray) {
// Resource : actual resource eg : log_in_msg.xml
Resource sequenceResource = registry.get(sequence);
String resourceId = sequenceResource.getUUID();
try {
String contentString = IOUtils.toString(sequenceResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
OMElement omElement = AXIOMUtil.stringToOM(contentString);
OMAttribute attribute = omElement.getAttribute(new QName(PolicyConstants.MEDIATION_NAME_ATTRIBUTE));
String mediationPolicyName = attribute.getAttributeValue();
mediation = new Mediation();
mediation.setUuid(resourceId);
mediation.setName(mediationPolicyName);
// Extract sequence type from the registry resource path
String resourceType = type.substring(type.lastIndexOf("/") + 1);
mediation.setType(resourceType);
// Add mediation to the mediation list
mediationList.add(mediation);
} catch (XMLStreamException e) {
// If any exception been caught flow may continue with the next mediation policy
log.error("Error occurred while getting omElement out of " + "mediation content from " + sequence, e);
} catch (IOException e) {
log.error("Error occurred while converting resource " + "contentStream in to string in " + sequence, e);
}
}
}
}
}
}
} catch (RegistryException e) {
String msg = "Failed to get global mediation policies";
throw new APIManagementException(msg, e);
}
return mediationList;
}
use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addApiSpecificMediationPolicyFromFile.
/**
* Add API specific mediation sequences from file content.
*
* @param localName Local name of the mediation policy to be added
* @param content File content of the mediation policy to be added
* @param fileName File name of the mediation policy to be added
* @param type Type (in/out/fault) of the mediation policy to be added
* @param apiProvider API Provider
* @param apiId API ID of the mediation policy
* @param organization Organization of the API
* @return
* @throws APIManagementException If the sequence is malformed.
*/
private static Mediation addApiSpecificMediationPolicyFromFile(String localName, String content, String fileName, String type, APIProvider apiProvider, String apiId, String organization) throws APIManagementException {
if (APIConstants.MEDIATION_SEQUENCE_ELEM.equals(localName)) {
Mediation mediationPolicy = new Mediation();
mediationPolicy.setConfig(content);
mediationPolicy.setName(fileName);
mediationPolicy.setType(type);
// Adding API specific mediation policy
return apiProvider.addApiSpecificMediationPolicy(apiId, mediationPolicy, organization);
} else {
throw new APIManagementException("Sequence is malformed");
}
}
use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addMediationPolicyFromFile.
/**
* Add mediation sequences from file content.
*
* @param content File content of the mediation policy to be added
* @param type Type (in/out/fault) of the mediation policy to be added
* @param apiProvider API Provider
* @param apiId API ID of the mediation policy
* @param organization Organization of the API
* @param existingMediations Existing mediation sequences
* (This can be null when adding an API specific sequence)
* @return Added mediation
* @throws Exception If an error occurs while adding the mediation sequence
*/
public static Mediation addMediationPolicyFromFile(String content, String type, APIProvider apiProvider, String apiId, String organization, List<Mediation> existingMediations, boolean isAPISpecific) throws Exception {
if (StringUtils.isNotEmpty(content)) {
OMElement seqElement = APIUtil.buildOMElement(new ByteArrayInputStream(content.getBytes()));
String localName = seqElement.getLocalName();
String fileName = seqElement.getAttributeValue(new QName("name"));
Mediation existingMediation = (existingMediations != null) ? checkInExistingMediations(existingMediations, fileName, type) : null;
// Otherwise, the value of this variable will be set before coming into this function
if (!isAPISpecific) {
if (existingMediation != null) {
log.debug("Sequence" + fileName + " already exists");
} else {
return addApiSpecificMediationPolicyFromFile(localName, content, fileName, type, apiProvider, apiId, organization);
}
} else {
if (existingMediation != null) {
// This will happen only when updating an API specific sequence using apictl
apiProvider.deleteApiSpecificMediationPolicy(apiId, existingMediation.getUuid(), organization);
}
return addApiSpecificMediationPolicyFromFile(localName, content, fileName, type, apiProvider, apiId, organization);
}
}
return null;
}
use of org.wso2.carbon.apimgt.persistence.dto.Mediation in project carbon-apimgt by wso2.
the class OAS2Parser method generateExample.
/**
* This method generates Sample/Mock payloads for Swagger (2.0) definitions
*
* @param swaggerDef Swagger Definition
* @return Swagger Json
*/
@Override
public Map<String, Object> generateExample(String swaggerDef) throws APIManagementException {
// create APIResourceMediationPolicy List = policyList
SwaggerParser parser = new SwaggerParser();
SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
Swagger swagger = parseAttemptForV2.getSwagger();
// return map
Map<String, Object> returnMap = new HashMap<>();
// List for APIResMedPolicyList
List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
int responseCode = 0;
int minResponseCode = 0;
String path = entry.getKey();
Map<String, Model> definitions = swagger.getDefinitions();
// operation map to get verb
Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
List<Operation> operations = swagger.getPaths().get(path).getOperations();
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>();
Object[] operationsArray = operationMap.entrySet().toArray();
if (operationsArray.length > i) {
Map.Entry<HttpMethod, Operation> operationEntry = (Map.Entry<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");
}
StringBuilder genCode = new StringBuilder();
boolean hasJsonPayload = false;
boolean hasXmlPayload = false;
// for setting only one initializing if condition per response code
boolean respCodeInitialized = false;
for (String responseEntry : op.getResponses().keySet()) {
if (!responseEntry.equals("default")) {
responseCode = Integer.parseInt(responseEntry);
responseCodes.add(responseCode);
minResponseCode = Collections.min(responseCodes);
}
if (op.getResponses().get(responseEntry).getExamples() != null) {
Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
if (applicationJson != null) {
String jsonExample = Json.pretty(applicationJson);
genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
respCodeInitialized = true;
hasJsonPayload = true;
}
if (applicationXml != null) {
String xmlExample = applicationXml.toString();
genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
hasXmlPayload = true;
}
} else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
Model model = op.getResponses().get(responseEntry).getResponseSchema();
String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
hasJsonPayload = true;
} else if (op.getResponses().get(responseEntry).getExamples() == null && op.getResponses().get(responseEntry).getResponseSchema() == null) {
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);
apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
// sets script to each resource in the swagger
op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
}
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 MediationPoliciesApiServiceImpl method getAllGlobalMediationPolicies.
/**
* Returns list of global Mediation policies
*
* @param limit maximum number of mediation returns
* @param offset starting index
* @param query search condition
* @param ifNoneMatch If-None-Match header value
* @return Matched global mediation policies for given search condition
*/
@Override
public Response getAllGlobalMediationPolicies(Integer limit, Integer offset, String query, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
// pre-processing
// setting default limit and offset values if they are not set
limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
List<Mediation> mediationList = apiProvider.getAllGlobalMediationPolicies();
MediationListDTO mediationListDTO = MediationMappingUtil.fromMediationListToDTO(mediationList, offset, limit);
return Response.ok().entity(mediationListDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Error while retrieving global mediation policies";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
return null;
}
}
Aggregations