Beispiel #1
0
  void appendCollectionTo(
      final ObjectSpecification objectSpec, final OneToManyAssociation collection) {

    final String objectType = objectTypeFor(objectSpec);
    final String collectionId = collection.getId();

    final Path path = new Path();
    swagger.path(
        String.format("/objects/%s/{objectId}/collections/%s", objectType, collectionId), path);

    final String tag = tagFor(objectType, null);
    final Operation collectionOperation =
        new Operation()
            .tag(tag)
            .description(Util.roSpec("17.1") + ": resource of " + objectType + "#" + collectionId)
            .parameter(new PathParameter().name("objectId").type("string"))
            .produces("application/json;profile=urn:org.apache.isis/v1")
            .produces("application/json;profile=urn:org.apache.isis/v1;suppress=true")
            .produces(
                "application/json;profile=urn:org.restfulobjects:repr-types/object-collection");

    path.get(collectionOperation);
    collectionOperation.response(
        200,
        new Response()
            .description(
                objectType
                    + "#"
                    + collectionId
                    + " , if Accept: application/json;profile=urn:org.apache.isis/v1")
            .schema(modelFor(collection)));
  }
  @Test
  public void testArrayResponse() {
    Swagger swagger = new Swagger();

    ArrayProperty schema = new ArrayProperty();
    schema.setItems(new ObjectProperty().property("name", new StringProperty()));

    swagger.path(
        "/foo/baz",
        new Path()
            .get(
                new Operation()
                    .response(
                        200,
                        new Response()
                            .vendorExtension("x-foo", "bar")
                            .description("it works!")
                            .schema(schema))));
    new InlineModelResolver().flatten(swagger);

    Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200");
    assertTrue(response.getSchema() instanceof ArrayProperty);

    ArrayProperty am = (ArrayProperty) response.getSchema();
    Property items = am.getItems();
    assertTrue(items instanceof ObjectProperty);
    ObjectProperty op = (ObjectProperty) items;
    Property name = op.getProperties().get("name");
    assertTrue(name instanceof StringProperty);
  }
  @Test
  public void testInlineMapResponse() throws Exception {
    Swagger swagger = new Swagger();

    MapProperty schema = new MapProperty();
    schema.setAdditionalProperties(new StringProperty());

    swagger.path(
        "/foo/baz",
        new Path()
            .get(
                new Operation()
                    .response(
                        200,
                        new Response()
                            .vendorExtension("x-foo", "bar")
                            .description("it works!")
                            .schema(schema))));
    new InlineModelResolver().flatten(swagger);
    Json.prettyPrint(swagger);

    Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Property property = response.getSchema();
    assertTrue(property instanceof MapProperty);
    assertTrue(swagger.getDefinitions().size() == 0);
  }
Beispiel #4
0
  void appendServicePath(final ObjectSpecification objectSpec) {

    final String serviceId = serviceIdFor(objectSpec);

    final Path path = new Path();
    swagger.path(String.format("/services/%s", serviceId), path);

    final String serviceModelDefinition = serviceId + "Repr";

    final String tag = tagFor(serviceId, "> services");
    path.get(
        new Operation()
            .tag(tag)
            .description(Util.roSpec("15.1"))
            .produces("application/json")
            .produces("application/json;profile=urn:org.restfulobjects:repr-types/object")
            .response(
                200,
                newResponse(Caching.TRANSACTIONAL)
                    .description("OK")
                    .schema(newRefProperty(serviceModelDefinition))));

    final ModelImpl model =
        newModel(Util.roSpec("15.1.2") + ": representation of " + serviceId)
            .property("title", stringProperty())
            .property("serviceId", stringProperty()._default(serviceId))
            .property("members", new ObjectProperty());

    addDefinition(serviceModelDefinition, model);
  }
  @Test
  public void resolveInlineBodyParameter() throws Exception {
    Swagger swagger = new Swagger();

    swagger.path(
        "/hello",
        new Path()
            .get(
                new Operation()
                    .parameter(
                        new BodyParameter()
                            .name("body")
                            .schema(
                                new ModelImpl()
                                    .property(
                                        "address",
                                        new ObjectProperty()
                                            .property("street", new StringProperty()))
                                    .property("name", new StringProperty())))));

    new InlineModelResolver().flatten(swagger);

    Operation operation = swagger.getPaths().get("/hello").getGet();
    BodyParameter bp = (BodyParameter) operation.getParameters().get(0);
    assertTrue(bp.getSchema() instanceof RefModel);

    Model body = swagger.getDefinitions().get("body");
    assertTrue(body instanceof ModelImpl);

    ModelImpl impl = (ModelImpl) body;
    assertNotNull(impl.getProperties().get("address"));
  }
Beispiel #6
0
  ModelImpl appendObjectPathAndModelDefinitions(final ObjectSpecification objectSpec) {

    final String objectType = objectTypeFor(objectSpec);

    final Path path = new Path();
    swagger.path(String.format("/objects/%s/{objectId}", objectType), path);

    final String tag = tagFor(objectType, null);
    final Operation operation = new Operation();
    path.get(operation);
    operation
        .tag(tag)
        .description(Util.roSpec("14.1"))
        .parameter(new PathParameter().name("objectId").type("string"))
        .produces("application/json;profile=urn:org.apache.isis/v1")
        .produces("application/json;profile=urn:org.apache.isis/v1;suppress=true")
        .produces("application/json;profile=urn:org.restfulobjects:repr-types/object");

    // per https://github.com/swagger-api/swagger-spec/issues/146, swagger 2.0 doesn't support
    // multiple
    // modelled representations per path and response code;
    // in particular cannot associate representation/model with Accept header ('produces(...)
    // method)
    final String restfulObjectsModelDefinition = objectType + "RestfulObjectsRepr";
    if (false) {
      operation.response(
          200,
          newResponse(Caching.TRANSACTIONAL)
              .description(
                  "if Accept: application/json;profile=urn:org.restfulobjects:repr-types/object")
              .schema(newRefProperty(restfulObjectsModelDefinition)));

      final ModelImpl roSpecModel =
          newModel(Util.roSpec("14.4") + ": representation of " + objectType)
              .property("title", stringProperty())
              .property("domainType", stringProperty()._default(objectType))
              .property("instanceId", stringProperty())
              .property("members", new ObjectProperty());
      swagger.addDefinition(restfulObjectsModelDefinition, roSpecModel);
    }

    final String isisModelDefinition = objectType + "Repr";
    operation.response(
        200,
        newResponse(Caching.TRANSACTIONAL)
            .description(
                objectType + " , if Accept: application/json;profile=urn:org.apache.isis/v1")
            .schema(newRefProperty(isisModelDefinition)));

    final ModelImpl isisModel = new ModelImpl();
    addDefinition(isisModelDefinition, isisModel);

    // return so can be appended to
    return isisModel;
  }
  @Test
  public void testBasicInput() {
    Swagger swagger = new Swagger();

    ModelImpl user = new ModelImpl().property("name", new StringProperty());

    swagger.path(
        "/foo/baz",
        new Path()
            .post(
                new Operation()
                    .parameter(new BodyParameter().name("myBody").schema(new RefModel("User")))));

    swagger.addDefinition("User", user);

    new InlineModelResolver().flatten(swagger);

    Json.prettyPrint(swagger);
  }
  @Test
  public void resolveInlineArrayBodyParameter() throws Exception {
    Swagger swagger = new Swagger();

    swagger.path(
        "/hello",
        new Path()
            .get(
                new Operation()
                    .parameter(
                        new BodyParameter()
                            .name("body")
                            .schema(
                                new ArrayModel()
                                    .items(
                                        new ObjectProperty()
                                            .property(
                                                "address",
                                                new ObjectProperty()
                                                    .property("street", new StringProperty())))))));

    new InlineModelResolver().flatten(swagger);

    Parameter param = swagger.getPaths().get("/hello").getGet().getParameters().get(0);
    assertTrue(param instanceof BodyParameter);

    BodyParameter bp = (BodyParameter) param;
    Model schema = bp.getSchema();

    assertTrue(schema instanceof ArrayModel);

    ArrayModel am = (ArrayModel) schema;
    Property inner = am.getItems();

    ObjectProperty op = (ObjectProperty) inner;
    Property name = op.getProperties().get("address");
    assertTrue(name instanceof RefProperty);

    Model model = swagger.getDefinitions().get("hello_address");
    assertNotNull(model);
  }
  @Test
  public void resolveInlineArrayResponse() throws Exception {
    Swagger swagger = new Swagger();

    swagger.path(
        "/foo/baz",
        new Path()
            .get(
                new Operation()
                    .response(
                        200,
                        new Response()
                            .vendorExtension("x-foo", "bar")
                            .description("it works!")
                            .schema(
                                new ArrayProperty()
                                    .items(
                                        new ObjectProperty()
                                            .property("name", new StringProperty()))))));

    new InlineModelResolver().flatten(swagger);

    Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200");
    assertNotNull(response);

    assertNotNull(response.getSchema());
    Property responseProperty = response.getSchema();

    // no need to flatten more
    assertTrue(responseProperty instanceof ArrayProperty);

    ArrayProperty ap = (ArrayProperty) responseProperty;
    Property p = ap.getItems();

    assertNotNull(p);

    ObjectProperty innerModel = (ObjectProperty) p;
    assertTrue(innerModel.getProperties().size() == 1);
    assertNotNull(innerModel.getProperties().get("name"));
  }
  @Test
  public void testInlineResponseModel() throws Exception {
    Swagger swagger = new Swagger();

    swagger
        .path(
            "/foo/bar",
            new Path()
                .get(
                    new Operation()
                        .response(
                            200,
                            new Response()
                                .description("it works!")
                                .schema(
                                    new ObjectProperty().property("name", new StringProperty())))))
        .path(
            "/foo/baz",
            new Path()
                .get(
                    new Operation()
                        .response(
                            200,
                            new Response()
                                .vendorExtension("x-foo", "bar")
                                .description("it works!")
                                .schema(
                                    new ObjectProperty().property("name", new StringProperty())))));
    new InlineModelResolver().flatten(swagger);

    Map<String, Response> responses = swagger.getPaths().get("/foo/bar").getGet().getResponses();

    Response response = responses.get("200");
    assertNotNull(response);
    assertTrue(response.getSchema() instanceof RefProperty);

    ModelImpl model = (ModelImpl) swagger.getDefinitions().get("inline_response_200");
    assertTrue(model.getProperties().size() == 1);
    assertNotNull(model.getProperties().get("name"));
  }
  @Test
  public void notResolveNonModelBodyParameter() throws Exception {
    Swagger swagger = new Swagger();

    swagger.path(
        "/hello",
        new Path()
            .get(
                new Operation()
                    .parameter(
                        new BodyParameter()
                            .name("body")
                            .schema(new ModelImpl().type("string").format("binary")))));

    new InlineModelResolver().flatten(swagger);

    Operation operation = swagger.getPaths().get("/hello").getGet();
    BodyParameter bp = (BodyParameter) operation.getParameters().get(0);
    assertTrue(bp.getSchema() instanceof ModelImpl);
    ModelImpl m = (ModelImpl) bp.getSchema();
    assertEquals("string", m.getType());
    assertEquals("binary", m.getFormat());
  }
  @Test
  public void testInlineMapResponseWithObjectProperty() throws Exception {
    Swagger swagger = new Swagger();

    MapProperty schema = new MapProperty();
    schema.setAdditionalProperties(new ObjectProperty().property("name", new StringProperty()));

    swagger.path(
        "/foo/baz",
        new Path()
            .get(
                new Operation()
                    .response(
                        200,
                        new Response()
                            .vendorExtension("x-foo", "bar")
                            .description("it works!")
                            .schema(schema))));
    new InlineModelResolver().flatten(swagger);

    Response response = swagger.getPaths().get("/foo/baz").getGet().getResponses().get("200");

    Property property = response.getSchema();
    assertTrue(property instanceof RefProperty);

    Model inline = swagger.getDefinitions().get("inline_response_200");
    assertTrue(inline instanceof ModelImpl);
    ModelImpl impl = (ModelImpl) inline;

    Property innerProperty = impl.getAdditionalProperties();
    assertTrue(innerProperty instanceof ObjectProperty);

    ObjectProperty obj = (ObjectProperty) innerProperty;
    Property name = obj.getProperties().get("name");
    assertTrue(name instanceof StringProperty);
  }
Beispiel #13
0
  void appendObjectActionInvokePath(
      final ObjectSpecification objectSpec, final ObjectAction objectAction) {

    final String objectType = objectTypeFor(objectSpec);
    final String actionId = objectAction.getId();

    final List<ObjectActionParameter> parameters = objectAction.getParameters();
    final Path path = new Path();
    swagger.path(
        String.format("/objects/%s/{objectId}/actions/%s/invoke", objectType, actionId), path);

    final String tag = tagFor(objectType, null);
    final Operation invokeOperation =
        new Operation()
            .tag(tag)
            .description(
                Util.roSpec("19.1") + ": (invoke) resource of " + objectType + "#" + actionId)
            .parameter(new PathParameter().name("objectId").type("string"))
            .produces("application/json;profile=urn:org.apache.isis/v1")
            .produces("application/json;profile=urn:org.apache.isis/v1;suppress=true")
            .produces("application/json;profile=urn:org.restfulobjects:repr-types/action-result");

    final ActionSemantics.Of semantics = objectAction.getSemantics();
    if (semantics.isSafeInNature()) {
      path.get(invokeOperation);

      for (final ObjectActionParameter parameter : parameters) {
        invokeOperation.parameter(
            new QueryParameter()
                .name(parameter.getId())
                .description(
                    Util.roSpec("2.9.1")
                        + (!Strings.isNullOrEmpty(parameter.getDescription())
                            ? (": " + parameter.getDescription())
                            : ""))
                .required(false)
                .type("string"));
      }
      if (!parameters.isEmpty()) {
        invokeOperation.parameter(
            new QueryParameter()
                .name("x-isis-querystring")
                .description(
                    Util.roSpec("2.10") + ": all (formal) arguments as base64 encoded string")
                .required(false)
                .type("string"));
      }

    } else {
      if (semantics.isIdempotentInNature()) {
        path.put(invokeOperation);
      } else {
        path.post(invokeOperation);
      }

      final ModelImpl bodyParam = new ModelImpl().type("object");
      for (final ObjectActionParameter parameter : parameters) {

        final ObjectSpecification specification = parameter.getSpecification();
        final Property valueProperty =
            specification.isValue() ? modelFor(specification) : refToLinkModel();
        bodyParam.property(
            parameter.getId(), new ObjectProperty().property("value", valueProperty));
      }

      invokeOperation
          .consumes("application/json")
          .parameter(new BodyParameter().name("body").schema(bodyParam));
    }

    invokeOperation.response(
        200,
        new Response()
            .description(objectType + "#" + actionId)
            .schema(actionReturnTypeFor(objectAction)));
  }
Beispiel #14
0
  void appendServiceActionInvokePath(
      final ObjectSpecification serviceSpec, final ObjectAction serviceAction) {

    final String serviceId = serviceIdFor(serviceSpec);
    final String actionId = serviceAction.getId();

    final List<ObjectActionParameter> parameters = serviceAction.getParameters();
    final Path path = new Path();
    swagger.path(String.format("/services/%s/actions/%s/invoke", serviceId, actionId), path);

    final String tag = tagFor(serviceId, "> services");
    final Operation invokeOperation =
        new Operation()
            .tag(tag)
            .description(
                Util.roSpec("19.1") + ": (invoke) resource of " + serviceId + "#" + actionId)
            .produces("application/json;profile=urn:org.apache.isis/v1")
            .produces("application/json;profile=urn:org.apache.isis/v1;suppress=true")
            .produces("application/json;profile=urn:org.restfulobjects:repr-types/action-result");

    final ActionSemantics.Of semantics = serviceAction.getSemantics();
    if (semantics.isSafeInNature()) {
      path.get(invokeOperation);

      for (final ObjectActionParameter parameter : parameters) {
        invokeOperation.parameter(
            new QueryParameter()
                .name(parameter.getId())
                .description(
                    Util.roSpec("2.9.1")
                        + (!Strings.isNullOrEmpty(parameter.getDescription())
                            ? (": " + parameter.getDescription())
                            : ""))
                .required(false)
                .type("string"));
      }
      if (!parameters.isEmpty()) {
        invokeOperation.parameter(
            new QueryParameter()
                .name("x-isis-querystring")
                .description(
                    Util.roSpec("2.10") + ": all (formal) arguments as base64 encoded string")
                .required(false)
                .type("string"));
      }

    } else {
      if (semantics.isIdempotentInNature()) {
        path.put(invokeOperation);
      } else {
        path.post(invokeOperation);
      }

      final ModelImpl bodyParam = new ModelImpl().type("object");
      for (final ObjectActionParameter parameter : parameters) {

        final Property valueProperty;
        // TODO: need to switch on parameter's type and create appropriate impl of valueProperty
        // if(parameter.getSpecification().isValue()) ...
        valueProperty = stringProperty();

        bodyParam.property(
            parameter.getId(), new ObjectProperty().property("value", valueProperty));
      }

      invokeOperation
          .consumes("application/json")
          .parameter(new BodyParameter().name("body").schema(bodyParam));
    }

    invokeOperation.response(
        200,
        new Response()
            .description(
                serviceId
                    + "#"
                    + actionId
                    + " , if Accept: application/json;profile=urn:org.apache.isis/v1")
            .schema(actionReturnTypeFor(serviceAction)));
  }
Beispiel #15
0
  private void parse(
      Swagger swagger, RestDefinition rest, String camelContextId, ClassResolver classResolver) {
    List<VerbDefinition> verbs = new ArrayList<>(rest.getVerbs());
    // must sort the verbs by uri so we group them together when an uri has multiple operations
    Collections.sort(verbs, new VerbOrdering());

    // we need to group the operations within the same tag, so use the path as default if not
    // configured
    String pathAsTag =
        rest.getTag() != null ? rest.getTag() : FileUtil.stripLeadingSeparator(rest.getPath());
    String summary = rest.getDescriptionText();

    if (ObjectHelper.isNotEmpty(pathAsTag)) {
      // add rest as tag
      Tag tag = new Tag();
      tag.description(summary);
      tag.name(pathAsTag);
      swagger.addTag(tag);
    }

    // gather all types in use
    Set<String> types = new LinkedHashSet<>();
    for (VerbDefinition verb : verbs) {
      String type = verb.getType();
      if (ObjectHelper.isNotEmpty(type)) {
        if (type.endsWith("[]")) {
          type = type.substring(0, type.length() - 2);
        }
        types.add(type);
      }
      type = verb.getOutType();
      if (ObjectHelper.isNotEmpty(type)) {
        if (type.endsWith("[]")) {
          type = type.substring(0, type.length() - 2);
        }
        types.add(type);
      }
      // there can also be types in response messages
      if (verb.getResponseMsgs() != null) {
        for (RestOperationResponseMsgDefinition def : verb.getResponseMsgs()) {
          type = def.getResponseModel();
          if (ObjectHelper.isNotEmpty(type)) {
            if (type.endsWith("[]")) {
              type = type.substring(0, type.length() - 2);
            }
            types.add(type);
          }
        }
      }
    }

    // use annotation scanner to find models (annotated classes)
    for (String type : types) {
      Class<?> clazz = classResolver.resolveClass(type);
      appendModels(clazz, swagger);
    }

    // used during gathering of apis
    List<Path> paths = new ArrayList<>();

    String basePath = rest.getPath();

    for (VerbDefinition verb : verbs) {

      // the method must be in lower case
      String method = verb.asVerb().toLowerCase(Locale.US);
      // operation path is a key
      String opPath = SwaggerHelper.buildUrl(basePath, verb.getUri());

      Operation op = new Operation();
      if (ObjectHelper.isNotEmpty(pathAsTag)) {
        // group in the same tag
        op.addTag(pathAsTag);
      }

      // add id as vendor extensions
      op.getVendorExtensions().put("x-camelContextId", camelContextId);
      op.getVendorExtensions().put("x-routeId", verb.getRouteId());

      Path path = swagger.getPath(opPath);
      if (path == null) {
        path = new Path();
        paths.add(path);
      }
      path = path.set(method, op);

      String consumes = verb.getConsumes() != null ? verb.getConsumes() : rest.getConsumes();
      if (consumes != null) {
        String[] parts = consumes.split(",");
        for (String part : parts) {
          op.addConsumes(part);
        }
      }

      String produces = verb.getProduces() != null ? verb.getProduces() : rest.getProduces();
      if (produces != null) {
        String[] parts = produces.split(",");
        for (String part : parts) {
          op.addProduces(part);
        }
      }

      if (verb.getDescriptionText() != null) {
        op.summary(verb.getDescriptionText());
      }

      for (RestOperationParamDefinition param : verb.getParams()) {
        Parameter parameter = null;
        if (param.getType().equals(RestParamType.body)) {
          parameter = new BodyParameter();
        } else if (param.getType().equals(RestParamType.form)) {
          parameter = new FormParameter();
        } else if (param.getType().equals(RestParamType.header)) {
          parameter = new HeaderParameter();
        } else if (param.getType().equals(RestParamType.path)) {
          parameter = new PathParameter();
        } else if (param.getType().equals(RestParamType.query)) {
          parameter = new QueryParameter();
        }

        if (parameter != null) {
          parameter.setName(param.getName());
          parameter.setAccess(param.getAccess());
          parameter.setDescription(param.getDescription());
          parameter.setRequired(param.getRequired());

          // set type on parameter
          if (parameter instanceof SerializableParameter) {
            SerializableParameter sp = (SerializableParameter) parameter;

            if (param.getDataType() != null) {
              sp.setType(param.getDataType());
            }
            if (param.getAllowableValues() != null) {
              sp.setEnum(param.getAllowableValues());
            }
          }

          // set schema on body parameter
          if (parameter instanceof BodyParameter) {
            BodyParameter bp = (BodyParameter) parameter;

            if (verb.getType() != null) {
              String ref = modelTypeAsRef(verb.getType(), swagger);
              if (ref != null) {
                bp.setSchema(new RefModel(ref));
              }
            }
          }

          op.addParameter(parameter);
        }
      }

      // if we have an out type then set that as response message
      if (verb.getOutType() != null) {
        Response response = new Response();
        Property prop = modelTypeAsProperty(verb.getOutType(), swagger);
        response.setSchema(prop);
        response.setDescription("Output type");
        op.addResponse("200", response);
      }

      // enrich with configured response messages from the rest-dsl
      for (RestOperationResponseMsgDefinition msg : verb.getResponseMsgs()) {
        Response response = null;
        if (op.getResponses() != null) {
          response = op.getResponses().get(msg.getCode());
        }
        if (response == null) {
          response = new Response();
        }
        if (ObjectHelper.isNotEmpty(msg.getResponseModel())) {
          Property prop = modelTypeAsProperty(msg.getResponseModel(), swagger);
          response.setSchema(prop);
        }
        response.setDescription(msg.getMessage());
        op.addResponse(msg.getCode(), response);
      }

      // add path
      swagger.path(opPath, path);
    }
  }
Beispiel #16
0
  void appendRestfulObjectsSupportingPathsAndDefinitions() {

    final String tag = "> restful objects supporting resources";

    swagger.path(
        "/",
        new Path()
            .get(
                new Operation()
                    .tag(tag)
                    .description(Util.roSpec("5.1"))
                    .produces("application/json")
                    .produces(
                        "application/json;profile=urn:org.restfulobjects:repr-types/home-page")
                    .response(
                        200,
                        newResponse(Caching.NON_EXPIRING)
                            .description("OK")
                            .schema(newRefProperty("RestfulObjectsSupportingHomePageRepr")))));
    addDefinition("RestfulObjectsSupportingHomePageRepr", newModel(Util.roSpec("5.2")));

    swagger.path(
        "/user",
        new Path()
            .get(
                new Operation()
                    .tag(tag)
                    .description(Util.roSpec("6.1"))
                    .produces("application/json")
                    .produces("application/json;profile=urn:org.restfulobjects:repr-types/user")
                    .response(
                        200,
                        newResponse(Caching.USER_INFO)
                            .description("OK")
                            .schema(newRefProperty("RestfulObjectsSupportingUserRepr")))));
    addDefinition(
        "RestfulObjectsSupportingUserRepr",
        newModel(Util.roSpec("6.2"))
            .property("userName", stringProperty())
            .property("roles", arrayOfStrings())
            .property("links", arrayOfLinks())
            .required("userName")
            .required("roles"));

    swagger.path(
        "/services",
        new Path()
            .get(
                new Operation()
                    .tag(tag)
                    .description(Util.roSpec("7.1"))
                    .produces("application/json")
                    .produces("application/json;profile=urn:org.restfulobjects:repr-types/services")
                    .response(
                        200,
                        newResponse(Caching.USER_INFO)
                            .description("OK")
                            .schema(newRefProperty("RestfulObjectsSupportingServicesRepr")))));
    addDefinition(
        "RestfulObjectsSupportingServicesRepr",
        newModel(Util.roSpec("7.2"))
            .property("value", arrayOfLinks())
            .required("userName")
            .required("roles"));

    swagger.path(
        "/version",
        new Path()
            .get(
                new Operation()
                    .tag(tag)
                    .description(Util.roSpec("8.1"))
                    .produces("application/json")
                    .produces(
                        "application/json;profile=urn:org.restfulobjects:repr-types/RestfulObjectsSupportingServicesRepr")
                    .response(
                        200,
                        newResponse(Caching.NON_EXPIRING)
                            .description("OK")
                            .schema(new ObjectProperty()))));
    swagger.addDefinition(
        "RestfulObjectsSupportingServicesRepr",
        newModel(Util.roSpec("8.2"))
            .property("specVersion", stringProperty())
            .property("implVersion", stringProperty())
            .property(
                "optionalCapabilities",
                new ObjectProperty()
                    .property("blobsClobs", stringProperty())
                    .property("deleteObjects", stringProperty())
                    .property("domainModel", stringProperty())
                    .property("validateOnly", stringProperty())
                    .property("protoPersistentObjects", stringProperty()))
            .required("userName")
            .required("roles"));
  }
Beispiel #17
0
  public Swagger filter(
      Swagger swagger,
      SwaggerSpecFilter filter,
      Map<String, List<String>> params,
      Map<String, String> cookies,
      Map<String, List<String>> headers) {
    Swagger clone = new Swagger();
    clone
        .info(swagger.getInfo())
        .tags(swagger.getTags() == null ? null : new ArrayList<Tag>(swagger.getTags()))
        .host(swagger.getHost())
        .basePath(swagger.getBasePath())
        .schemes(swagger.getSchemes())
        .consumes(swagger.getConsumes())
        .produces(swagger.getProduces())
        .externalDocs(swagger.getExternalDocs())
        .vendorExtensions(swagger.getVendorExtensions());

    final Set<String> filteredTags = new HashSet<String>();
    final Set<String> allowedTags = new HashSet<String>();
    for (String resourcePath : swagger.getPaths().keySet()) {
      Path path = swagger.getPaths().get(resourcePath);
      Map<String, Operation> ops = new HashMap<String, Operation>();
      ops.put("get", path.getGet());
      ops.put("put", path.getPut());
      ops.put("post", path.getPost());
      ops.put("delete", path.getDelete());
      ops.put("patch", path.getPatch());
      ops.put("options", path.getOptions());

      Path clonedPath = new Path();
      for (String key : ops.keySet()) {
        Operation op = ops.get(key);
        if (op != null) {
          ApiDescription desc = new ApiDescription(resourcePath, key);
          final Set<String> tags;
          if (filter.isOperationAllowed(op, desc, params, cookies, headers)) {
            clonedPath.set(key, filterOperation(filter, op, desc, params, cookies, headers));
            tags = allowedTags;
          } else {
            tags = filteredTags;
          }
          if (op.getTags() != null) {
            tags.addAll(op.getTags());
          }
        }
      }
      if (!clonedPath.isEmpty()) {
        clone.path(resourcePath, clonedPath);
      }
    }
    final List<Tag> tags = clone.getTags();
    filteredTags.removeAll(allowedTags);
    if (tags != null && !filteredTags.isEmpty()) {
      for (Iterator<Tag> it = tags.iterator(); it.hasNext(); ) {
        if (filteredTags.contains(it.next().getName())) {
          it.remove();
        }
      }
      if (clone.getTags().isEmpty()) {
        clone.setTags(null);
      }
    }

    Map<String, Model> definitions =
        filterDefinitions(filter, swagger.getDefinitions(), params, cookies, headers);
    clone.setSecurityDefinitions(swagger.getSecurityDefinitions());
    clone.setDefinitions(definitions);

    // isRemovingUnreferencedDefinitions is not defined in SwaggerSpecFilter to avoid breaking
    // compatibility with
    // existing client filters directly implementing SwaggerSpecFilter.
    if (filter instanceof AbstractSpecFilter) {
      if (((AbstractSpecFilter) filter).isRemovingUnreferencedDefinitions()) {
        clone = removeBrokenReferenceDefinitions(clone);
      }
    }

    return clone;
  }