use of org.wso2.carbon.apimgt.api.model.SOAPToRestSequence in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method getPublisherAPI.
@Override
public PublisherAPI getPublisherAPI(Organization org, String apiId) throws APIPersistenceException {
boolean tenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
tenantFlowStarted = holder.isTenantFlowStarted();
Registry registry = holder.getRegistry();
GenericArtifact apiArtifact = getAPIArtifact(apiId, registry);
if (apiArtifact != null) {
API api = RegistryPersistenceUtil.getApiForPublishing(registry, apiArtifact);
String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
int prependIndex = apiPath.lastIndexOf("/api");
String apiSourcePath = apiPath.substring(0, prependIndex);
String definitionPath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
String asyncApiDefinitionPath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
if (registry.resourceExists(definitionPath)) {
Resource apiDocResource = registry.get(definitionPath);
String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
api.setSwaggerDefinition(apiDocContent);
}
if (APIConstants.API_TYPE_SOAPTOREST.equals(api.getType())) {
List<SOAPToRestSequence> list = getSoapToRestSequences(registry, api, Direction.IN);
list.addAll(getSoapToRestSequences(registry, api, Direction.OUT));
api.setSoapToRestSequences(list);
} else if (APIConstants.API_TYPE_WEBSUB.equals(api.getType()) || APIConstants.API_TYPE_WS.equals(api.getType()) || APIConstants.API_TYPE_SSE.equals(api.getType()) || APIConstants.API_TYPE_WEBHOOK.equals(api.getType())) {
if (asyncApiDefinitionPath != null) {
if (registry.resourceExists(asyncApiDefinitionPath)) {
Resource apiDocResource = registry.get(asyncApiDefinitionPath);
String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
api.setAsyncApiDefinition(apiDocContent);
}
}
}
PublisherAPI pubApi = APIMapper.INSTANCE.toPublisherApi(api);
if (log.isDebugEnabled()) {
log.debug("API for id " + apiId + " : " + pubApi.toString());
}
return pubApi;
} else {
String msg = "Failed to get API. API artifact corresponding to artifactId " + apiId + " does not exist";
throw new APIMgtResourceNotFoundException(msg);
}
} catch (RegistryException e) {
String msg = "Failed to get API";
throw new APIPersistenceException(msg, e);
} catch (APIManagementException e) {
String msg = "Failed to get API";
throw new APIPersistenceException(msg, e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.api.model.SOAPToRestSequence in project carbon-apimgt by wso2.
the class SequenceGenerator method generateSequencesFromSwagger.
/**
* Generates in/out sequences from the swagger given
*
* @param swaggerStr swagger string
* @throws APIManagementException
*/
public static List<SOAPToRestSequence> generateSequencesFromSwagger(String swaggerStr) throws APIManagementException {
List<SOAPToRestSequence> sequences = new ArrayList<SOAPToRestSequence>();
Swagger swagger = new SwaggerParser().parse(swaggerStr);
Map<String, Model> definitions = swagger.getDefinitions();
// Configure serializers
SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
Json.mapper().registerModule(simpleModule);
Yaml.mapper().registerModule(simpleModule);
Map<String, Path> paths = swagger.getPaths();
for (String pathName : paths.keySet()) {
Path path = paths.get(pathName);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
for (HttpMethod httpMethod : operationMap.keySet()) {
boolean isResourceFromWSDL = false;
Map<String, String> parameterJsonPathMapping = new HashMap<>();
Map<String, String> queryParameters = new HashMap<>();
Operation operation = operationMap.get(httpMethod);
String operationId = operation.getOperationId();
// get vendor extensions
Map<String, Object> vendorExtensions = operation.getVendorExtensions();
Object vendorExtensionObj = vendorExtensions.get("x-wso2-soap");
String soapAction = SOAPToRESTConstants.EMPTY_STRING;
String namespace = SOAPToRESTConstants.EMPTY_STRING;
String soapVersion = SOAPToRESTConstants.EMPTY_STRING;
if (vendorExtensionObj != null) {
soapAction = (String) ((LinkedHashMap) vendorExtensionObj).get("soap-action");
namespace = (String) ((LinkedHashMap) vendorExtensionObj).get("namespace");
soapVersion = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_VERSION);
soapMessageType = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_MESSAGE_TYPE);
soapStyle = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_STYLE);
isResourceFromWSDL = true;
}
String soapNamespace = SOAPToRESTConstants.SOAP12_NAMSPACE;
if (StringUtils.isNotBlank(soapVersion) && SOAPToRESTConstants.SOAP_VERSION_11.equals(soapVersion)) {
soapNamespace = SOAPToRESTConstants.SOAP11_NAMESPACE;
}
List<Parameter> parameters = operation.getParameters();
for (Parameter parameter : parameters) {
String name = parameter.getName();
if (parameter instanceof BodyParameter) {
Model schema = ((BodyParameter) parameter).getSchema();
if (schema instanceof RefModel) {
String $ref = ((RefModel) schema).get$ref();
if (StringUtils.isNotBlank($ref)) {
String defName = $ref.substring("#/definitions/".length());
Model model = definitions.get(defName);
Example example = ExampleBuilder.fromModel(defName, model, definitions, new HashSet<String>());
replaceNullWithStringExample(example);
String jsonExample = Json.pretty(example);
try {
org.json.JSONObject json = new org.json.JSONObject(jsonExample);
SequenceUtils.listJson(json, parameterJsonPathMapping);
} catch (JSONException e) {
log.error("Error occurred while generating json mapping for the definition", e);
}
}
}
}
if (parameter instanceof QueryParameter) {
String type = ((QueryParameter) parameter).getType();
queryParameters.put(name, type);
}
}
// populates body parameter json paths and query parameters to generate api sequence parameters
populateParametersFromOperation(operation, definitions, parameterJsonPathMapping, queryParameters);
Map<String, String> payloadSequence = createPayloadFacXMLForOperation(parameterJsonPathMapping, queryParameters, namespace, SOAPToRESTConstants.EMPTY_STRING, operationId, definitions);
try {
String[] propAndArgElements = getPropertyAndArgElementsForSequence(parameterJsonPathMapping, queryParameters);
if (log.isDebugEnabled()) {
log.debug("properties string for the generated sequence: " + propAndArgElements[0]);
log.debug("arguments string for the generated sequence: " + propAndArgElements[1]);
}
org.json.simple.JSONArray arraySequenceElements = new org.json.simple.JSONArray();
// gets array elements for the sequence to be used
getArraySequenceElements(arraySequenceElements, parameterJsonPathMapping);
Map<String, String> sequenceMap = new HashMap<>();
sequenceMap.put("args", propAndArgElements[0]);
sequenceMap.put("properties", propAndArgElements[1]);
sequenceMap.put("sequence", payloadSequence.get(operationId));
RESTToSOAPMsgTemplate template = new RESTToSOAPMsgTemplate();
String inSequence = template.getMappingInSequence(sequenceMap, operationId, soapAction, namespace, soapNamespace, arraySequenceElements);
String outSequence = template.getMappingOutSequence();
if (isResourceFromWSDL) {
SOAPToRestSequence inSeq = new SOAPToRestSequence(httpMethod.toString().toLowerCase(), pathName, inSequence, Direction.IN);
sequences.add(inSeq);
SOAPToRestSequence outSeq = new SOAPToRestSequence(httpMethod.toString().toLowerCase(), pathName, outSequence, Direction.OUT);
sequences.add(outSeq);
}
} catch (APIManagementException e) {
handleException("Error when generating sequence property and arg elements for soap operation: " + operationId, e);
}
}
}
return sequences;
}
use of org.wso2.carbon.apimgt.api.model.SOAPToRestSequence in project carbon-apimgt by wso2.
the class SequenceUtils method getRestToSoapConvertedSequence.
/**
* Gets soap to rest converted sequence from the registry
* <p>
* Note: this method is directly invoked from the jaggery layer
*
* @param api API
* @param seqType to identify the sequence is whether in/out sequence
* @return converted sequences string for a given operation
* @throws APIManagementException throws exceptions on unsuccessful retrieval of resources in registry
*/
public static String getRestToSoapConvertedSequence(API api, String seqType) throws APIManagementException {
JSONObject resultJson = new JSONObject();
List<SOAPToRestSequence> sequences = api.getSoapToRestSequences();
if (sequences == null) {
handleException("Cannot find any resource policies for the api " + api.getUuid());
}
for (SOAPToRestSequence sequence : sequences) {
if (sequence.getDirection().toString().equalsIgnoreCase(seqType)) {
String content = sequence.getContent();
String resourceName = sequence.getPath();
String httpMethod = sequence.getMethod();
Map<String, String> resourceMap = new HashMap<>();
resourceMap.put(SOAPToRESTConstants.RESOURCE_ID, sequence.getUuid());
resourceMap.put(SOAPToRESTConstants.METHOD, httpMethod);
resourceMap.put(SOAPToRESTConstants.CONTENT, content);
resultJson.put(resourceName + "_" + httpMethod, resourceMap);
}
}
if (log.isDebugEnabled()) {
log.debug("Saved sequence for type " + seqType + " for api:" + api.getId().getProviderName() + "-" + api.getId().getApiName() + "-" + api.getId().getVersion() + " is: " + resultJson.toJSONString());
}
return resultJson.toJSONString();
}
use of org.wso2.carbon.apimgt.api.model.SOAPToRestSequence in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateSwagger.
/**
* update swagger definition of the given api.
*
* @param apiId API Id
* @param response response of a swagger definition validation call
* @param organization Organization Identifier
* @return updated swagger definition
* @throws APIManagementException when error occurred updating swagger
* @throws FaultGatewaysException when error occurred publishing API to the gateway
*/
public static String updateSwagger(String apiId, APIDefinitionValidationResponse response, boolean isServiceAPI, String organization) throws APIManagementException, FaultGatewaysException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// this will fail if user does not have access to the API or the API does not exist
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
APIDefinition oasParser = response.getParser();
String apiDefinition = response.getJsonContent();
if (isServiceAPI) {
apiDefinition = oasParser.copyVendorExtensions(existingAPI.getSwaggerDefinition(), apiDefinition);
} else {
apiDefinition = OASParserUtil.preProcess(apiDefinition);
}
if (APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType())) {
List<SOAPToRestSequence> sequenceList = SequenceGenerator.generateSequencesFromSwagger(apiDefinition);
existingAPI.setSoapToRestSequences(sequenceList);
}
Set<URITemplate> uriTemplates = null;
uriTemplates = oasParser.getURITemplates(apiDefinition);
if (uriTemplates == null || uriTemplates.isEmpty()) {
throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
}
Set<org.wso2.carbon.apimgt.api.model.Scope> scopes = oasParser.getScopes(apiDefinition);
// validating scope roles
for (org.wso2.carbon.apimgt.api.model.Scope scope : scopes) {
String roles = scope.getRoles();
if (roles != null) {
for (String aRole : roles.split(",")) {
boolean isValidRole = APIUtil.isRoleNameExist(RestApiCommonUtil.getLoggedInUsername(), aRole);
if (!isValidRole) {
throw new APIManagementException("Role '" + aRole + "' Does not exist.");
}
}
}
}
List<APIResource> removedProductResources = apiProvider.getRemovedProductResources(uriTemplates, existingAPI);
if (!removedProductResources.isEmpty()) {
throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, existingAPI.getId().getApiName(), existingAPI.getId().getVersion()));
}
// set existing operation policies to URI templates
apiProvider.setOperationPoliciesToURITemplates(apiId, uriTemplates);
existingAPI.setUriTemplates(uriTemplates);
existingAPI.setScopes(scopes);
PublisherCommonUtils.validateScopes(existingAPI);
// Update API is called to update URITemplates and scopes of the API
SwaggerData swaggerData = new SwaggerData(existingAPI);
String updatedApiDefinition = oasParser.populateCustomManagementInfo(apiDefinition, swaggerData);
apiProvider.saveSwaggerDefinition(existingAPI, updatedApiDefinition, organization);
existingAPI.setSwaggerDefinition(updatedApiDefinition);
API unModifiedAPI = apiProvider.getAPIbyUUID(apiId, organization);
existingAPI.setStatus(unModifiedAPI.getStatus());
apiProvider.updateAPI(existingAPI, unModifiedAPI);
// retrieves the updated swagger definition
// TODO see why we need to get it
String apiSwagger = apiProvider.getOpenAPIDefinition(apiId, organization);
// instead of passing same
return oasParser.getOASDefinitionForPublisher(existingAPI, apiSwagger);
}
use of org.wso2.carbon.apimgt.api.model.SOAPToRestSequence in project carbon-apimgt by wso2.
the class PublisherCommonUtils method updateAPIBySettingGenerateSequencesFromSwagger.
/**
* Set the generated SOAP to REST sequences from the swagger file to the API and update it.
*
* @param swaggerContent Swagger content
* @param api API to update
* @param apiProvider API Provider
* @param organization Organization Identifier
* @return Updated API Object
* @throws APIManagementException If an error occurs while generating the sequences or updating the API
* @throws FaultGatewaysException If an error occurs while updating the API
*/
public static API updateAPIBySettingGenerateSequencesFromSwagger(String swaggerContent, API api, APIProvider apiProvider, String organization) throws APIManagementException, FaultGatewaysException {
List<SOAPToRestSequence> list = SequenceGenerator.generateSequencesFromSwagger(swaggerContent);
API updatedAPI = apiProvider.getAPIbyUUID(api.getUuid(), organization);
updatedAPI.setSoapToRestSequences(list);
return apiProvider.updateAPI(updatedAPI, api);
}
Aggregations