Search in sources :

Example 41 with QueryParameter

use of io.swagger.models.parameters.QueryParameter in project java-chassis by ServiceComb.

the class TestPath method testUrlPathBuilder.

@Test
public void testUrlPathBuilder() throws Exception {
    Map<String, RestParam> paramMap = new HashMap<>();
    Parameter pathParameter = new PathParameter();
    pathParameter.setName("id");
    RestParam oRestParam = new RestParam(pathParameter, int.class);
    paramMap.put(oRestParam.getParamName(), oRestParam);
    Parameter queryParameter = new QueryParameter();
    queryParameter.setName("q");
    oRestParam = new RestParam(queryParameter, String.class);
    paramMap.put(oRestParam.getParamName(), oRestParam);
    URLPathBuilder oURLPathBuilder = new URLPathBuilder("/root/{id}", paramMap);
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("id", 100);
    parameters.put("q", "query");
    Assert.assertEquals("/root/100?q=query", oURLPathBuilder.createRequestPath(parameters));
    Assert.assertEquals("/root/100", oURLPathBuilder.createPathString(parameters));
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) HashMap(java.util.HashMap) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) URLPathBuilder(org.apache.servicecomb.common.rest.definition.path.URLPathBuilder) PathParameter(io.swagger.models.parameters.PathParameter) Test(org.junit.Test)

Example 42 with QueryParameter

use of io.swagger.models.parameters.QueryParameter in project java-chassis by ServiceComb.

the class QueryCodecTestBase method should_decode.

private void should_decode(HttpServletRequest request, Object decodedValue) {
    Class<?> targetType = decodedValue == null ? Object.class : decodedValue.getClass();
    QueryParameter queryParameter = new QueryParameter();
    queryParameter.setCollectionFormat(codec.getCodecName());
    if (targetType.isArray()) {
        queryParameter.setType(ArrayProperty.TYPE);
    }
    QueryProcessor queryProcessor = new QueryProcessor(queryParameter, TypeFactory.defaultInstance().constructType(targetType));
    Object values = codec.decode(queryProcessor, request);
    assertThat(values).isEqualTo(decodedValue);
}
Also used : QueryParameter(io.swagger.models.parameters.QueryParameter) QueryProcessor(org.apache.servicecomb.common.rest.codec.param.QueryProcessorCreator.QueryProcessor)

Example 43 with QueryParameter

use of io.swagger.models.parameters.QueryParameter 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 44 with QueryParameter

use of io.swagger.models.parameters.QueryParameter in project swagger-core by swagger-api.

the class ParameterProcessorTest method beanValidationDecimalMinTest.

@Test
public void beanValidationDecimalMinTest() throws NoSuchMethodException {
    final Method method = getClass().getDeclaredMethod("beanValidationDecimalMin", double.class, double.class);
    final Type[] genericParameterTypes = method.getGenericParameterTypes();
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    final QueryParameter inclusiveParam = (QueryParameter) ParameterProcessor.applyAnnotations(null, new QueryParameter(), genericParameterTypes[0], Arrays.asList(paramAnnotations[0]));
    assertNotNull(inclusiveParam);
    assertEquals(inclusiveParam.getMinimum(), new BigDecimal(5.5));
    assertNull(inclusiveParam.isExclusiveMinimum());
    final QueryParameter exclusiveParam = (QueryParameter) ParameterProcessor.applyAnnotations(null, new QueryParameter(), genericParameterTypes[1], Arrays.asList(paramAnnotations[1]));
    assertNotNull(exclusiveParam);
    assertEquals(exclusiveParam.getMinimum(), new BigDecimal(5.5));
    assertTrue(exclusiveParam.isExclusiveMinimum());
}
Also used : Type(java.lang.reflect.Type) QueryParameter(io.swagger.models.parameters.QueryParameter) Method(java.lang.reflect.Method) BigDecimal(java.math.BigDecimal) Test(org.testng.annotations.Test)

Example 45 with QueryParameter

use of io.swagger.models.parameters.QueryParameter in project swagger-core by swagger-api.

the class SecurityDefinitionTest method createModelWithSecurityRequirements.

@Test(description = "it should create a model with security requirements")
public void createModelWithSecurityRequirements() throws IOException {
    final Model personModel = ModelConverters.getInstance().read(Person.class).get("Person");
    final Model errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
    final Info info = new Info().version("1.0.0").title("Swagger Petstore");
    final Contact contact = new Contact().name("Swagger API Team").email("foo@bar.baz").url("http://swagger.io");
    info.setContact(contact);
    final Swagger swagger = new Swagger().info(info).host("petstore.swagger.io").scheme(Scheme.HTTP).consumes("application/json").produces("application/json").model("Person", personModel).model("Error", errorModel);
    swagger.securityDefinition("githubAccessCode", new OAuth2Definition().accessCode("http://foo.com/accessCode", "http://foo.com/tokenUrl").scope("user:email", "Grants read access to a user’s email addresses."));
    final Operation get = new Operation().produces("application/json").summary("finds pets in the system").description("a longer description").tag("Pet Operations").operationId("get pet by id");
    get.parameter(new QueryParameter().name("tags").description("tags to filter by").required(false).property(new StringProperty()));
    get.parameter(new PathParameter().name("petId").description("pet to fetch").property(new LongProperty()));
    final Response response = new Response().description("pets returned").schema(new RefProperty().asDefault("Person"));
    final Response errorResponse = new Response().description("error response").schema(new RefProperty().asDefault("Error"));
    get.response(200, response).defaultResponse(errorResponse).security(new SecurityRequirement("internal_oauth2").scope("user:email")).security(new SecurityRequirement("api_key"));
    swagger.path("/pets", new Path().get(get));
    final String json = ResourceUtils.loadClassResource(getClass(), "ModelWithSecurityRequirements.json");
    SerializationMatchers.assertEqualsToJson(swagger, json);
}
Also used : Path(io.swagger.models.Path) QueryParameter(io.swagger.models.parameters.QueryParameter) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) Error(io.swagger.models.Error) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) Info(io.swagger.models.Info) PathParameter(io.swagger.models.parameters.PathParameter) Contact(io.swagger.models.Contact) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) Swagger(io.swagger.models.Swagger) LongProperty(io.swagger.models.properties.LongProperty) Model(io.swagger.models.Model) Person(io.swagger.models.Person) SecurityRequirement(io.swagger.models.SecurityRequirement) Test(org.testng.annotations.Test)

Aggregations

QueryParameter (io.swagger.models.parameters.QueryParameter)88 Test (org.testng.annotations.Test)58 Parameter (io.swagger.models.parameters.Parameter)41 PathParameter (io.swagger.models.parameters.PathParameter)34 BodyParameter (io.swagger.models.parameters.BodyParameter)28 Swagger (io.swagger.models.Swagger)25 HeaderParameter (io.swagger.models.parameters.HeaderParameter)15 Operation (io.swagger.models.Operation)11 FormParameter (io.swagger.models.parameters.FormParameter)11 Test (org.junit.Test)11 SerializableParameter (io.swagger.models.parameters.SerializableParameter)10 StringProperty (io.swagger.models.properties.StringProperty)10 Path (io.swagger.models.Path)9 RefModel (io.swagger.models.RefModel)9 Type (java.lang.reflect.Type)9 BigDecimal (java.math.BigDecimal)9 HashMap (java.util.HashMap)9 RefProperty (io.swagger.models.properties.RefProperty)8 Response (io.swagger.models.Response)7 Method (java.lang.reflect.Method)7