Search in sources :

Example 1 with SOAPToRestSequence

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();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 2 with SOAPToRestSequence

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;
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) RefModel(io.swagger.models.RefModel) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) Operation(io.swagger.models.Operation) BodyParameter(io.swagger.models.parameters.BodyParameter) LinkedHashMap(java.util.LinkedHashMap) SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) Example(io.swagger.inflector.examples.models.Example) ObjectExample(io.swagger.inflector.examples.models.ObjectExample) ArrayExample(io.swagger.inflector.examples.models.ArrayExample) StringExample(io.swagger.inflector.examples.models.StringExample) Path(io.swagger.models.Path) JSONException(org.json.JSONException) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence) RESTToSOAPMsgTemplate(org.wso2.carbon.apimgt.impl.wsdl.template.RESTToSOAPMsgTemplate) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) JsonNodeExampleSerializer(io.swagger.inflector.processors.JsonNodeExampleSerializer) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) SimpleModule(com.fasterxml.jackson.databind.module.SimpleModule) HttpMethod(io.swagger.models.HttpMethod)

Example 3 with SOAPToRestSequence

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();
}
Also used : JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence)

Example 4 with SOAPToRestSequence

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);
}
Also used : APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API)

Example 5 with SOAPToRestSequence

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);
}
Also used : API(org.wso2.carbon.apimgt.api.model.API) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence)

Aggregations

SOAPToRestSequence (org.wso2.carbon.apimgt.api.model.SOAPToRestSequence)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 API (org.wso2.carbon.apimgt.api.model.API)5 Resource (org.wso2.carbon.registry.core.Resource)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 JSONObject (org.json.simple.JSONObject)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)2 Collection (org.wso2.carbon.registry.core.Collection)2 SimpleModule (com.fasterxml.jackson.databind.module.SimpleModule)1 ArrayExample (io.swagger.inflector.examples.models.ArrayExample)1 Example (io.swagger.inflector.examples.models.Example)1 ObjectExample (io.swagger.inflector.examples.models.ObjectExample)1 StringExample (io.swagger.inflector.examples.models.StringExample)1 JsonNodeExampleSerializer (io.swagger.inflector.processors.JsonNodeExampleSerializer)1 HttpMethod (io.swagger.models.HttpMethod)1 Model (io.swagger.models.Model)1 Operation (io.swagger.models.Operation)1