@Test
  public void resolveInlineModelTest() throws Exception {
    Swagger swagger = new Swagger();

    swagger.addDefinition(
        "User",
        new ModelImpl()
            .name("user")
            .description("a common user")
            .property("name", new StringProperty())
            .property(
                "address",
                new ObjectProperty()
                    .title("title")
                    ._default("default")
                    .access("access")
                    .readOnly(false)
                    .required(true)
                    .description("description")
                    .name("name")
                    .property("street", new StringProperty())
                    .property("city", new StringProperty())));

    new InlineModelResolver().flatten(swagger);

    ModelImpl user = (ModelImpl) swagger.getDefinitions().get("User");

    assertNotNull(user);
    assertTrue(user.getProperties().get("address") instanceof RefProperty);

    ModelImpl address = (ModelImpl) swagger.getDefinitions().get("User_address");
    assertNotNull(address);
    assertNotNull(address.getProperties().get("city"));
    assertNotNull(address.getProperties().get("street"));
  }
  @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"));
  }
  @Override
  public void preprocessSwagger(Swagger swagger) {
    if (swagger != null && swagger.getPaths() != null) {
      for (String pathname : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathname);
        if (path.getOperations() != null) {
          for (Operation operation : path.getOperations()) {
            boolean hasFormParameters = false;
            for (Parameter parameter : operation.getParameters()) {
              if (parameter instanceof FormParameter) {
                hasFormParameters = true;
              }
            }

            String defaultContentType =
                hasFormParameters ? "application/x-www-form-urlencoded" : "application/json";
            String contentType =
                operation.getConsumes() == null || operation.getConsumes().isEmpty()
                    ? defaultContentType
                    : operation.getConsumes().get(0);
            String accepts = getAccept(operation);
            operation.setVendorExtension("x-contentType", contentType);
            operation.setVendorExtension("x-accepts", accepts);
          }
        }
      }
    }
  }
  @Test
  public void testGenerateUniqueOperationIds() {
    final File output = folder.getRoot();

    final Swagger swagger =
        new SwaggerParser().read("src/test/resources/2_0/duplicateOperationIds.yaml");
    CodegenConfig codegenConfig = new JavaClientCodegen();
    codegenConfig.setOutputDir(output.getAbsolutePath());

    ClientOptInput clientOptInput =
        new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig);

    DefaultGenerator generator = new DefaultGenerator();
    generator.opts(clientOptInput);

    Map<String, List<CodegenOperation>> paths = generator.processPaths(swagger.getPaths());
    Set<String> opIds = new HashSet<String>();
    for (String path : paths.keySet()) {
      List<CodegenOperation> ops = paths.get(path);
      for (CodegenOperation op : ops) {
        assertFalse(opIds.contains(op.operationId));
        opIds.add(op.operationId);
      }
    }
  }
  @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 resolveInlineArrayModel() throws Exception {
    Swagger swagger = new Swagger();

    swagger.addDefinition(
        "User",
        new ArrayModel()
            .items(
                new ObjectProperty()
                    .title("title")
                    ._default("default")
                    .access("access")
                    .readOnly(false)
                    .required(true)
                    .description("description")
                    .name("name")
                    .property("street", new StringProperty())
                    .property("city", new StringProperty())));

    new InlineModelResolver().flatten(swagger);

    Model model = swagger.getDefinitions().get("User");
    assertTrue(model instanceof ArrayModel);

    Model user = swagger.getDefinitions().get("User_inner");
    assertNotNull(user);
    assertEquals("description", user.getDescription());
  }
  @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);
  }
Ejemplo n.º 8
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(description = "returns NSData when response format is binary")
  public void binaryDataTest() {
    final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json");
    final DefaultCodegen codegen = new SwiftCodegen();
    final String path = "/tests/binaryResponse";
    final Operation p = model.getPaths().get(path).getPost();
    final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions());

    Assert.assertEquals(op.returnType, "NSData");
    Assert.assertEquals(op.bodyParam.dataType, "NSData");
    Assert.assertTrue(op.bodyParam.isBinary);
    Assert.assertTrue(op.responses.get(0).isBinary);
  }
Ejemplo n.º 10
0
 /**
  * If the class is annotated with swagger annotations its parsed into a Swagger model
  * representation which is added to swagger
  *
  * @param clazz the class such as pojo with swagger annotation
  * @param swagger the swagger model
  */
 private void appendModels(Class clazz, Swagger swagger) {
   RestModelConverters converters = new RestModelConverters();
   final Map<String, Model> models = converters.readClass(clazz);
   for (Map.Entry<String, Model> entry : models.entrySet()) {
     swagger.model(entry.getKey(), entry.getValue());
   }
 }
Ejemplo n.º 11
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);
  }
Ejemplo n.º 12
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)));
  }
Ejemplo n.º 13
0
 public SecuritySchemeDefinition fromSecurity(String name) {
   Map<String, SecuritySchemeDefinition> map = swagger.getSecurityDefinitions();
   if (map == null) {
     return null;
   }
   return map.get(name);
 }
Ejemplo n.º 14
0
  private Model asModel(String typeName, Swagger swagger) {
    boolean array = typeName.endsWith("[]");
    if (array) {
      typeName = typeName.substring(0, typeName.length() - 2);
    }

    if (swagger.getDefinitions() != null) {
      for (Model model : swagger.getDefinitions().values()) {
        StringProperty modelType = (StringProperty) model.getVendorExtensions().get("x-className");
        if (modelType != null && typeName.equals(modelType.getFormat())) {
          return model;
        }
      }
    }
    return null;
  }
  @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);
  }
Ejemplo n.º 16
0
  void appendLinkModelDefinition() {
    swagger.addDefinition(
        "LinkRepr",
        new ModelImpl()
            .type("object")
            .property(
                "rel",
                stringProperty()
                    .description("the relationship of the resource to this referencing resource"))
            .property(
                "href",
                stringProperty().description("the hyperlink reference (URL) of the resource"))
            .property("title", stringProperty().description("title to render"))
            .property(
                "method",
                stringPropertyEnum("GET", "POST", "PUT", "DELETE")
                    .description("HTTP verb to access"))
            .property(
                "type",
                stringProperty()
                    .description(
                        "Content-Type recognized by the resource (for HTTP Accept header)"))
            .property(
                "arguments",
                new ObjectProperty()
                    .description("Any arguments, to send as query strings or in body"))
            .property(
                "value", stringProperty().description("the representation of the link if followed"))
            .required("rel")
            .required("href")
            .required("method"));

    swagger.addDefinition(
        "HrefRepr",
        new ModelImpl()
            .type("object")
            .description(
                "Abbreviated version of the Link resource, used primarily to reference non-value objects")
            .property(
                "href",
                stringProperty().description("the hyperlink reference (URL) of the resource"))
            .required("href"));
  }
  @Test
  public void testSecurityWithoutGlobal() throws Exception {
    final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json");
    CodegenConfig codegenConfig = new JavaClientCodegen();

    ClientOptInput clientOptInput =
        new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig);

    DefaultGenerator gen = new DefaultGenerator();
    gen.opts(clientOptInput);
    Map<String, List<CodegenOperation>> paths = gen.processPaths(swagger.getPaths());

    CodegenSecurity cs, apiKey, petstoreAuth;

    // security of "getPetById": api_key
    CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById");
    assertEquals(getPetById.authMethods.size(), 2);
    cs = getPetById.authMethods.get(0);
    if ("api_key".equals(cs.name)) {
      apiKey = cs;
      petstoreAuth = getPetById.authMethods.get(1);
    } else {
      petstoreAuth = cs;
      apiKey = getPetById.authMethods.get(1);
    }
    assertEquals(petstoreAuth.name, "petstore_auth");
    assertEquals(petstoreAuth.type, "oauth2");
    assertEquals(apiKey.name, "api_key");
    assertEquals(apiKey.type, "apiKey");

    // security of "updatePetWithForm": petstore_auth
    CodegenOperation updatePetWithForm =
        findCodegenOperationByOperationId(paths, "updatePetWithForm");
    assertEquals(updatePetWithForm.authMethods.size(), 1);
    petstoreAuth = updatePetWithForm.authMethods.iterator().next();
    assertEquals(petstoreAuth.name, "petstore_auth");
    assertEquals(petstoreAuth.type, "oauth2");

    // security of "loginUser": null (no global security either)
    CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser");
    assertNull(loginUser.authMethods);
  }
Ejemplo n.º 18
0
 private void locateReferencedDefinitions(
     String ref, Set<String> nestedReferencedDefinitions, Swagger swagger) {
   // if not already processed so as to avoid infinite loops
   if (!nestedReferencedDefinitions.contains(ref)) {
     nestedReferencedDefinitions.add(ref);
     Model model = swagger.getDefinitions().get(ref);
     if (model != null) {
       locateReferencedDefinitions(model.getProperties(), nestedReferencedDefinitions, 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);
  }
Ejemplo n.º 20
0
  Swagger generate() {
    this.swagger = new Swagger();

    swagger.basePath(basePath);
    swagger.info(
        new Info()
            .version(
                "0.0.0") // TODO: provide some way of passing the name, version etc (some sort of
                         // SPI service?)
            .title(visibility.name() + " API"));

    appendRestfulObjectsSupportingPathsAndDefinitions();
    appendLinkModelDefinition();

    appendServicePathsAndDefinitions();
    appendObjectPathsAndDefinitions();

    appendDefinitionsForOrphanedReferences();

    return swagger;
  }
  @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);
  }
Ejemplo n.º 25
0
  private void assertSwagger(Swagger swagger) {
    assertEquals("/", swagger.getBasePath());

    assertEquals(INFO_DESCRIPTION, swagger.getInfo().getDescription());
    assertEquals(INFO_TERMS_OF_SERVICE, swagger.getInfo().getTermsOfService());

    // excluded prefixes
    assertNull(swagger.getPath(ServiceUriPaths.CORE_AUTHZ_USERS));
    assertNull(swagger.getPath(ServiceUriPaths.CORE_AUTHZ_ROLES));

    assertNotNull(swagger.getPath(ServiceUriPaths.CORE_PROCESSES));
    assertNotNull(swagger.getPath(ServiceUriPaths.CORE_CREDENTIALS));

    Path p = swagger.getPath("/cars");
    assertNotNull(p);
    assertNotNull(p.getPost());
    assertNotNull(p.getGet());

    assertNotNull(swagger.getPath("/cars/template"));
    assertNotNull(swagger.getPath("/cars/available"));
    assertNotNull(swagger.getPath("/cars/config"));
    assertNotNull(swagger.getPath("/cars/stats"));
    assertNotNull(swagger.getPath("/cars/subscriptions"));

    assertNotNull(swagger.getPath("/cars/{id}/template"));
    assertNotNull(swagger.getPath("/cars/{id}/available"));
    assertNotNull(swagger.getPath("/cars/{id}/config"));
    assertNotNull(swagger.getPath("/cars/{id}/stats"));
    assertNotNull(swagger.getPath("/cars/{id}/subscriptions"));

    p = swagger.getPath("/cars/{id}");
    assertNotNull(p);
    assertNull(p.getPost());
    assertNull(p.getPatch());
    assertNotNull(p.getGet());
    assertNotNull(p.getPut());

    p = swagger.getPath("/tokens");
    assertNotNull(p);
    assertNotNull(p.getGet());
    assertNotNull(p.getGet().getResponses());
    assertNotNull(p.getPost());
    assertNotNull(p.getPost().getParameters());
    assertNull(p.getPatch());
    assertNull(p.getDelete());

    Model model = swagger.getDefinitions().get(Utils.buildKind(UserToken.class));
    Map<String, Property> properties = model.getProperties();
    assertNull(properties.get(UserToken.FIELD_NAME_INTERNAL_ID));
  }
Ejemplo n.º 26
0
 private void addDefinition(final String key, final ModelImpl model) {
   addSwaggerDefinition(key);
   swagger.addDefinition(key, model);
 }
Ejemplo n.º 27
0
 void appendDefinitionsForOrphanedReferences() {
   final Set<String> referencesWithoutDefinition = getReferencesWithoutDefinition();
   for (String reference : referencesWithoutDefinition) {
     swagger.addDefinition(reference, new ModelImpl());
   }
 }
Ejemplo n.º 28
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)));
  }
Ejemplo n.º 29
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)));
  }
Ejemplo n.º 30
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"));
  }