Search in sources :

Example 21 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method getConfigurationProperties.

/**
 * Get the configuration properties of UI
 */
@Override
public List<Property> getConfigurationProperties() {
    List<Property> configProperties = new ArrayList<Property>();
    Property smsUrl = new Property();
    smsUrl.setName(SMSOTPConstants.SMS_URL);
    smsUrl.setDisplayName("SMS URL");
    smsUrl.setRequired(true);
    smsUrl.setDescription("Enter client sms url value. If the phone number and text message are in URL, " + "specify them as $ctx.num and $ctx.msg");
    smsUrl.setDisplayOrder(0);
    configProperties.add(smsUrl);
    Property httpMethod = new Property();
    httpMethod.setName(SMSOTPConstants.HTTP_METHOD);
    httpMethod.setDisplayName("HTTP Method");
    httpMethod.setRequired(true);
    httpMethod.setDescription("Enter the HTTP Method used by the SMS API");
    httpMethod.setDisplayOrder(1);
    configProperties.add(httpMethod);
    Property headers = new Property();
    headers.setName(SMSOTPConstants.HEADERS);
    headers.setDisplayName("HTTP Headers");
    headers.setRequired(false);
    headers.setDescription("Enter the headers used by the API separated by comma, with the Header name and value " + "separated by \":\". If the phone number and text message are in Headers, specify them as $ctx.num and $ctx.msg");
    headers.setDisplayOrder(2);
    configProperties.add(headers);
    Property payload = new Property();
    payload.setName(SMSOTPConstants.PAYLOAD);
    payload.setDisplayName("HTTP Payload");
    payload.setRequired(false);
    payload.setDescription("Enter the HTTP Payload used by the SMS API. If the phone number and text message are " + "in Payload, specify them as $ctx.num and $ctx.msg");
    payload.setDisplayOrder(3);
    configProperties.add(payload);
    Property httpResponse = new Property();
    httpResponse.setName(SMSOTPConstants.HTTP_RESPONSE);
    httpResponse.setDisplayName("HTTP Response Code");
    httpResponse.setRequired(false);
    httpResponse.setDescription("Enter the HTTP response code the API sends upon successful call. Leave empty if unknown");
    httpResponse.setDisplayOrder(4);
    configProperties.add(httpResponse);
    return configProperties;
}
Also used : ArrayList(java.util.ArrayList) Property(org.wso2.carbon.identity.application.common.model.Property)

Example 22 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project jaggery by wso2.

the class ResourceHostObject method jsGet_content.

public Object jsGet_content() throws ScriptException {
    try {
        Object result = this.resource.getContent();
        String mediaType = this.resource.getMediaType();
        if (result instanceof byte[]) {
            // if mediaType is xml related one, we return an e4x xml object
            if (mediaType != null) {
                if (mediaType.matches(".*[\\/].*[xX][mM][lL].*")) {
                    return context.newObject(this, "XML", new Object[] { new String((byte[]) result) });
                }
            }
            return new String((byte[]) result);
        } else if (result instanceof String[]) {
            String[] content = (String[]) result;
            return context.newArray(this, Arrays.copyOf(content, content.length, Object[].class));
        } else {
            return Context.toObject(result, this);
        }
    } catch (RegistryException e) {
        throw new ScriptException("Registry Exception while reading content property", e);
    }
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) XMLObject(org.mozilla.javascript.xml.XMLObject) RegistryException(org.wso2.carbon.registry.api.RegistryException)

Example 23 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property 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 24 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property 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 25 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property 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)

Aggregations

HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)32 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 Resource (org.wso2.carbon.registry.core.Resource)23 Map (java.util.Map)21 Test (org.junit.Test)21 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 DataResponse (org.wso2.carbon.bpmn.rest.model.common.DataResponse)17 API (org.wso2.carbon.apimgt.api.model.API)16 UserStoreException (org.wso2.carbon.user.api.UserStoreException)16 Path (javax.ws.rs.Path)14 Produces (javax.ws.rs.Produces)14 JSONObject (org.json.simple.JSONObject)14 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)14 List (java.util.List)13 IOException (java.io.IOException)11 QName (javax.xml.namespace.QName)11 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)11 Properties (java.util.Properties)10 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)10