Search in sources :

Example 51 with ModelImpl

use of io.swagger.models.ModelImpl in project carbon-apimgt by wso2.

the class SequenceGenerator method createPayloadFacXMLForOperation.

private static Map<String, String> createPayloadFacXMLForOperation(Map<String, String> parameterJsonPathMapping, Map<String, String> queryPathParamMapping, String namespace, String prefix, String operationId, Map<String, Model> definitions) throws APIManagementException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    DocumentBuilder docBuilder;
    StringWriter stringWriter = new StringWriter();
    Boolean isNamespaceQualified = false;
    Boolean isRootComplexType = false;
    try {
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = null;
        if (SOAPToRESTConstants.SOAP_RPC_MESSAGE_TYPE.equalsIgnoreCase(soapMessageType) || SOAPToRESTConstants.SOAP_RPC_MESSAGE_TYPE.equalsIgnoreCase(soapStyle) || parameterJsonPathMapping.size() == 0) {
            rootElement = doc.createElementNS(namespace, SOAPToRESTConstants.SequenceGen.NAMESPACE_PREFIX + SOAPToRESTConstants.SequenceGen.NAMESPACE_SEPARATOR + operationId);
            doc.appendChild(rootElement);
        }
        int count = 1;
        for (String parameter : parameterJsonPathMapping.keySet()) {
            String parameterType = parameterJsonPathMapping.get(parameter);
            String[] parameterTreeNodes = parameter.split("\\.");
            Element prevElement = rootElement;
            int elemPos = 0;
            int length = parameterType.equals(SOAPToRESTConstants.ParamTypes.ARRAY) ? parameterTreeNodes.length - 1 : parameterTreeNodes.length;
            if (length > 0 && !isRootComplexType) {
                isRootComplexType = true;
            }
            for (int i = 0; i < length; i++) {
                String parameterTreeNode = parameterTreeNodes[i];
                ModelImpl model = (ModelImpl) definitions.get(parameterTreeNode);
                if (model != null) {
                    Map<String, Object> venderExtensions = model.getVendorExtensions();
                    if (venderExtensions.get(SOAPToRESTConstants.X_NAMESPACE_QUALIFIED) != null && Boolean.parseBoolean(venderExtensions.get(SOAPToRESTConstants.X_NAMESPACE_QUALIFIED).toString())) {
                        isNamespaceQualified = true;
                    }
                }
                if (StringUtils.isNotBlank(parameterTreeNode)) {
                    if (SOAPToRESTConstants.ATTR_CONTENT_KEYWORD.equalsIgnoreCase(parameterTreeNode)) {
                        String attName = parameterTreeNodes[++i];
                        prevElement.setAttribute(attName, SOAPToRESTConstants.SequenceGen.PROPERTY_ACCESSOR + count++);
                        break;
                    }
                    if (SOAPToRESTConstants.BASE_CONTENT_KEYWORD.equalsIgnoreCase(parameterTreeNode)) {
                        prevElement.setTextContent(SOAPToRESTConstants.SequenceGen.PROPERTY_ACCESSOR + count++);
                        break;
                    }
                    Element element;
                    if (isNamespaceQualified) {
                        element = doc.createElementNS(namespace, SOAPToRESTConstants.SequenceGen.NAMESPACE_PREFIX + SOAPToRESTConstants.SequenceGen.NAMESPACE_SEPARATOR + parameterTreeNode);
                    } else if (!isNamespaceQualified && isRootComplexType) {
                        element = doc.createElementNS(namespace, SOAPToRESTConstants.SequenceGen.NAMESPACE_PREFIX + SOAPToRESTConstants.SequenceGen.NAMESPACE_SEPARATOR + parameterTreeNode);
                        isRootComplexType = false;
                    } else {
                        element = doc.createElementNS(null, parameterTreeNode);
                        element.setAttribute(SOAPToRESTConstants.XMLNS, SOAPToRESTConstants.X_WSO2_UNIQUE_NAMESPACE);
                    }
                    String xPathOfNode = StringUtils.EMPTY;
                    if (doc.getElementsByTagName(element.getTagName()).getLength() > 0) {
                        xPathOfNode = getXpath(doc.getElementsByTagName(element.getTagName()).item(0));
                        xPathOfNode = xPathOfNode.replaceAll("/+", ".");
                        if (xPathOfNode.startsWith(".")) {
                            xPathOfNode = xPathOfNode.substring(1);
                        }
                        if (xPathOfNode.contains(operationId + ".")) {
                            xPathOfNode = xPathOfNode.replace(operationId + ".", "");
                        }
                    }
                    if (doc.getElementsByTagName(element.getTagName()).getLength() > 0 && parameter.contains(xPathOfNode) && rootElement != doc.getElementsByTagName(element.getTagName()).item(0)) {
                        prevElement = (Element) doc.getElementsByTagName(element.getTagName()).item(0);
                    } else {
                        if (elemPos == length - 1) {
                            element.setTextContent(SOAPToRESTConstants.SequenceGen.PROPERTY_ACCESSOR + count);
                            count++;
                        }
                        if (prevElement != null) {
                            prevElement.appendChild(element);
                            prevElement = element;
                        } else {
                            doc.appendChild(element);
                            prevElement = element;
                        }
                    }
                    elemPos++;
                }
            }
        }
        count = 1;
        if (parameterJsonPathMapping.size() == 0) {
            for (String queryParam : queryPathParamMapping.keySet()) {
                Element element = doc.createElementNS(namespace, SOAPToRESTConstants.SequenceGen.NAMESPACE_PREFIX + SOAPToRESTConstants.SequenceGen.NAMESPACE_SEPARATOR + queryParam);
                element.setTextContent(SOAPToRESTConstants.SequenceGen.PROPERTY_ACCESSOR + count);
                count++;
                if (rootElement != null) {
                    rootElement.appendChild(element);
                } else {
                    doc.appendChild(element);
                }
            }
        } else if (parameterJsonPathMapping.size() > 0 && queryPathParamMapping.size() > 0) {
            log.warn("Query parameters along with the body parameter is not allowed");
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(SOAPToRESTConstants.SequenceGen.INDENT_PROPERTY, SOAPToRESTConstants.SequenceGen.INDENT_VALUE);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));
    } catch (ParserConfigurationException e) {
        handleException("Error occurred when building in sequence xml", e);
    } catch (TransformerConfigurationException e) {
        handleException("Error in transport configuration", e);
    } catch (TransformerException e) {
        handleException("Error occurred when transforming in sequence xml", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("parameter mapping for used in payload factory for soap operation:" + operationId + " is " + stringWriter.toString());
    }
    Map<String, String> paramMap = new HashMap<>();
    paramMap.put(operationId, processPayloadFactXML(stringWriter.toString()));
    return paramMap;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ModelImpl(io.swagger.models.ModelImpl) TransformerException(javax.xml.transform.TransformerException)

Example 52 with ModelImpl

use of io.swagger.models.ModelImpl in project carbon-apimgt by wso2.

the class WSDL11SOAPOperationExtractor method initModels.

/**
 * Initiallize SOAP to REST Operations
 *
 * @return true if extracting operations was successful
 */
private boolean initModels() throws APIMgtWSDLException {
    wsdlDefinition = getWSDLDefinition();
    boolean canProcess = true;
    targetNamespace = wsdlDefinition.getTargetNamespace();
    Types types = wsdlDefinition.getTypes();
    if (types != null) {
        typeList = types.getExtensibilityElements();
    }
    if (typeList != null) {
        for (Object ext : typeList) {
            if (ext instanceof Schema) {
                Schema schema = (Schema) ext;
                Map importedSchemas = schema.getImports();
                Element schemaElement = schema.getElement();
                NodeList schemaNodes = schemaElement.getChildNodes();
                schemaNodeList.addAll(SOAPOperationBindingUtils.list(schemaNodes));
                // gets types from imported schemas from the parent wsdl. Nested schemas will not be imported.
                if (importedSchemas != null) {
                    for (Object importedSchemaObj : importedSchemas.keySet()) {
                        String schemaUrl = (String) importedSchemaObj;
                        if (importedSchemas.get(schemaUrl) != null) {
                            Vector vector = (Vector) importedSchemas.get(schemaUrl);
                            for (Object schemaVector : vector) {
                                if (schemaVector instanceof SchemaImport) {
                                    Schema referencedSchema = ((SchemaImport) schemaVector).getReferencedSchema();
                                    if (referencedSchema != null && referencedSchema.getElement() != null) {
                                        if (referencedSchema.getElement().hasChildNodes()) {
                                            schemaNodeList.addAll(SOAPOperationBindingUtils.list(referencedSchema.getElement().getChildNodes()));
                                        } else {
                                            log.warn("The referenced schema : " + schemaUrl + " doesn't have any defined types");
                                        }
                                    } else {
                                        boolean isInlineSchema = false;
                                        for (Object aSchema : typeList) {
                                            if (schemaUrl.equalsIgnoreCase(((Schema) aSchema).getElement().getAttribute(TARGET_NAMESPACE_ATTRIBUTE))) {
                                                isInlineSchema = true;
                                                break;
                                            }
                                        }
                                        if (isInlineSchema) {
                                            log.debug(schemaUrl + " is already defined inline. Hence continue.");
                                        } else {
                                            log.warn("Cannot access referenced schema for the schema defined at: " + schemaUrl);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    log.info("No any imported schemas found in the given wsdl.");
                }
                List schemaIncludes = schema.getIncludes();
                for (Iterator iter = schemaIncludes.iterator(); iter.hasNext(); ) {
                    SchemaReference schemaInclude = (SchemaReference) iter.next();
                    Schema schemaImp = schemaInclude.getReferencedSchema();
                    String schemaLoc = schemaInclude.getSchemaLocationURI();
                    if (schemaImp != null && schemaImp.getElement() != null) {
                        if (schemaImp.getElement().hasChildNodes()) {
                            schemaNodeList.addAll(SOAPOperationBindingUtils.list(schemaImp.getElement().getChildNodes()));
                        } else {
                            log.warn("The referenced schema : " + schemaLoc + " doesn't have any defined types");
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new SwaggerFieldsExcludeStrategy()).create();
                    log.debug("swagger definition model map from the wsdl: " + gson.toJson(parameterModelMap));
                }
                if (schemaNodeList == null) {
                    log.warn("No schemas found in the type element for target namespace:" + schema.getDocumentBaseURI());
                }
            }
        }
        if (schemaNodeList != null) {
            for (Node node : schemaNodeList) {
                WSDLParamDefinition wsdlParamDefinition = new WSDLParamDefinition();
                ModelImpl model = new ModelImpl();
                Property currentProperty = null;
                try {
                    traverseTypeElement(node, null, model, currentProperty);
                } catch (APIManagementException e) {
                    throw new APIMgtWSDLException(e);
                }
                if (StringUtils.isNotBlank(model.getName())) {
                    parameterModelMap.put(model.getName(), model);
                }
                if (wsdlParamDefinition.getDefinitionName() != null) {
                    wsdlParamDefinitions.add(wsdlParamDefinition);
                }
            }
        } else {
            log.info("No schema is defined in the wsdl document");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully initialized an instance of " + this.getClass().getSimpleName() + " with a single WSDL.");
    }
    return canProcess;
}
Also used : Types(javax.wsdl.Types) SwaggerFieldsExcludeStrategy(org.wso2.carbon.apimgt.impl.wsdl.util.SwaggerFieldsExcludeStrategy) WSDLParamDefinition(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLParamDefinition) SchemaImport(javax.wsdl.extensions.schema.SchemaImport) GsonBuilder(com.google.gson.GsonBuilder) Schema(javax.wsdl.extensions.schema.Schema) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Gson(com.google.gson.Gson) SchemaReference(javax.wsdl.extensions.schema.SchemaReference) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) ModelImpl(io.swagger.models.ModelImpl) Map(java.util.Map) HashMap(java.util.HashMap) NamedNodeMap(org.w3c.dom.NamedNodeMap) Vector(java.util.Vector) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) LongProperty(io.swagger.models.properties.LongProperty) DecimalProperty(io.swagger.models.properties.DecimalProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) DateTimeProperty(io.swagger.models.properties.DateTimeProperty) RefProperty(io.swagger.models.properties.RefProperty) FloatProperty(io.swagger.models.properties.FloatProperty) DateProperty(io.swagger.models.properties.DateProperty) ObjectProperty(io.swagger.models.properties.ObjectProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty)

Example 53 with ModelImpl

use of io.swagger.models.ModelImpl in project carbon-apimgt by wso2.

the class WSDL11SOAPOperationExtractor method getSoapOutputParameterModel.

/**
 * Gets swagger output parameter model for a given soap operation
 *
 * @param bindingOperation soap operation
 * @return list of swagger models for the parameters
 * @throws APIMgtWSDLException
 */
private List<ModelImpl> getSoapOutputParameterModel(BindingOperation bindingOperation) throws APIMgtWSDLException {
    List<ModelImpl> outputParameterModelList = new ArrayList<>();
    Operation operation = bindingOperation.getOperation();
    if (operation != null) {
        Output output = operation.getOutput();
        if (output != null) {
            Message message = output.getMessage();
            if (message != null) {
                Map map = message.getParts();
                for (Object obj : map.entrySet()) {
                    Map.Entry entry = (Map.Entry) obj;
                    Part part = (Part) entry.getValue();
                    if (part != null) {
                        if (part.getElementName() != null) {
                            outputParameterModelList.add(parameterModelMap.get(part.getElementName().getLocalPart()));
                        } else {
                            if (part.getTypeName() != null && parameterModelMap.containsKey(part.getTypeName().getLocalPart())) {
                                outputParameterModelList.add(parameterModelMap.get(part.getTypeName().getLocalPart()));
                            } else {
                                ModelImpl model = new ModelImpl();
                                model.setType(ObjectProperty.TYPE);
                                model.setName(message.getQName().getLocalPart());
                                if (getPropertyFromDataType(part.getTypeName().getLocalPart()) instanceof RefProperty) {
                                    RefProperty property = (RefProperty) getPropertyFromDataType(part.getTypeName().getLocalPart());
                                    property.set$ref(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT + part.getTypeName().getLocalPart());
                                    model.addProperty(part.getName(), property);
                                } else {
                                    model.addProperty(part.getName(), getPropertyFromDataType(part.getTypeName().getLocalPart()));
                                }
                                parameterModelMap.put(model.getName(), model);
                                outputParameterModelList.add(model);
                            }
                        }
                    }
                }
            }
        }
    }
    return outputParameterModelList;
}
Also used : Message(javax.wsdl.Message) Part(javax.wsdl.Part) Output(javax.wsdl.Output) ArrayList(java.util.ArrayList) 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) ModelImpl(io.swagger.models.ModelImpl) Map(java.util.Map) HashMap(java.util.HashMap) NamedNodeMap(org.w3c.dom.NamedNodeMap) RefProperty(io.swagger.models.properties.RefProperty)

Example 54 with ModelImpl

use of io.swagger.models.ModelImpl in project carbon-apimgt by wso2.

the class WSDLSOAPOperationExtractorImplTestCase method testGetSwaggerModelForWSDLsWithCompositeBindings.

@Test
public void testGetSwaggerModelForWSDLsWithCompositeBindings() throws Exception {
    APIMWSDLReader wsdlReader = new APIMWSDLReader(Thread.currentThread().getContextClassLoader().getResource("wsdls/wsdl-with-composite-bindings/sampleservice.wsdl").toExternalForm());
    byte[] wsdlContent = wsdlReader.getWSDL();
    WSDL11SOAPOperationExtractor processor = SOAPOperationBindingUtils.getWSDL11SOAPOperationExtractor(wsdlContent, wsdlReader);
    Set<WSDLSOAPOperation> operations = processor.getWsdlInfo().getSoapBindingOperations();
    Assert.assertNotNull(operations);
    Map<String, ModelImpl> parameterModelMap = processor.getWsdlInfo().getParameterModelMap();
    Assert.assertNotNull(parameterModelMap);
}
Also used : APIMWSDLReader(org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader) WSDLSOAPOperation(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLSOAPOperation) ModelImpl(io.swagger.models.ModelImpl) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 55 with ModelImpl

use of io.swagger.models.ModelImpl in project carbon-apimgt by wso2.

the class WSDLSOAPOperationExtractorImplTestCase method testGetSwaggerModelForSimpleType.

@Test
public void testGetSwaggerModelForSimpleType() throws Exception {
    APIMWSDLReader wsdlReader = new APIMWSDLReader(Thread.currentThread().getContextClassLoader().getResource("wsdls/sample-service.wsdl").toExternalForm());
    byte[] wsdlContent = wsdlReader.getWSDL();
    WSDL11SOAPOperationExtractor processor = SOAPOperationBindingUtils.getWSDL11SOAPOperationExtractor(wsdlContent, wsdlReader);
    Map<String, ModelImpl> parameterModelMap = processor.getWsdlInfo().getParameterModelMap();
    Assert.assertNotNull(parameterModelMap);
    // get simple type
    Assert.assertNotNull(parameterModelMap.get("Condition"));
    Assert.assertEquals("string", parameterModelMap.get("Condition").getType());
    // get simple type inside complex type
    Assert.assertNotNull(parameterModelMap.get("ItemSearchRequest").getProperties().get("Availability"));
    Assert.assertEquals("string", parameterModelMap.get("ItemSearchRequest").getProperties().get("Availability").getType());
}
Also used : APIMWSDLReader(org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader) ModelImpl(io.swagger.models.ModelImpl) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

ModelImpl (io.swagger.models.ModelImpl)112 Test (org.testng.annotations.Test)46 Model (io.swagger.models.Model)43 Property (io.swagger.models.properties.Property)40 StringProperty (io.swagger.models.properties.StringProperty)32 RefProperty (io.swagger.models.properties.RefProperty)29 BodyParameter (io.swagger.models.parameters.BodyParameter)28 ArrayProperty (io.swagger.models.properties.ArrayProperty)27 RefModel (io.swagger.models.RefModel)24 IntegerProperty (io.swagger.models.properties.IntegerProperty)18 Swagger (io.swagger.models.Swagger)16 JavaType (com.fasterxml.jackson.databind.JavaType)15 Map (java.util.Map)15 MapProperty (io.swagger.models.properties.MapProperty)14 Test (org.junit.Test)14 Parameter (io.swagger.models.parameters.Parameter)12 HashMap (java.util.HashMap)12 ArrayModel (io.swagger.models.ArrayModel)11 ComposedModel (io.swagger.models.ComposedModel)11 ArrayList (java.util.ArrayList)11