Skip to content

Instantly share code, notes, and snippets.

@arnaudbos
Last active February 12, 2018 09:40
Show Gist options
  • Save arnaudbos/96478c325a0e16e621e968e1141655b9 to your computer and use it in GitHub Desktop.
Save arnaudbos/96478c325a0e16e621e968e1141655b9 to your computer and use it in GitHub Desktop.
Swagger binary and Codegen InputStream
package com.mycompany.myproject.resources.utils;
import com.fasterxml.jackson.databind.JavaType;
import io.swagger.converter.ModelConverter;
import io.swagger.converter.ModelConverterContext;
import io.swagger.models.Model;
import io.swagger.models.Xml;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import io.swagger.util.Json;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Iterator;
public class BinaryPropertyConverter implements ModelConverter {
@Override
public Property resolveProperty(Type type, ModelConverterContext context, Annotation[] annotations, Iterator<ModelConverter> chain) {
JavaType _type = Json.mapper().constructType(type);
if (_type != null) {
Class<?> cls = _type.getRawClass();
if (Binary.class.isAssignableFrom(cls)) {
return new BinaryProperty();
}
}
if (chain.hasNext()) {
return chain.next().resolveProperty(type, context, annotations, chain);
} else {
return null;
}
}
@Override
public Model resolve(Type type, ModelConverterContext context, Iterator<ModelConverter> chain) {
if (chain.hasNext()) {
return chain.next().resolve(type, context, chain);
} else {
return null;
}
}
public static class Binary {
}
public static class BinaryProperty extends StringProperty implements Property {
public BinaryProperty() {
super.type = "string";
super.format = "binary";
}
public static boolean isType(String type, String format) {
return "string".equals(type) && "binary".equals(format);
}
public BinaryProperty xml(Xml xml) {
this.setXml(xml);
return this;
}
public BinaryProperty example(String example) {
this.setExample(example);
return this;
}
public BinaryProperty vendorExtension(String key, Object obj) {
this.setVendorExtension(key, obj);
return this;
}
public BinaryProperty readOnly() {
this.setReadOnly(Boolean.TRUE);
return this;
}
}
}
@GET @Path("/{thingId}/preview")
@Produces("image/jpeg")
@ApiOperation(
value = "Get thing preview",
produces = "image/jpeg", // For example
response = BinaryPropertyConverter.Binary.class
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The preview"),
@ApiResponse(code = 404, message = "Thing not found"),
@ApiResponse(code = 500, message = "Application Server Error")
})
public Response getThingPreview(
@ApiParam("Thing ID") @PathParam("thingId") UUID thingId
) {
return the InputStream wrapped in the Response, or change the return type from Response to InputStream if it is your thing.
}
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Create a thing with preview",
produces = MediaType.APPLICATION_JSON
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Thing created", response = YOURTYPE.class),
@ApiResponse(code = 400, message = "Bad request"),
@ApiResponse(code = 500, message = "Application Server Error")
})
@ApiImplicitParams({
@ApiImplicitParam(name = "preview", value = "Thing preview", required = true, type = "string", format = "binary", paramType = "form"))
})
public Response postProduct(
@FormDataParam("preview") InputStream preview)
{
return YOURTYPE in the Response, or change the return type from Response to YOURTYPE if it is your thing.
}
<plugin>
<groupId>com.github.kongchen</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<version>3.1.6</version>
<executions>
<execution>
<id>Generate swagger specification</id>
<phase>install</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<apiSources>
<apiSource>
<locations>com.mycompany.myproject</locations>
<basePath>/services</basePath>
<swaggerDirectory>target/generated-resources/swagger</swaggerDirectory>
<info>
<title>Myproject API</title>
<version>v${project.version}</version>
</info>
<modelConverters>com.mycompany.myproject.resources.utils.BinaryPropertyConverter</modelConverters>
</apiSource>
</apiSources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>Generate swagger client code</id>
<phase>install</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<addCompileSourceRoot>false</addCompileSourceRoot>
<inputSpec>target/generated-resources/swagger/swagger.json</inputSpec>
<output>${project.parent.basedir}/myproject-client-gen</output>
<language>java</language>
<library>retrofit2</library>
<apiPackage>com.mycompany.myproject.client.api</apiPackage>
<groupId>${project.groupId}</groupId>
<artifactId>myproject-client-gen</artifactId>
<artifactVersion>${project.version}</artifactVersion>
<configOptions>
<dateLibrary>joda</dateLibrary>
<type-mappings>binary=java.io.InputStream</type-mappings>
</configOptions>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-cli</artifactId>
<version>2.2.3</version>
</dependency>
</dependencies>
</plugin>
@arnaudbos
Copy link
Author

arnaudbos commented Feb 12, 2018

For return types

@ApiOperation(
        value = "Get thing preview",
        produces = "image/jpeg",
        response = BinaryPropertyConverter.Binary.class
)

Will get you a swagger.json spec with:

            "schema" : {
              "type" : "string",
              "format" : "binary"
            }

And a client "API" interface with return type:

Call<java.io.InputStream> getThingPreview

For paramaters:

    @ApiImplicitParams({
            @ApiImplicitParam(name = "preview", value = "Thing preview", required = true, type = "string", format = "binary", paramType = "form")
    })

Will get to spec:

        {
          "name" : "preview",
          "in" : "formData",
          "description" : "Thing preview",
          "required" : true,
          "type" : "string",
          "format" : "binary"
        }

And client:

Call<YourReturnType> postProduct(
    @retrofit2.http.Part("preview") java.io.InputStream preview);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment