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

The following examples show how to use io.swagger.models.Operation#addResponse() . 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: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 2
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 3
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void correctResponses(Operation operation) {
  int okCode = Status.OK.getStatusCode();
  String strOkCode = String.valueOf(okCode);
  Response okResponse = null;

  for (Entry<String, Response> responseEntry : operation.getResponses().entrySet()) {
    Response response = responseEntry.getValue();
    if (StringUtils.isEmpty(response.getDescription())) {
      response.setDescription("response of " + responseEntry.getKey());
    }

    if (operation.getResponses().get(strOkCode) != null) {
      continue;
    }

    int statusCode = NumberUtils.toInt(responseEntry.getKey());
    if ("default".equals(responseEntry.getKey())) {
      statusCode = okCode;
    }
    if (Family.SUCCESSFUL.equals(Family.familyOf(statusCode))) {
      okResponse = response;
    }
  }

  if (okResponse != null) {
    operation.addResponse(strOkCode, okResponse);
  }
}
 
Example 4
Source File: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void correctResponsesOperationFixEmptyDescription() {
  Response response = new Response();

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

  SwaggerUtils.correctResponses(operation);
  Assert.assertEquals("response of 200", response.getDescription());
}
 
Example 5
Source File: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void correctResponsesOperationNotChangeExistDescription() {
  Response response = new Response();
  response.setDescription("description");

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

  SwaggerUtils.correctResponses(operation);
  Assert.assertEquals("description", response.getDescription());
}
 
Example 6
Source File: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void correctResponsesOperationDefaultTo200() {
  Response response = new Response();

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

  SwaggerUtils.correctResponses(operation);
  Assert.assertSame(response, operation.getResponses().get("200"));
}
 
Example 7
Source File: TestSwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void correctResponsesOperation2xxTo200() {
  Response response = new Response();

  Operation operation = new Operation();
  operation.addResponse("default", new Response());
  operation.addResponse("201", response);
  operation.addResponse("301", new Response());

  SwaggerUtils.correctResponses(operation);
  Assert.assertSame(response, operation.getResponses().get("200"));
}
 
Example 8
Source File: SwaggerUtils.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Create a swagger definition from data-service resource details.
 *
 * @param axisResourceMap AxisResourceMap containing resource details.
 * @param dataServiceName Name of the data service.
 * @param transports      Transports supported from the data-service.
 * @param serverConfig    Server config details.
 * @param isJSON          result format JSON or YAML.
 * @return Swagger definition as string.
 * @throws AxisFault Error occurred while fetching the host address.
 */
private static String createSwaggerFromDefinition(AxisResourceMap axisResourceMap, String dataServiceName,
                                                  List<String> transports, MIServerConfig serverConfig,
                                                  boolean isJSON)
        throws AxisFault {

    Swagger swaggerDoc = new Swagger();
    addSwaggerInfoSection(dataServiceName, transports, serverConfig, swaggerDoc);

    Map<String, Path> paths = new HashMap<>();

    for (Map.Entry<String, AxisResource> entry : axisResourceMap.getResources().entrySet()) {
        Path path = new Path();
        for (String method : entry.getValue().getMethods()) {
            Operation operation = new Operation();
            List<AxisResourceParameter> parameterList = entry.getValue().getResourceParameterList(method);
            generatePathAndQueryParameters(method, operation, parameterList);
            // Adding a sample request payload for methods except GET.
            generateSampleRequestPayload(method, operation, parameterList);
            Response response = new Response();
            response.description("this is the default response");
            operation.addResponse("default", response);
            switch (method) {
                case "GET":
                    path.get(operation);
                    break;
                case "POST":
                    path.post(operation);
                    break;
                case "DELETE":
                    path.delete(operation);
                    break;
                case "PUT":
                    path.put(operation);
                    break;
                default:
                    throw new AxisFault("Invalid method \"" + method + "\" detected in the data-service");
            }
        }
        String contextPath = entry.getKey().startsWith("/") ? entry.getKey() : "/" + entry.getKey();
        paths.put(contextPath, path);
    }
    swaggerDoc.setPaths(paths);
    if (isJSON) return Json.pretty(swaggerDoc);
    try {
        return Yaml.pretty().writeValueAsString(swaggerDoc);
    } catch (JsonProcessingException e) {
        logger.error("Error occurred while creating the YAML configuration", e);
        return null;
    }
}
 
Example 9
Source File: SwaggerExtension.java    From Web-API with MIT License 4 votes vote down vote up
@Override
public void decorateOperation(Operation operation, Method method,
                              Iterator<io.swagger.jaxrs.ext.SwaggerExtension> chain) {
    // Automatically add query params
    operation.addParameter(new RefParameter("details"));
    operation.addParameter(new RefParameter("accept"));
    operation.addParameter(new RefParameter("pretty"));

    // Automatically add 500 as a possible response
    operation.addResponse("500", new RefResponse("500"));

    // Automatically add error codes depending on thrown exceptions
    for (Class<?> execClass : method.getExceptionTypes()) {
        if (BadRequestException.class.isAssignableFrom(execClass)) {
            operation.addResponse("400", new RefResponse("400"));
        }
        if (NotFoundException.class.isAssignableFrom(execClass)) {
            operation.addResponse("404", new RefResponse("404"));
        }
        if (NotImplementedException.class.isAssignableFrom(execClass)) {
            operation.addResponse("501", new RefResponse("501"));
        }
    }

    Permission[] perms = method.getAnnotationsByType(Permission.class);
    if (perms.length > 0) {
        // Automatically add 401 & 403 as a possible response
        operation.addResponse("401", new RefResponse("401"));
        operation.addResponse("403", new RefResponse("403"));

        // Automatically add required permission notes if we have a @Permission annotation
        Path path = method.getDeclaringClass().getAnnotation(Path.class);
        String prefix = path != null ? path.value() + "." : "";

        StringBuilder permStr = new StringBuilder("  \n\n **Required permissions:**  \n\n");
        for (Permission perm : perms) {
            permStr.append("- **").append(prefix).append(String.join(".", perm.value())).append("**  \n");
        }

        operation.setDescription(operation.getDescription() + permStr.toString());

        // Add security definitions
        operation.addSecurity("ApiKeyHeader", new ArrayList<>());
        operation.addSecurity("ApiKeyQuery", new ArrayList<>());
    }
    super.decorateOperation(operation, method, chain);
}