Java Code Examples for io.swagger.models.Operation#getParameters()

The following examples show how to use io.swagger.models.Operation#getParameters() . 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 servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Provide a method to validate swagger. This method is now implemented to check common errors, and the logic
 * will be changed when necessary. For internal use only.
 */
public static void validateSwagger(Swagger swagger) {
  Map<String, Path> paths = swagger.getPaths();
  if (paths == null) {
    return;
  }

  for (Path path : paths.values()) {
    Operation operation = path.getPost();
    if (operation == null) {
      continue;
    }

    for (Parameter parameter : operation.getParameters()) {
      if (BodyParameter.class.isInstance(parameter) &&
          ((BodyParameter) parameter).getSchema() == null) {
        throw new ServiceCombException("swagger validator: body parameter schema is empty.");
      }
    }
  }
}
 
Example 2
Source File: SwaggerToProtoGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void fillRequestType(Operation operation, ProtoMethod protoMethod) {
  List<Parameter> parameters = operation.getParameters();
  if (parameters.isEmpty()) {
    addImports(ProtoConst.EMPTY_PROTO);
    protoMethod.setArgTypeName(ProtoConst.EMPTY.getCanonicalName());
    return;
  }

  if (parameters.size() == 1) {
    String type = convertSwaggerType(parameters.get(0));
    if (messages.contains(type)) {
      protoMethod.setArgTypeName(type);
      return;
    }
  }

  String wrapName = StringUtils.capitalize(operation.getOperationId()) + "RequestWrap";
  createWrapArgs(wrapName, parameters);

  protoMethod.setArgTypeName(wrapName);
}
 
Example 3
Source File: SwaggerInventory.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void process(Operation operation) {
    this.operations.add(operation);
    Iterator var2;
    if(operation.getParameters() != null) {
        var2 = operation.getParameters().iterator();

        while(var2.hasNext()) {
            Parameter key = (Parameter)var2.next();
            this.process(key);
        }
    }

    if(operation.getResponses() != null) {
        var2 = operation.getResponses().keySet().iterator();

        while(var2.hasNext()) {
            String key1 = (String)var2.next();
            Response response = (Response)operation.getResponses().get(key1);
            this.process(response);
        }
    }

}
 
Example 4
Source File: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createCommonParameters() throws Exception {
    reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class));
    Swagger result = reader.read(CommonParametersApi.class);
    Parameter headerParam = result.getParameter("headerParam");
    assertTrue(headerParam instanceof HeaderParameter);
    Parameter queryParam = result.getParameter("queryParam");
    assertTrue(queryParam instanceof QueryParameter);

    result = reader.read(ReferenceCommonParametersApi.class);
    Operation get = result.getPath("/apath").getGet();
    List<Parameter> parameters = get.getParameters();
    for (Parameter parameter : parameters) {
        assertTrue(parameter instanceof RefParameter);
    }

    ObjectMapper mapper = Json.mapper();
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    String json = jsonWriter.writeValueAsString(result);
    JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-common-parameters.json"));
    JsonAssert.assertJsonEquals(expectJson, json);
}
 
Example 5
Source File: FlaskConnexionCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    // need vendor extensions for x-swagger-router-controller
    Map<String, Path> paths = swagger.getPaths();
    if(paths != null) {
        for(String pathname : paths.keySet()) {
            Path path = paths.get(pathname);
            Map<HttpMethod, Operation> operationMap = path.getOperationMap();
            if(operationMap != null) {
                for(HttpMethod method : operationMap.keySet()) {
                    Operation operation = operationMap.get(method);
                    String tag = "default";
                    if(operation.getTags() != null && operation.getTags().size() > 0) {
                        tag = operation.getTags().get(0);
                    }
                    String operationId = operation.getOperationId();
                    if(operationId == null) {
                        operationId = getOrGenerateOperationId(operation, pathname, method.toString());
                    }
                    operation.setOperationId(toOperationId(operationId));
                    if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) {
                        operation.getVendorExtensions().put(
                                "x-swagger-router-controller",
                                controllerPackage + "." + toApiFilename(tag)
                        );
                    }
                    for (Parameter param: operation.getParameters()) {
                        // sanitize the param name but don't underscore it since it's used for request mapping
                        String name = param.getName();
                        String paramName = sanitizeName(name);
                        if (!paramName.equals(name)) {
                            LOGGER.warn(name + " cannot be used as parameter name with flask-connexion and was sanitized as " + paramName);
                        }
                        param.setName(paramName);
                    }
                }
            }
        }
    }
}
 
Example 6
Source File: AbstractJavaCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    if (swagger == null || swagger.getPaths() == null){
        return;
    }
    for (String pathname : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathname);
        if (path.getOperations() == null){
            continue;
        }
        for (Operation operation : path.getOperations()) {
            boolean hasFormParameters = false;
            boolean hasBodyParameters = false;
            for (Parameter parameter : operation.getParameters()) {
                if (parameter instanceof FormParameter) {
                    hasFormParameters = true;
                }
                if (parameter instanceof BodyParameter) {
                    hasBodyParameters = true;
                }
            }
            if (hasBodyParameters || hasFormParameters){
                String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
                String contentType =  operation.getConsumes() == null || operation.getConsumes().isEmpty() ? defaultContentType : operation.getConsumes().get(0);
                operation.setVendorExtension("x-contentType", contentType);
            }
            String accepts = getAccept(operation);
            operation.setVendorExtension("x-accepts", accepts);
        }
    }
}
 
Example 7
Source File: ApexClientCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path,
                                      String httpMethod,
                                      Operation operation,
                                      Map<String, Model> definitions,
                                      Swagger swagger) {
    Boolean hasFormParams = false;
    for (Parameter p : operation.getParameters()) {
        if ("formData".equals(p.getIn())) {
            hasFormParams = true;
            break;
        }
    }

    // only support serialization into JSON and urlencoded forms for now
    operation.setConsumes(
        Collections.singletonList(hasFormParams
            ? "application/x-www-form-urlencoded"
            : "application/json"));

    // only support deserialization from JSON for now
    operation.setProduces(Collections.singletonList("application/json"));

    CodegenOperation op = super.fromOperation(
        path, httpMethod, operation, definitions, swagger);
    if (op.getHasExamples()) {
        // prepare examples for Apex test classes
        Property responseProperty = findMethodResponse(operation.getResponses()).getSchema();
        String deserializedExample = toExampleValue(responseProperty);
        for (Map<String, String> example : op.examples) {
            example.put("example", escapeText(example.get("example")));
            example.put("deserializedExample", deserializedExample);
        }
    }

    return op;
}
 
Example 8
Source File: ReaderTest.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({  "serial" })
	@Test
	public void testApplyParameters(){
		Swagger swagger = new Swagger();
		Reader.read(swagger, new HashMap<Class<?>, Object>(){{
			put(InterfaceServiceTest.class, new InterfaceServiceImplTest());
		}}, "/h");
		
//		System.out.println(Json.pretty(swagger));
		Map<String, Path> paths = swagger.getPaths();
		Assert.assertEquals(paths.size(), 4);
		
		Path path = swagger.getPaths().get("/h/com.deepoove.swagger.dubbo.api.InterfaceServiceTest/test");
		Assert.assertNotNull(path);
		Operation operation = path.getOperationMap().get(HttpMethod.POST);
		Assert.assertNotNull(operation);
		Assert.assertNotNull(operation.getParameters());
		Assert.assertEquals(operation.getSummary(), "查询用户");
		
		List<Parameter> parameters = operation.getParameters();
		Assert.assertEquals(parameters.get(0).getName(), "para");
		Assert.assertEquals(parameters.get(1).getName(), "code");
		
		Assert.assertTrue(parameters.get(0).getRequired());
		Assert.assertEquals(parameters.get(0).getDescription(), "参数");
		
		
		path = swagger.getPaths().get("/h/com.deepoove.swagger.dubbo.api.InterfaceServiceTest/login/bypwd");
        Assert.assertNotNull(path);
        path = swagger.getPaths().get("/h/com.deepoove.swagger.dubbo.api.InterfaceServiceTest/login");
        Assert.assertNotNull(path);
		
	}
 
Example 9
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all parameters for the operation. Note: According to the spec, parameters defined
 * inside the operations overrides the parameters defined in the path scope which has the same
 * name and location values (example name : 'shelveId' and location : 'query').
 */
public static ImmutableList<Parameter> getAllResolvedParameters(
    Operation operation, Path parentPath, final DiagCollector diagCollector, Location location) {
  List<Parameter> allResolvedParameters = new ArrayList<>();
  // First populate all the parameters defined in the operation.
  if (operation.getParameters() != null) {
    ImmutableList<Parameter> resolvedParameters =
        getResolvedParameters(
            diagCollector, ImmutableList.copyOf(operation.getParameters()), location);
    allResolvedParameters.addAll(resolvedParameters);
  }
  FluentIterable<Parameter> fluentAllParameters = FluentIterable.from(allResolvedParameters);

  // Now populate shared parameters that were not overridden inside the operation.
  if (parentPath.getParameters() != null) {
    ImmutableList<Parameter> resolvedSharedParameters =
        getResolvedParameters(
            diagCollector, ImmutableList.copyOf(parentPath.getParameters()), location);
    for (final Parameter sharedParam : resolvedSharedParameters) {
      boolean overriddenInOperation =
          fluentAllParameters.anyMatch(
              new Predicate<Parameter>() {
                @Override
                public boolean apply(Parameter parameter) {
                  return parameter.getName().equals(sharedParam.getName())
                      && parameter.getIn().equals(sharedParam.getIn());
                }
              });
      if (!overriddenInOperation) {
        allResolvedParameters.add(sharedParam);
      }
    }
  }
  return ImmutableList.copyOf(allResolvedParameters);
}
 
Example 10
Source File: SequenceGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void populateParametersFromOperation(Operation operation, Map<String, Model> definitions,
        Map<String, String> parameterJsonPathMapping, Map<String, String> queryParameters) {

    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>());

                    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: " + defName, e);
                    }
                }
            }
        }
        if (parameter instanceof QueryParameter) {
            String type = ((QueryParameter) parameter).getType();
            queryParameters.put(name, type);
        }
    }
}
 
Example 11
Source File: DefaultCodegen.java    From TypeScript-Microservices with MIT License 4 votes vote down vote up
/**
 * Return the example path
 *
 * @param path the path of the operation
 * @param operation Swagger operation object
 * @return string presentation of the example path
 */
@SuppressWarnings("static-method")
public String generateExamplePath(String path, Operation operation) {
    StringBuilder sb = new StringBuilder();
    sb.append(path);

    if (operation.getParameters() != null) {
        int count = 0;

        for (Parameter param : operation.getParameters()) {
            if (param instanceof QueryParameter) {
                StringBuilder paramPart = new StringBuilder();
                QueryParameter qp = (QueryParameter) param;

                if (count == 0) {
                    paramPart.append("?");
                } else {
                    paramPart.append(",");
                }
                count += 1;
                if (!param.getRequired()) {
                    paramPart.append("[");
                }
                paramPart.append(param.getName()).append("=");
                paramPart.append("{");
                if (qp.getCollectionFormat() != null) {
                    paramPart.append(param.getName()).append("1");
                    if ("csv".equals(qp.getCollectionFormat())) {
                        paramPart.append(",");
                    } else if ("pipes".equals(qp.getCollectionFormat())) {
                        paramPart.append("|");
                    } else if ("tsv".equals(qp.getCollectionFormat())) {
                        paramPart.append("\t");
                    } else if ("multi".equals(qp.getCollectionFormat())) {
                        paramPart.append("&").append(param.getName()).append("=");
                        paramPart.append(param.getName()).append("2");
                    }
                } else {
                    paramPart.append(param.getName());
                }
                paramPart.append("}");
                if (!param.getRequired()) {
                    paramPart.append("]");
                }
                sb.append(paramPart.toString());
            }
        }
    }

    return sb.toString();
}
 
Example 12
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 13
Source File: ImportController.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
private void swaggerToRFConverter(String projectId, String name, MultipartFile file) throws IOException {
// MultipartFile file
File tempFile = File.createTempFile("RF_SWAGGER_IMPORT", "JSON");
file.transferTo(tempFile);
Swagger swagger = new SwaggerParser().read(tempFile.getAbsolutePath());

String host = swagger.getHost();
String basePath = swagger.getBasePath();

Info info = swagger.getInfo();
String title = info.getTitle();
String description = info.getDescription();

NodeDTO folderNode = createFolder(projectId, title);
folderNode.setDescription(description);

ConversationDTO conversationDTO;

Map<String, Path> paths = swagger.getPaths();
Set<String> keySet = paths.keySet();
for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {
    String pathKey = iterator.next();
    Path path = paths.get(pathKey);

    Map<HttpMethod, Operation> operationMap = path.getOperationMap();
    Set<HttpMethod> operationsKeySet = operationMap.keySet();
    for (Iterator<HttpMethod> operIterator = operationsKeySet.iterator(); operIterator.hasNext();) {
	HttpMethod httpMethod = operIterator.next();
	Operation operation = operationMap.get(httpMethod);

	conversationDTO = new ConversationDTO();
	RfRequestDTO rfRequestDTO = new RfRequestDTO();
	rfRequestDTO.setApiUrl("http://" + host + basePath + pathKey);
	rfRequestDTO.setMethodType(httpMethod.name());
	operation.getParameters();
	conversationDTO.setRfRequestDTO(rfRequestDTO);
	ConversationDTO createdConversation = conversationController.create(conversationDTO);
	conversationDTO.setId(createdConversation.getId());

	String operationId = operation.getOperationId();
	String summary = operation.getSummary();
	// Request Node
	NodeDTO childNode = new NodeDTO();
	childNode.setName(operationId);
	childNode.setDescription(summary);
	childNode.setProjectId(projectId);
	childNode.setConversationDTO(conversationDTO);
	NodeDTO createdChildNode = nodeController.create(folderNode.getId(), childNode);
	System.out.println("created node : " + createdChildNode.getName());
    }
}
   }