Search in sources :

Example 91 with Operation

use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.

the class ApiMgtDAO method addOperationPolicyMapping.

public void addOperationPolicyMapping(Set<URITemplate> uriTemplates) throws APIManagementException {
    if (uriTemplates != null && !uriTemplates.isEmpty()) {
        try (Connection connection = APIMgtDBUtil.getConnection()) {
            connection.setAutoCommit(false);
            try (PreparedStatement preparedStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING)) {
                for (URITemplate uriTemplate : uriTemplates) {
                    List<OperationPolicy> operationPolicies = uriTemplate.getOperationPolicies();
                    if (operationPolicies != null && !operationPolicies.isEmpty()) {
                        for (OperationPolicy operationPolicy : operationPolicies) {
                            Gson gson = new Gson();
                            String paramJSON = gson.toJson(operationPolicy.getParameters());
                            preparedStatement.setInt(1, uriTemplate.getId());
                            preparedStatement.setString(2, operationPolicy.getPolicyId());
                            preparedStatement.setString(3, operationPolicy.getDirection());
                            preparedStatement.setString(4, paramJSON);
                            preparedStatement.setInt(5, operationPolicy.getOrder());
                            preparedStatement.addBatch();
                        }
                    }
                }
                preparedStatement.executeBatch();
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        } catch (SQLException e) {
            throw new APIManagementException("Error while updating operation Policy mapping for API", e);
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) Connection(java.sql.Connection) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement)

Example 92 with Operation

use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.

the class ApiMgtDAO method deleteAPIProductRevision.

/**
 * Delete API Product revision database records
 *
 * @param apiRevision content of the revision
 * @throws APIManagementException if an error occurs when restoring an API revision
 */
public void deleteAPIProductRevision(APIRevision apiRevision) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try {
            connection.setAutoCommit(false);
            // Retrieve API ID
            APIProductIdentifier apiProductIdentifier = APIUtil.getAPIProductIdentifierFromUUID(apiRevision.getApiUUID());
            int apiId = getAPIID(apiRevision.getApiUUID(), connection);
            int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiProductIdentifier.getProviderName()));
            // Removing related revision entries from AM_REVISION table
            PreparedStatement removeAMRevisionStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.DELETE_API_REVISION);
            removeAMRevisionStatement.setString(1, apiRevision.getRevisionUUID());
            removeAMRevisionStatement.executeUpdate();
            // Removing related revision entries from AM_API_PRODUCT_MAPPING table
            PreparedStatement removeProductMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_REVISION_ENTRIES_IN_AM_API_PRODUCT_MAPPING_BY_REVISION_UUID);
            removeProductMappingsStatement.setInt(1, apiId);
            removeProductMappingsStatement.setString(2, apiRevision.getRevisionUUID());
            removeProductMappingsStatement.executeUpdate();
            // Removing related revision entries from AM_API_URL_MAPPING table
            PreparedStatement removeURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_PRODUCT_REVISION_ENTRIES_IN_AM_API_URL_MAPPING_BY_REVISION_UUID);
            removeURLMappingsStatement.setString(1, apiRevision.getRevisionUUID());
            removeURLMappingsStatement.executeUpdate();
            // Removing related revision entries from AM_API_CLIENT_CERTIFICATE table
            PreparedStatement removeClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_REVISION_ENTRIES_IN_AM_API_CLIENT_CERTIFICATE_BY_REVISION_UUID);
            removeClientCertificatesStatement.setInt(1, apiId);
            removeClientCertificatesStatement.setString(2, apiRevision.getRevisionUUID());
            removeClientCertificatesStatement.executeUpdate();
            // Removing related revision entries from AM_GRAPHQL_COMPLEXITY table
            PreparedStatement removeGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_REVISION_ENTRIES_IN_AM_GRAPHQL_COMPLEXITY_BY_REVISION_UUID);
            removeGraphQLComplexityStatement.setInt(1, apiId);
            removeGraphQLComplexityStatement.setString(2, apiRevision.getRevisionUUID());
            removeGraphQLComplexityStatement.executeUpdate();
            // Removing related revision entries for operation policies
            deleteAllAPISpecificOperationPoliciesByAPIUUID(connection, apiRevision.getApiUUID(), apiRevision.getRevisionUUID());
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            handleException("Failed to delete API Revision entry of API Product UUID " + apiRevision.getApiUUID(), e);
        }
    } catch (SQLException e) {
        handleException("Failed to delete API Revision entry of API Product UUID " + apiRevision.getApiUUID(), e);
    }
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 93 with Operation

use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.

the class ApiMgtDAO method removeAPIFromDefaultVersion.

/**
 * Sets/removes default api entry such that api will not represent as default api further.
 * If the api's version is the same as the published version, then the whole entry will be removed.
 * Otherwise only the default version attribute is set to null.
 *
 * @param apiIdList
 * @param connection
 * @return
 * @throws APIManagementException
 */
private void removeAPIFromDefaultVersion(List<APIIdentifier> apiIdList, Connection connection) throws APIManagementException {
    // TODO: check list empty
    try (PreparedStatement prepStmtDefVersionDelete = connection.prepareStatement(SQLConstants.REMOVE_API_DEFAULT_VERSION_SQL)) {
        for (APIIdentifier apiId : apiIdList) {
            prepStmtDefVersionDelete.setString(1, apiId.getApiName());
            prepStmtDefVersionDelete.setString(2, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
            prepStmtDefVersionDelete.addBatch();
        }
        prepStmtDefVersionDelete.executeBatch();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            log.error("Error while rolling back the failed operation", e1);
        }
        handleException("Error while deleting the API default version entry: " + apiIdList.stream().map(APIIdentifier::getApiName).collect(Collectors.joining(",")) + " from the " + "database", e);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 94 with Operation

use of org.wso2.carbon.apimgt.api.doc.model.Operation 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 95 with Operation

use of org.wso2.carbon.apimgt.api.doc.model.Operation in project carbon-apimgt by wso2.

the class WSDL11SOAPOperationExtractor method getTargetNamespace.

/**
 * Gets the target namespace given the soap binding operation
 *
 * @param bindingOperation soap operation
 * @return target name space
 */
private String getTargetNamespace(BindingOperation bindingOperation) {
    Operation operation = bindingOperation.getOperation();
    if (operation != null) {
        Input input = operation.getInput();
        if (input != null) {
            Message message = input.getMessage();
            if (message != null) {
                Map partMap = message.getParts();
                for (Object obj : partMap.entrySet()) {
                    Map.Entry entry = (Map.Entry) obj;
                    Part part = (Part) entry.getValue();
                    if (part != null) {
                        if (part.getElementName() != null) {
                            return part.getElementName().getNamespaceURI();
                        }
                    }
                }
            }
        }
    }
    return targetNamespace;
}
Also used : Input(javax.wsdl.Input) Message(javax.wsdl.Message) Part(javax.wsdl.Part) Operation(javax.wsdl.Operation) SOAP12Operation(javax.wsdl.extensions.soap12.SOAP12Operation) WSDLSOAPOperation(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLSOAPOperation) BindingOperation(javax.wsdl.BindingOperation) SOAPOperation(javax.wsdl.extensions.soap.SOAPOperation) WSDLOperation(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLOperation) Map(java.util.Map) HashMap(java.util.HashMap) NamedNodeMap(org.w3c.dom.NamedNodeMap)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 HashMap (java.util.HashMap)55 ArrayList (java.util.ArrayList)43 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)42 Test (org.testng.annotations.Test)34 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)29 HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)29 Map (java.util.Map)28 IOException (java.io.IOException)23 API (org.wso2.carbon.apimgt.api.model.API)22 List (java.util.List)20 JSONObject (org.json.simple.JSONObject)20 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)20 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)19 LinkedHashMap (java.util.LinkedHashMap)18 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)18 OperationPolicyData (org.wso2.carbon.apimgt.api.model.OperationPolicyData)18 APIInfo (org.wso2.carbon.apimgt.api.model.APIInfo)17 Connection (java.sql.Connection)16 PreparedStatement (java.sql.PreparedStatement)16