io.swagger.models.parameters.PathParameter Java Examples

The following examples show how to use io.swagger.models.parameters.PathParameter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SwaggerUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method will generate path and query parameters in the swagger document.
 *
 * @param method        method of API resource.
 * @param operation     swagger operation object.
 * @param parameterList list of parameters.
 */
private static void generatePathAndQueryParameters(String method, Operation operation,
                                                   List<AxisResourceParameter> parameterList) {

    if (!parameterList.isEmpty()) {
        for (AxisResourceParameter resourceParameter : parameterList) {
            AxisResourceParameter.ParameterType resourceParameterType =
                    resourceParameter.getParameterType();
            if (resourceParameterType.equals(AxisResourceParameter.ParameterType.URL_PARAMETER)) {
                PathParameter pathParameter = new PathParameter();
                pathParameter.setName(resourceParameter.getParameterName());
                pathParameter.setType(resourceParameter.getParameterDataType());
                pathParameter.required(true);
                operation.addParameter(pathParameter);
            } else if (resourceParameterType
                    .equals(AxisResourceParameter.ParameterType.QUERY_PARAMETER) && "GET".equals(method)) {
                //  Currently handling query parameter only for GET requests.
                QueryParameter queryParameter = new QueryParameter();
                queryParameter.setName(resourceParameter.getParameterName());
                queryParameter.setType(resourceParameter.getParameterDataType());
                queryParameter.required(true);
                operation.addParameter(queryParameter);
            }
        }
    }
}
 
Example #2
Source File: AbstractOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected Parameter createParameter(HttpParameterType httpParameterType) {
  switch (httpParameterType) {
    case PATH:
      return new PathParameter();
    case QUERY:
      return new QueryParameter();
    case HEADER:
      return new HeaderParameter();
    case FORM:
      return new FormParameter();
    case COOKIE:
      return new CookieParameter();
    case BODY:
      return new BodyParameter();
    default:
      throw new IllegalStateException("not support httpParameterType " + httpParameterType);
  }
}
 
Example #3
Source File: TestPath.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source File: URLPathBuilderTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testNormal() throws Exception {
  Map<String, RestParam> paramMap = new LinkedHashMap<>();
  addParam("p0", int.class, PathParameter::new, paramMap);
  addParam("p1", String.class, PathParameter::new, paramMap);
  addParam("q0", int.class, QueryParameter::new, paramMap);
  addParam("q1", String.class, QueryParameter::new, paramMap);

  URLPathBuilder urlPathBuilder = new URLPathBuilder("/path/{p0}/and/{p1}", paramMap);
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("p0", 10);
  parameters.put("p1", "abcPath");
  parameters.put("q0", 11);
  parameters.put("q1", "queryABC");
  Assert.assertEquals("/path/10/and/abcPath?q0=11&q1=queryABC",
      urlPathBuilder.createRequestPath(parameters));
  Assert.assertEquals("/path/10/and/abcPath",
      urlPathBuilder.createPathString(parameters));
}
 
Example #5
Source File: URLPathBuilderTest.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegexPathParam() throws Exception {
  Map<String, RestParam> paramMap = new LinkedHashMap<>();
  addParam("p0", int.class, PathParameter::new, paramMap);
  addParam("p1", String.class, PathParameter::new, paramMap);
  addParam("q0", int.class, QueryParameter::new, paramMap);
  addParam("q1", String.class, QueryParameter::new, paramMap);

  URLPathBuilder urlPathBuilder = new URLPathBuilder("/path/{p0 : .*}/and/{p1:.*}", paramMap);
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("p0", 10);
  parameters.put("p1", "abcPath");
  parameters.put("q0", 11);
  parameters.put("q1", "queryABC");
  Assert.assertEquals("/path/10/and/abcPath?q0=11&q1=queryABC",
      urlPathBuilder.createRequestPath(parameters));
  Assert.assertEquals("/path/10/and/abcPath",
      urlPathBuilder.createPathString(parameters));
}
 
Example #6
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new operation object using the URI template object
 *
 * @param resource API resource data
 * @return a new operation object using the URI template object
 */
private Operation createOperation(SwaggerData.Resource resource) {
    Operation operation = new Operation();
    List<String> pathParams = getPathParamNames(resource.getPath());
    for (String pathParam : pathParams) {
        PathParameter pathParameter = new PathParameter();
        pathParameter.setName(pathParam);
        pathParameter.setType("string");
        operation.addParameter(pathParameter);
    }

    updateOperationManagedInfo(resource, operation);

    Response response = new Response();
    response.setDescription("OK");
    operation.addResponse(APIConstants.SWAGGER_RESPONSE_200, response);
    return operation;
}
 
Example #7
Source File: TestClassUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void isRawJsonType() {
  PathParameter param = new PathParameter();

  Assert.assertFalse(SwaggerUtils.isRawJsonType(param));

  param.setVendorExtension(SwaggerConst.EXT_RAW_JSON_TYPE, Boolean.FALSE);
  Assert.assertFalse(SwaggerUtils.isRawJsonType(param));

  param.setVendorExtension(SwaggerConst.EXT_RAW_JSON_TYPE, Boolean.TRUE);
  Assert.assertTrue(SwaggerUtils.isRawJsonType(param));
}
 
Example #8
Source File: URLPathBuilderTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncode() throws Exception {
  Map<String, RestParam> paramMap = new LinkedHashMap<>();
  addParam("p", String.class, PathParameter::new, paramMap);
  addParam("q", String.class, QueryParameter::new, paramMap);

  URLPathBuilder urlPathBuilder = new URLPathBuilder("/path/{p}", paramMap);
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("p", "ab%% %cd%");
  parameters.put("q", "ab%% %cd%");
  Assert.assertEquals("/path/ab%25%25%20%25cd%25?q=ab%25%25+%25cd%25",
      urlPathBuilder.createRequestPath(parameters));
  Assert.assertEquals("/path/ab%25%25%20%25cd%25",
      urlPathBuilder.createPathString(parameters));
}
 
Example #9
Source File: TestPathProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreate() {
  ParamValueProcessorCreator creator =
      ParamValueProcessorCreatorManager.INSTANCE.findValue(PathProcessorCreator.PARAMTYPE);
  Parameter parameter = new PathParameter();
  parameter.setName("path");

  ParamValueProcessor processor = creator.create(parameter, String.class);

  Assert.assertEquals(PathProcessor.class, processor.getClass());
}
 
Example #10
Source File: PathSegment.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
protected Collection<? extends Parameter> localParameters() {
    if(localParams == null) {
        if(node != null) {
            log.debug("processing parameters from attached node");
            final Set<String> existingNames = parent.params().stream().map(Parameter::getName).collect(Collectors.toSet());

            localParams = node.getKeyDefinition().stream()
                    .map(k -> {

                        final String name = generateName(k, existingNames);

                        final PathParameter param = new PathParameter()
                                .name(name);

                        final Optional<LeafSchemaNode> keyNode = node.getChildNodes().stream()
                                .filter(n -> n instanceof LeafSchemaNode)
                                .filter(n -> n.getQName().equals(k))
                                .map(n -> ((LeafSchemaNode)n))
                                .findFirst();

                        if(keyNode.isPresent()) {
                            final LeafSchemaNode kN = keyNode.get();
                            param
                                .description("Id of " + node.getQName().getLocalName())
                                .property(converter.convert(kN.getType(), kN));
                        }

                        return param;
                    })
                    .collect(Collectors.toList());
        } else {
            localParams = Collections.emptyList();
        }
    }

    return localParams;
}
 
Example #11
Source File: ResourceReaderExtension.java    From mdw with Apache License 2.0 5 votes vote down vote up
private Parameter createParam(String paramType) {
    if ("path".equals(paramType))
        return new PathParameter();
    else if ("query".equals(paramType))
        return new QueryParameter();
    else if ("form".equals(paramType))
        return new FormParameter();
    else if ("formData".equals(paramType))
        return new FormParameter();
    else if ("header".equals(paramType))
        return new HeaderParameter();
    else if ("body".equals(paramType))
        return new BodyParameter();
    return null;
}
 
Example #12
Source File: SwaggerWorkflowReader.java    From mdw with Apache License 2.0 5 votes vote down vote up
private io.swagger.models.parameters.Parameter createParam(ParameterType paramType) {
    if (paramType == ParameterType.Path)
        return new PathParameter();
    else if (paramType == ParameterType.Query)
        return new QueryParameter();
    else if (paramType == ParameterType.Form)
        return new FormParameter();
    else if (paramType == ParameterType.Header)
        return new HeaderParameter();
    else if (paramType == ParameterType.Body)
        return new BodyParameter();
    return null;
}
 
Example #13
Source File: PathProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  JavaType targetType =
      genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
  return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true);
}
 
Example #14
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param operation
 * @return
 */
private String getMethodParameters(Operation operation) {
	String methodParameter = "";
	List<Parameter> parameters = operation.getParameters();

	for (Parameter parameter : parameters) {
		if (StringUtils.isNotEmpty(methodParameter)) {
			methodParameter = new StringBuilder().append(methodParameter).append(",").toString();
		}

		if (parameter instanceof PathParameter) {
			methodParameter = new StringBuilder().append(methodParameter)
					.append(toTitleCase(((PathParameter) parameter).getType())).append(" ")
					.append(((PathParameter) parameter).getName()).toString();
		} else if (parameter instanceof QueryParameter) {
			Property queryParameterProperty = ((QueryParameter) parameter).getItems();

			if (queryParameterProperty instanceof RefProperty) {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((RefProperty) queryParameterProperty).getSimpleRef())).append("[] ")
						.append(((BodyParameter) parameter).getName()).toString();
			} else if (queryParameterProperty instanceof StringProperty) {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((StringProperty) queryParameterProperty).getType())).append("[] ")
						.append(((QueryParameter) parameter).getName()).toString();
			} else {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((QueryParameter) parameter).getType())).append(" ")
						.append(((QueryParameter) parameter).getName()).toString();
			}
		} else if (parameter instanceof BodyParameter) {
			Model bodyParameter = ((BodyParameter) parameter).getSchema();

			if (bodyParameter instanceof RefModel) {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((RefModel) bodyParameter).getSimpleRef())).append(" ")
						.append(((BodyParameter) parameter).getName()).toString();
			} else if (bodyParameter instanceof ArrayModel) {
				Property propertyObject = ((ArrayModel) bodyParameter).getItems();

				if (propertyObject instanceof RefProperty) {
					methodParameter = new StringBuilder().append(methodParameter)
							.append(toTitleCase(((RefProperty) propertyObject).getSimpleRef())).append("[] ")
							.append(((BodyParameter) parameter).getName()).toString();
				}
			}
		} else if (parameter instanceof FormParameter) {
			methodParameter = new StringBuilder().append(methodParameter)
					.append(toTitleCase(((FormParameter) parameter).getType())).append(" ")
					.append(((FormParameter) parameter).getName()).toString();
		}
	}

	return methodParameter;
}
 
Example #15
Source File: SwaggerAnnotationsReader.java    From mdw with Apache License 2.0 4 votes vote down vote up
private void read(ReaderContext context) {
    final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class);
    if (swaggerDefinition != null) {
        readSwaggerConfig(swaggerDefinition);
    }
    for (Method method : context.getCls().getMethods()) {
        if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) {
            continue;
        }
        final Operation operation = new Operation();
        String operationPath = null;
        String httpMethod = null;

        final Type[] genericParameterTypes = method.getGenericParameterTypes();
        final Annotation[][] paramAnnotations = method.getParameterAnnotations();

        // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension
        // for (ReaderExtension extension : ReaderExtensions.getExtensions()) {
        for (ReaderExtension extension : getExtensions()) {
            if (operationPath == null) {
                operationPath = extension.getPath(context, method);
            }
            if (httpMethod == null) {
                httpMethod = extension.getHttpMethod(context, method);
            }
            if (operationPath == null || httpMethod == null) {
                continue;
            }

            if (extension.isReadable(context)) {
                extension.setDeprecated(operation, method);
                extension.applyConsumes(context, operation, method);
                extension.applyProduces(context, operation, method);
                extension.applyOperationId(operation, method);
                extension.applySummary(operation, method);
                extension.applyDescription(operation, method);
                extension.applySchemes(context, operation, method);
                extension.applySecurityRequirements(context, operation, method);
                extension.applyTags(context, operation, method);
                extension.applyResponses(context, operation, method);
                extension.applyImplicitParameters(context, operation, method);
                for (int i = 0; i < genericParameterTypes.length; i++) {
                    extension.applyParameters(context, operation, genericParameterTypes[i], paramAnnotations[i]);
                }
            }
        }

        if (httpMethod != null && operationPath != null) {
            if (operation.getResponses() == null) {
                operation.defaultResponse(new Response().description("OK"));
            }
            else {
                for (String k : operation.getResponses().keySet()) {
                    if (k.equals("200")) {
                        Response response = operation.getResponses().get(k);
                        if ("successful operation".equals(response.getDescription()))
                            response.setDescription("OK");
                    }
                }
            }

            final Map<String,String> regexMap = new HashMap<>();
            final String parsedPath = PathUtils.parsePath(operationPath, regexMap);

            if (parsedPath != null) {
                // check for curly path params
                for (String seg : parsedPath.split("/")) {
                    if (seg.startsWith("{") && seg.endsWith("}")) {
                        String segName = seg.substring(1, seg.length() - 1);
                        boolean declared = false;
                        for (Parameter opParam : operation.getParameters()) {
                            if ("path".equals(opParam.getIn()) && segName.equals(opParam.getName())) {
                                declared = true;
                                break;
                            }
                        }
                        if (!declared) {
                            // add it for free
                            PathParameter pathParam = new PathParameter();
                            pathParam.setName(segName);
                            pathParam.setRequired(false);
                            pathParam.setDefaultValue("");
                            operation.parameter(pathParam);
                        }
                    }
                }
            }


            Path path = swagger.getPath(parsedPath);
            if (path == null) {
                path = new Path();
                swagger.path(parsedPath, path);
            }
            path.set(httpMethod.toLowerCase(), operation);
        }
    }
}
 
Example #16
Source File: MappingConverterImplTest.java    From binder-swagger-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Test
public void testMtoParameters_Multiple() {
    List<Parameter> params = converter.mToParameters("", mapping(
            field("id", $(intv()).in("path").desc("id").$$),
            field("data", $(mapping(
                    field("id", $(intv()).desc("id").$$),
                    field("name", $(text(required())).desc("name").$$)
            )).in("body").$$)
    ));

    assertEquals(params.size(), 2);

    ///
    assertTrue(params.get(0) instanceof PathParameter);
    PathParameter p1 = (PathParameter) params.get(0);

    assertEquals(p1.getType(), "integer");
    assertEquals(p1.getFormat(), "int32");
    assertEquals(p1.getDescription(), "id");
    assertEquals(p1.getRequired(), true);

    ///
    assertTrue(params.get(1) instanceof BodyParameter);
    BodyParameter p2 = (BodyParameter) params.get(1);
    ModelImpl model = (ModelImpl) p2.getSchema();

    assertEquals(model.getType(), "object");
    assertEquals(model.getRequired(), Arrays.asList("name"));
    assertTrue(model.getProperties() != null);
    assertEquals(model.getProperties().size(), 2);
    assertTrue(model.getProperties().get("id") instanceof IntegerProperty);
    assertTrue(model.getProperties().get("name") instanceof StringProperty);

    /// 'in' is required!!!
    try {
        List<Parameter> params1 = converter.mToParameters("", mapping(
                field("id", $(intv()).desc("id").$$),
                field("data", $(mapping(
                        field("id", $(intv()).desc("id").$$),
                        field("name", $(text(required())).desc("name").$$)
                )).in("body").$$)
        ));
        assertEquals(false, "shouldn't happen");
    } catch (Exception e) {
        assertEquals(e.getMessage(), "in is required!!!");
    }
}