io.swagger.annotations.SwaggerDefinition#io.swagger.models.Response源码实例Demo

下面列出了io.swagger.annotations.SwaggerDefinition#io.swagger.models.Response 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
        Map<String, Model> definitions, Swagger swagger) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        Response methodResponse = findMethodResponse(operation.getResponses());

        if (methodResponse != null) {
            if (methodResponse.getSchema() != null) {
                CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
                op.vendorExtensions.put("x-codegen-response", cm);
                if(cm.datatype == "HttpContent")
                {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }

    return op;
}
 
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
                                      Map<String, Model> definitions, Swagger swagger) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        Response methodResponse = findMethodResponse(operation.getResponses());

        if (methodResponse != null) {
            if (methodResponse.getSchema() != null) {
                CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
                op.vendorExtensions.put("x-codegen-response", cm);
                if(cm.datatype == "HttpContent") {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }

    String pathForPistache = path.replaceAll("\\{(.*?)}", ":$1");
    op.vendorExtensions.put("x-codegen-pistache-path", pathForPistache);

    return op;
}
 
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
                                      Map<String, Model> definitions, Swagger swagger) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        Response methodResponse = findMethodResponse(operation.getResponses());

        if (methodResponse != null) {
            if (methodResponse.getSchema() != null) {
                CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
                op.vendorExtensions.put("x-codegen-response", cm);
                if(cm.datatype == "HttpContent") {
                    op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
                }
            }
        }
    }
    return op;
}
 
源代码4 项目: TypeScript-Microservices   文件: DefaultCodegen.java
/**
 * Override with any special handling of response codes
 * @param responses Swagger Operation's responses
 * @return default method response or <tt>null</tt> if not found
 */
protected Response findMethodResponse(Map<String, Response> responses) {

    String code = null;
    for (String responseCode : responses.keySet()) {
        if (responseCode.startsWith("2") || responseCode.equals("default")) {
            if (code == null || code.compareTo(responseCode) > 0) {
                code = responseCode;
            }
        }
    }
    if (code == null) {
        return null;
    }
    return responses.get(code);
}
 
源代码5 项目: dorado   文件: Reader.java
@SuppressWarnings("deprecation")
private void addResponse(Operation operation, ApiResponse apiResponse, JsonView jsonView) {
	Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders(), jsonView);
	Map<String, Object> examples = parseExamples(apiResponse.examples());

	Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
	response.setExamples(examples);

	if (apiResponse.code() == 0) {
		operation.defaultResponse(response);
	} else {
		operation.response(apiResponse.code(), response);
	}

	if (StringUtils.isNotEmpty(apiResponse.reference())) {
		response.schema(new RefProperty(apiResponse.reference()));
	} else if (!isVoid(apiResponse.response())) {
		Type responseType = apiResponse.response();
		final Property property = ModelConverters.getInstance().readAsProperty(responseType, jsonView);
		if (property != null) {
			response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
			appendModels(responseType);
		}
	}
}
 
private static void generateResponse(Swagger swagger, ResponseConfig responseConfig) {
  Response response = new Response();

  Property property = generateResponseProperty(swagger, responseConfig);
  if (property != null) {
    Model model = new PropertyModelConverter().propertyToModel(property);
    response.setResponseSchema(model);
  }
  response.setDescription(responseConfig.getDescription());
  addExamplesToResponse(response, responseConfig);
  if (responseConfig.getResponseHeaders() != null) {
    Map<String, Property> headers = generateResponseHeader(swagger, responseConfig.getResponseHeaders());
    response.setHeaders(headers);
  }

  responseConfig.setResponse(response);
}
 
private void testBase(Path path) {
  Assert.assertEquals(1, path.getOperations().size());

  Operation operation = path.getGet();

  Assert.assertEquals("summary", operation.getSummary());
  Assert.assertEquals("notes", operation.getDescription());
  Assert.assertEquals(Arrays.asList("tag1", "tag2"), operation.getTags());
  Assert.assertEquals(Arrays.asList("application/json"), operation.getProduces());
  Assert.assertEquals(Arrays.asList("application/json"), operation.getConsumes());
  Assert.assertEquals(Arrays.asList(Scheme.HTTP, Scheme.HTTPS), operation.getSchemes());

  Map<String, Response> responseMap = operation.getResponses();
  Assert.assertEquals(2, responseMap.size());

  Response response = responseMap.get(SwaggerConst.SUCCESS_KEY);
  Assert.assertNotNull(response);
  Assert.assertEquals(null, response.getResponseSchema());

  response = responseMap.get("202");
  Assert.assertNotNull(response);
  Assert.assertEquals(null, response.getResponseSchema());

  Assert.assertEquals(1, response.getHeaders().size());
  Assert.assertEquals("integer", response.getHeaders().get("h1").getType());
}
 
@Override
public void decorateOperation(final Operation operation, final Method method, final Iterator<SwaggerExtension> chain) {

    final TestVendorAnnotation annotation = method.getAnnotation(TestVendorAnnotation.class);
    if (annotation != null) {

        Map<String, Response> map = new HashMap<String, Response>(operation.getResponses());
        final Response value = new Response();
        value.setDescription(RESPONSE_DESCRIPTION);
        map.put(RESPONSE_STATUS_401, value);
        operation.setResponses(map);
    }

    if (chain.hasNext()) {
        chain.next().decorateOperation(operation, method, chain);
    }
}
 
@Test
public void correctResponsesHavePaths() {
  Response response = new Response();

  Operation operation = new Operation();
  operation.addResponse("200", response);

  Path path = new Path();
  path.set("get", operation);

  Swagger swagger = new Swagger();
  swagger.path("/base", path);

  SwaggerUtils.correctResponses(swagger);

  Assert.assertEquals("response of 200", response.getDescription());
}
 
private void fillResponseType(Operation operation, ProtoMethod protoMethod) {
  for (Entry<String, Response> entry : operation.getResponses().entrySet()) {
    String type = convertSwaggerType(entry.getValue().getResponseSchema());
    boolean wrapped = !messages.contains(type);

    ProtoResponse protoResponse = new ProtoResponse();
    protoResponse.setTypeName(type);

    if (wrapped) {
      String wrapName = StringUtils.capitalize(operation.getOperationId()) + "ResponseWrap" + entry.getKey();
      wrapPropertyToMessage(wrapName, entry.getValue().getResponseSchema());

      protoResponse.setTypeName(wrapName);
    }
    protoMethod.addResponse(entry.getKey(), protoResponse);
  }
}
 
源代码11 项目: yang2swagger   文件: PostOperationGenerator.java
@Override
public Operation execute(DataSchemaNode node) {
    final Operation post = dropLastSegmentParameters ? listOperation() : defaultOperation();
    final RefModel definition = new RefModel(getDefinitionId(node));
    post.summary("creates " + getName(node));
    String description = node.getDescription() == null ? "creates " + getName(node) :
            node.getDescription();
    post.description(description);
    post.parameter(new BodyParameter()
            .name(getName(node) + ".body-param")
            .schema(definition)
            .description(getName(node) + " to be added to list"));

    post.response(201, new Response().description("Object created"));
    post.response(409, new Response().description("Object already exists"));
    return post;
}
 
源代码12 项目: yang2swagger   文件: PutOperationGenerator.java
@Override
public Operation execute(DataSchemaNode node) {
    final Operation put = defaultOperation();
    final RefModel definition = new RefModel(getDefinitionId(node));
    put.summary("creates or updates " + getName(node));
    String description = node.getDescription() == null ? "creates or updates " + getName(node) :
            node.getDescription();
    put.description(description);
    put.parameter(new BodyParameter()
            .name(getName(node) + ".body-param")
            .schema(definition)
            .description(getName(node) + " to be added or updated"));

    put.response(201, new Response().description("Object created"));
    put.response(204, new Response().description("Object modified"));
    return put;
}
 
源代码13 项目: yang2swagger   文件: PatchOperationGenerator.java
@Override
public Operation execute(DataSchemaNode node) {
    final Operation patch = defaultOperation();
    final RefModel definition = new RefModel(getDefinitionId(node));
    patch.summary("patches " + getName(node));
    String description = node.getDescription() == null ? "patches " + getName(node) :
            node.getDescription();
    patch.description(description);
    patch.parameter(new BodyParameter()
            .name(getName(node) + ".body-param")
            .schema(definition)
            .description(getName(node) + " to be added or updated"));

    patch.response(200, new Response()
            .schema(new RefProperty(getDefinitionId(node)))
            .description(getName(node)));
    patch.response(204, new Response().description("Operation successful"));
    return patch;
}
 
源代码14 项目: carbon-apimgt   文件: OASParserUtil.java
/**
 * Creates a json string using the swagger object.
 *
 * @param swaggerObj swagger object
 * @return json string using the swagger object
 * @throws APIManagementException error while creating swagger json
 */
public static String getSwaggerJsonString(Swagger swaggerObj) throws APIManagementException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    //this is to ignore "originalRef" in schema objects
    mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);

    //this is to ignore "responseSchema" in response schema objects
    mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
    try {
        return new String(mapper.writeValueAsBytes(swaggerObj));
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while generating Swagger json from model", e);
    }
}
 
源代码15 项目: swagger2puml   文件: PlantUMLCodegen.java
/**
 * 
 * @param operation
 * @return
 */
private String getErrorClassName(Operation operation) {
	StringBuilder errorClass = new StringBuilder();
	Map<String, Response> responses = operation.getResponses();
	for (Map.Entry<String, Response> responsesEntry : responses.entrySet()) {
		String responseCode = responsesEntry.getKey();

		if (responseCode.equalsIgnoreCase("default") || Integer.parseInt(responseCode) >= 300) {
			Property responseProperty = responsesEntry.getValue().getSchema();

			if (responseProperty instanceof RefProperty) {
				String errorClassName = ((RefProperty) responseProperty).getSimpleRef();
				if (!errorClass.toString().contains(errorClassName)) {
					if (StringUtils.isNotEmpty(errorClass)) {
						errorClass.append(",");
					}
					errorClass.append(errorClassName);
				}
			}
		}
	}

	return errorClass.toString();
}
 
@Override
public void decorateOperation(final Operation operation, final Method method, final Iterator<SwaggerExtension> chain) {

    final TestVendorAnnotation annotation = method.getAnnotation(TestVendorAnnotation.class);
    if (annotation != null) {

        Map<String, Response> map = new HashMap<String, Response>(operation.getResponses());
        final Response value = new Response();
        value.setDescription(RESPONSE_DESCRIPTION);
        map.put(RESPONSE_STATUS_501, value);
        operation.setResponses(map);
    }

    if (chain.hasNext()) {
        chain.next().decorateOperation(operation, method, chain);
    }
}
 
源代码17 项目: herd   文件: RestControllerProcessor.java
/**
 * Processes the return value of a RequestMapping annotated method.
 *
 * @param returnType the return type.
 * @param operation the operation.
 * @param returnDescription the description of the return value.
 *
 * @throws MojoExecutionException if the return type isn't an XmlType.
 */
private void processRestMethodReturnValue(Class<?> returnType, Operation operation, String returnDescription) throws MojoExecutionException
{
    log.debug("Processing REST method return value \"" + returnType.getName() + "\".");

    // Add the class name to the list of classes which we will create an example for.
    exampleClassNames.add(returnType.getSimpleName());

    // Add the success response
    operation.response(200, new Response().description(returnDescription == null ? "Success" : returnDescription)
        .schema(new RefProperty(getXmlType(returnType).name().trim())));

    // If we have an error class, add that as the default response.
    if (modelErrorClass != null)
    {
        operation.defaultResponse(new Response().description("General Error").schema(new RefProperty(getXmlType(modelErrorClass).name().trim())));
    }
}
 
private void createMethodResponses(RestApi api, Method method, String modelContentType, Map<String, Response> responses) {
    if (responses == null) {
        return;
    }

    // add responses from swagger
    responses.entrySet().forEach(e -> {
        if (e.getKey().equals("default")) {
            LOG.warn("Default response not supported, skipping");
        } else {
            LOG.info(format("Creating method response for api %s and method %s and status %s",
                            api.getId(), method.getHttpMethod(), e.getKey()));

            method.putMethodResponse(getCreateResponseInput(api, modelContentType, e.getValue()), e.getKey());
        }
    });
}
 
private Optional<Model> getModel(RestApi api, Response response) {

        String modelName;

        // if the response references a proper model, look for a model matching the model name
        if (response.getSchema() != null && response.getSchema().getType().equals("ref")) {
            modelName = ((RefProperty) response.getSchema()).getSimpleRef();
        } else {
            // if the response has an embedded schema, look for a model matching the generated name
            modelName = generateModelName(response);
        }

        try {
            Model model = api.getModelByName(modelName);
            if (model.getName() != null) {
                return Optional.of(model);
            }
        } catch (Exception ignored) {}

        return Optional.empty();
    }
 
源代码20 项目: msf4j   文件: ExtendedSwaggerReader.java
private void addResponse(Operation operation, ApiResponse apiResponse) {
    Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders());

    Response response = new Response().description(apiResponse.message()).headers(responseHeaders);

    if (apiResponse.code() == 0) {
        operation.defaultResponse(response);
    } else {
        operation.response(apiResponse.code(), response);
    }

    if (StringUtils.isNotEmpty(apiResponse.reference())) {
        response.schema(new RefProperty(apiResponse.reference()));
    } else if (!isVoid(apiResponse.response())) {
        Type responseType = apiResponse.response();
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
            appendModels(responseType);
        }
    }
}
 
源代码21 项目: assertj-swagger   文件: ConsumerDrivenValidator.java
private void validateResponses(Map<String, Response> actualOperationResponses, Map<String, Response> expectedOperationResponses, String httpMethod, String path) {
    String message = String.format("Checking responses of '%s' operation of path '%s'", httpMethod, path);
    if (MapUtils.isNotEmpty(expectedOperationResponses)) {
        softAssertions.assertThat(actualOperationResponses).as(message).isNotEmpty();
        if (MapUtils.isNotEmpty(actualOperationResponses)) {
            softAssertions.assertThat(actualOperationResponses.keySet()).as(message).hasSameElementsAs(expectedOperationResponses.keySet());
            for (Map.Entry<String, Response> actualResponseEntry : actualOperationResponses.entrySet()) {
                Response expectedResponse = expectedOperationResponses.get(actualResponseEntry.getKey());
                Response actualResponse = actualResponseEntry.getValue();
                String responseName = actualResponseEntry.getKey();
                validateResponse(actualResponse, expectedResponse, responseName, httpMethod, path);
            }
        }
    } else {
        softAssertions.assertThat(actualOperationResponses).as(message).isNullOrEmpty();
    }
}
 
private void validateResponses(Map<String, Response> actualOperationResponses, Map<String, Response> expectedOperationResponses, String httpMethod, String path) {
    String message = String.format("Checking responses of '%s' operation of path '%s'", httpMethod, path);
    if (MapUtils.isNotEmpty(expectedOperationResponses)) {
        softAssertions.assertThat(actualOperationResponses).as(message).isNotEmpty();
        if (MapUtils.isNotEmpty(actualOperationResponses)) {
            validateResponseByConfig(actualOperationResponses, expectedOperationResponses, message);
            for (Map.Entry<String, Response> actualResponseEntry : actualOperationResponses.entrySet()) {
                Response expectedResponse = expectedOperationResponses.get(actualResponseEntry.getKey());
                Response actualResponse = actualResponseEntry.getValue();
                String responseName = actualResponseEntry.getKey();
                validateResponse(actualResponse, expectedResponse, responseName, httpMethod, path);
            }
        }
    } else {
        softAssertions.assertThat(actualOperationResponses).as(message).isNullOrEmpty();
    }
}
 
源代码23 项目: swagger-parser   文件: SwaggerInventory.java
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);
        }
    }

}
 
源代码24 项目: carbon-apimgt   文件: OAS2Parser.java
/**
 * 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;
}
 
@Override
public boolean check(List<Parameter> params, Map<String, Response> responses) {
    Optional<Parameter> p = params.stream().filter(ParameterUtils.equalsParam(name, in)).findFirst();

    if (p.isPresent()) {
        String val = SwaggerSpecificationProcessor.extractValue(p.get());
        currentValue.add(val);
    }

    return currentValue.contains(expectedValue);
}
 
@Override
public boolean check(List<Parameter> params, Map<String, Response> responses) {
    Optional<Parameter> p = params.stream().filter(ParameterUtils.equalsParam(name, in)).findFirst();
    if (p.isPresent()) {
        String val = SwaggerSpecificationProcessor.extractValue(p.get());
        currentValue.add(val);
    }

    return true;
}
 
@Override
public boolean check(List<Parameter> params, Map<String, Response> responses) {
    Optional<Parameter> p = params.stream().filter(ParameterUtils.equalsParam(name, in)).findFirst();
    if (p.isPresent()) {
        String val = SwaggerSpecificationProcessor.extractValue(p.get());
        currentValue.add(val);
    }

    return true;
}
 
源代码28 项目: cellery-distribution   文件: UpdateManager.java
/**
 * Creates API Resources inside a Component
 *
 * @param api API sent by controller
 * @return Swagger Path Map
 */
private static Map<String, Path> createAPIResources(API api) {
    Map<String, Path> pathMap = new HashMap<>();
    for (ApiDefinition definition : api.getDefinitions()) {
        Path path = pathMap.computeIfAbsent(definition.getPath(), (key) -> new Path());
        Operation op = new Operation();

        Map<String, Response> resMap = new HashMap<>();
        Response res = new Response();
        res.setDescription("Successful");

        resMap.put("200", res);
        op.setResponses(resMap);

        disableMicroGWAuth(op);
        switch (definition.getMethod().toLowerCase(Locale.ENGLISH)) {
            case Constants.JsonParamNames.GET:
                path.setGet(op);
                break;
            case Constants.JsonParamNames.POST:
                path.setPost(op);
                break;
            case Constants.JsonParamNames.PUT:
                path.setPut(op);
                break;
            case Constants.JsonParamNames.DELETE:
                path.setDelete(op);
                break;
            default:
                log.error("HTTP Method not implemented");
        }
    }
    return pathMap;
}
 
@Override
public CodegenResponse fromResponse(String responseCode, Response resp) {
    final CodegenResponse response = super.fromResponse(responseCode, resp);
    if (response.dataType != null) {
        addEncoderAndDecoder(response.vendorExtensions, response.dataType, response.primitiveType);
    }
    return response;
}
 
源代码30 项目: TypeScript-Microservices   文件: DefaultCodegen.java
private void addHeaders(Response response, List<CodegenProperty> target) {
    if (response.getHeaders() != null) {
        for (Map.Entry<String, Property> headers : response.getHeaders().entrySet()) {
            target.add(fromProperty(headers.getKey(), headers.getValue()));
        }
    }
}