GithubHelp home page GithubHelp logo

k-simons / conjure-java Goto Github PK

View Code? Open in Web Editor NEW

This project forked from palantir/conjure-java

0.0 1.0 0.0 682 KB

Conjure generator for Java clients and servers

License: Apache License 2.0

Shell 0.01% Java 99.99%

conjure-java's Introduction

Conjure-Java Bintray License

CLI to generate Java POJOs and interfaces from Conjure API definitions.

Usage

The recommended way to use conjure-java is via a build tool like gradle-conjure. However, if you don't want to use gradle-conjure, there is also an executable which conforms to RFC 002, published on bintray.

Usage: conjure-java generate [...options] <input> <output>

Generate Java bindings for a Conjure API
    <input>      Path to the input IR file
    <output>     Output directory for generated source

Options:
    --objects    Generate POJOs for Conjure type definitions
    --jersey     Generate jax-rs annotated interfaces for client or server-usage
    --retrofit   Generate retrofit interfaces for streaming/async clients
    --requireNotNullAuthAndBodyParams
                 Generate @NotNull annotations for AuthHeaders and request body params
    --retrofitCompletableFutures
                 Generate retrofit services which return Java8 CompletableFuture instead of OkHttp Call (deprecated)
    --retrofitListenableFutures
                 Generate retrofit services which return Guava ListenableFuture instead of OkHttp Call

Feature Flags

Conjure-java supports feature flags to enable additional opt-in features. To enable features provided by a feature flag, simply supply the feature flag as an additional parameter when executing conjure-java. Available feature flags can be found in the FeatureFlags class.

Example generated objects

Conjure-java objects are always immutable and thread-safe. Fields are never null; instead, Java 8 Optionals are used. JSON serialization is handled using Jackson annotations.

  • Conjure object: ManyFieldExample

    Objects can only be instantiated using the builder pattern:

    ManyFieldExample example = ManyFieldExample.builder()
            .string("foo")
            .integer(123)
            .optionalItem("bar")
            .addAllItems(iterable)
            .build();

    Or using Jackson via conjure-jackson-serialization:

    ObjectMapper mapper = ObjectMappers.newServerObjectMapper();
    ManyFieldExample fromJson = mapper.readValue("{\"string\":\"foo\", ...}", ManyFieldExample.class);
  • Conjure union: UnionTypeExample

    Union types can be one of a few variants. To interact with a union value, users should use the .accept method and define a Visitor that handles each of the possible variants, including the possibility of an unknown variant.

    Foo output = unionTypeExample.accept(new Visitor<Foo>() {
    
        public Foo visitStringExample(StringExample value) {
            // your logic here!
        }
    
        public Foo visitSet(Set<String> value) {}
    
        // ...
    
        public Foo visitUnknown(String unknownType) {}
    
    });

    Visitors may seem clunky in Java, but they have the upside of compile-time assurance that you've handled all the possible variants. If you upgrade an API dependency and the API author added a new variant, the Java compiler will force you to explicitly deal with this new variant. We intentionally avoid switch statements and instanceof checks for this exact reason.

  • Conjure enum: EnumExample

    Enums are subtly different from regular Java enums because they tolerate deserializing unknown values. This is important because it ensures server authors can add new variants to an enum without causing runtime errors for consumers that use older API jars.

    EnumExample one = EnumExample.ONE;
    System.out.println(one); // prints: 'ONE'
    
    EnumExample fromJson = mapper.readValue("\"XYZ\"", EnumExample.class);
    System.out.println(fromJson); // prints: 'XYZ'
  • Conjure alias: StringAliasExample

    Aliases have exactly the same JSON representation as their inner type, so they are useful for making error-prone function signatures more bulletproof:

    -doSomething(String, String, String);
    +doSomething(ProductId, UserId, EmailAddress);

Example Jersey interfaces

Conjure-java generates Java interfaces with JAX-RS annotations, so they can be used on the client side or on the server-side.

Example jersey interface: EteService

@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/")
@Generated("com.palantir.conjure.java.services.JerseyServiceGenerator")
public interface EteService {
    @GET
    @Path("base/string")
    String string(@HeaderParam("Authorization") AuthHeader authHeader);
}

Jersey clients

Use conjure-java-runtime's JaxRsClient which configures Feign with sensible defaults:

RecipeBookService recipes = JaxRsClient.create(
        RecipeBookService.class,
        userAgent,
        hostMetrics,
        clientConfiguration);

List<Recipe> results = recipes.getRecipes();

Jersey servers

You need a Jersey-compatible server. We recommend Dropwizard (which is based on Jetty), but Grizzly, Tomcat, etc should also work fine. Use conjure-java-runtime's ConjureJerseyFeature to configure Jackson and Exception mappers appropriately. Then, you just need to implement the interface:

public final class RecipeBookResource implements RecipeBookService {

    @Override
    public List<Recipe> getRecipes() {
        // ...
    }
}

Then in your server main method, register your resource. For example, using Dropwizard:

 public void run(YourConfiguration configuration, Environment environment) {
     // ...
+    environment.jersey().register(new RecipeBookResource());
 }

Example Retrofit2 interfaces

As an alternative to the JAX-RS interfaces above, conjure-java can generate equivalent interfaces with Retrofit2 annotations. These clients are useful if you want to stream binary data or make non-blocking async calls:

Example Retrofit2 interface: EteServiceRetrofit

public interface EteServiceRetrofit {

    @GET("./base/binary")
    @Streaming
    Call<ResponseBody> binary(@Header("Authorization") AuthHeader authHeader);
}

Retrofit2 clients

Use conjure-java-runtime's Retrofit2Client which configures Retrofit2 with sensible defaults:

RecipeBookServiceRetrofit recipes = Retrofit2Client.create(
            RecipeBookServiceRetrofit.class,
            userAgent,
            hostMetrics,
            clientConfiguration);

Call<List<Recipe>> asyncResults = recipes.getRecipes();

Contributing

For instructions on how to set up your local development environment, check out the Contributing document.

License

This project is made available under the Apache 2.0 License.

conjure-java's People

Contributors

dansanduleac avatar dgleish avatar dtobin avatar ellisjoe avatar ferozco avatar iamdanfox avatar j-baker avatar jaceklach avatar markelliot avatar mcopes73 avatar pkoenig10 avatar qinfchen avatar robert3005 avatar svc-excavator-bot avatar tom-s-powell avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.