CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-immutables--immutables

Comprehensive Java annotation processing framework for generating immutable value objects, marshalers, repositories, and custom code generators with extensive integration support.

Pending
Overview
Eval results
Files

runtime-marshaling.mddocs/

Runtime Marshaling Framework

Runtime utilities for JSON marshaling, async operations, and framework integrations. These components provide the foundation for serialization, database operations, and integration with popular Java frameworks.

Capabilities

Core Marshaling

Abstract base class for JSON marshaling of immutable objects.

/**
 * Abstract marshaler for type T, providing JSON serialization and deserialization
 * capabilities. Generated marshalers extend this class to handle specific types.
 */
public abstract class Marshaler<T> {
  
  /** Unmarshal single instance from JSON parser */
  public abstract T unmarshalInstance(@WillNotClose JsonParser parser) throws IOException;
  
  /** Unmarshal collection of instances from JSON parser */
  public abstract Iterable<T> unmarshalIterable(@WillNotClose JsonParser parser) throws IOException;
  
  /** Marshal single instance to JSON generator */
  public abstract void marshalInstance(@WillNotClose JsonGenerator generator, T instance) throws IOException;
  
  /** Marshal collection of instances to JSON generator */
  public abstract void marshalIterable(@WillNotClose JsonGenerator generator, Iterable<T> iterable) throws IOException;
  
  /** Get the expected type this marshaler handles */
  public abstract Class<T> getExpectedType();
}

Marshaling Utilities

Convenient static methods for JSON marshaling operations.

/**
 * Utility class providing convenient methods for JSON marshaling and unmarshaling
 * of objects using generated marshalers.
 */
public final class Marshaling {
  
  /** Convert object to pretty-printed JSON string */
  public static String toJson(Object object);
  
  /** Parse JSON string to object of expected type */
  public static <T> T fromJson(String json, Class<? extends T> expectedType);
  
  /** Get marshaler instance for specified type */
  public static <T> Marshaler<T> marshalerFor(Class<? extends T> expectedType);
  
  /** Set fallback Jackson ObjectCodec for unknown types */
  public static void setFallbackCodec(@Nullable ObjectCodec fallbackCodec);
  
  /** Get currently configured fallback ObjectCodec */
  public static ObjectCodec getFallbackCodec();
}

Usage Examples:

import org.immutables.common.marshal.Marshaling;

// Convert immutable object to JSON
Person person = ImmutablePerson.builder()
    .name("Alice")
    .age(30)
    .build();
String json = Marshaling.toJson(person);
System.out.println(json); // {"name":"Alice","age":30}

// Parse JSON back to object
Person parsed = Marshaling.fromJson(json, Person.class);
assert person.equals(parsed);

// Get marshaler for advanced usage
Marshaler<Person> marshaler = Marshaling.marshalerFor(Person.class);

Repository Framework

Repository Base Class

Abstract base class for MongoDB repository operations with async futures.

/**
 * Abstract base class for repository implementations providing
 * MongoDB operations with FluentFuture return types.
 */
public static abstract class Repositories.Repository<T> {
  
  /** 
   * Create repository with configuration, collection name, and marshaler
   * @param configuration Database setup and executor configuration
   * @param collectionName MongoDB collection name
   * @param marshaler Marshaler for type T
   */
  protected Repository(RepositorySetup configuration, String collectionName, Marshaler<T> marshaler);
}

Repository Setup

Configuration class for repository database connections and executors.

/**
 * Configuration setup for repository connections, providing database
 * connection and executor configuration for async operations.
 */
public final class RepositorySetup {
  
  /** Create setup builder */
  public static Builder builder();
  
  /** Create setup from MongoDB URI string */
  public static RepositorySetup forUri(String uri);
  
  /**
   * Builder for repository setup configuration
   */
  public static class Builder {
    /** Set executor service for async operations */  
    public Builder executor(ListeningExecutorService executor);
    
    /** Set MongoDB database instance */
    public Builder database(DB database);
    
    /** Build final repository setup */
    public RepositorySetup build();
  }
}

Usage Example:

import org.immutables.common.repository.RepositorySetup;
import org.immutables.common.repository.Repositories;

// Setup repository configuration
RepositorySetup setup = RepositorySetup.builder()
    .database(mongoClient.getDB("myapp"))
    .executor(MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()))
    .build();

// Create repository (typically auto-generated)
@Mongo.Repository("users")
public abstract class UserRepository extends Repositories.Repository<User> {
  public UserRepository(RepositorySetup setup) {
    super(setup, "users", UserMarshaler.instance());
  }
}

Async Utilities

FluentFuture Interface

Enhanced ListenableFuture with fluent method chaining for async operations.

/**
 * Enhanced ListenableFuture interface providing fluent method chaining,
 * transformation capabilities, and improved error handling for async operations.
 */
public interface FluentFuture<V> extends ListenableFuture<V> {
  
  /** Get result with unchecked exception handling */
  V getUnchecked();
  
  /** Add completion callback, returning this future for chaining */
  FluentFuture<V> addCallback(FutureCallback<V> callback);
  
  /** Add fallback handling for failures */
  FluentFuture<V> withFallback(FutureFallback<V> fallback);
  
  /** Add fallback value for failures */
  FluentFuture<V> withFallbackValue(V value);
  
  /** Specify executor for transformations */
  FluentFuture<V> withExecutor(Executor executor);
  
  /** Transform result synchronously */
  <T> FluentFuture<T> transform(Function<? super V, ? extends T> function);
  
  /** Transform result asynchronously */
  <T> FluentFuture<T> transform(AsyncFunction<? super V, ? extends T> function);
  
  /** Transform result lazily (on access) */
  <T> FluentFuture<T> lazyTransform(Function<? super V, ? extends T> function);
}

Usage Example:

import org.immutables.common.concurrent.FluentFuture;

// Chain async operations fluently
FluentFuture<String> result = userRepository.findById("123")
    .transform(user -> user.email())
    .withFallbackValue("unknown@example.com")
    .addCallback(new FutureCallback<String>() {
      public void onSuccess(String email) {
        System.out.println("User email: " + email);
      }
      public void onFailure(Throwable t) {
        System.err.println("Failed to get email: " + t.getMessage());
      }
    });

Framework Integrations

JDBI Integration

ResultSetMapperFactory for integrating with JDBI SQL framework.

/**
 * JDBI ResultSetMapperFactory for mapping query results to immutable objects.
 * Register this factory with JDBI to enable automatic mapping of immutable types.
 */
@Beta
public class MapperFactory implements ResultSetMapperFactory {
  
  /** Check if this factory can handle the specified type */
  @Override
  public final boolean accepts(Class type, StatementContext ctx);
}

Usage Example:

import org.immutables.common.jdbi.MapperFactory;

// Register with JDBI for automatic immutable object mapping
DBI dbi = new DBI(dataSource);
dbi.registerMapper(new MapperFactory());

// Query returns immutable objects automatically
List<Person> people = dbi.withHandle(handle -> 
    handle.createQuery("SELECT name, age FROM people")
          .mapTo(Person.class)
          .list()
);

JAX-RS Integration

MessageBodyReader and MessageBodyWriter for JAX-RS JSON processing.

/**
 * JAX-RS MessageBodyReader and MessageBodyWriter providing JSON marshaling
 * for REST endpoints using generated marshalers.
 */
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class JaxrsMessageBodyProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
  // Automatic JSON marshaling for JAX-RS endpoints
}

Usage Example:

import org.immutables.common.marshal.JaxrsMessageBodyProvider;

// Register provider with JAX-RS application
@ApplicationPath("/api")
public class MyApplication extends Application {
  @Override
  public Set<Class<?>> getClasses() {
    return Set.of(
        JaxrsMessageBodyProvider.class,
        UserResource.class
    );
  }
}

// REST endpoint automatically handles JSON marshaling
@Path("/users")
public class UserResource {
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Person createUser(Person person) {
    // Person automatically unmarshaled from JSON request
    // Return value automatically marshaled to JSON response
    return userService.create(person);
  }
}

Advanced Usage Patterns

Custom Marshaler Implementation

public class PersonMarshaler extends Marshaler<Person> {
  
  @Override
  public Person unmarshalInstance(JsonParser parser) throws IOException {
    // Custom unmarshaling logic
    ImmutablePerson.Builder builder = ImmutablePerson.builder();
    
    while (parser.nextToken() != JsonToken.END_OBJECT) {
      String fieldName = parser.getCurrentName();
      parser.nextToken();
      
      switch (fieldName) {
        case "name":
          builder.name(parser.getValueAsString());
          break;
        case "age":
          builder.age(parser.getValueAsInt());
          break;
      }
    }
    
    return builder.build();
  }
  
  @Override
  public void marshalInstance(JsonGenerator generator, Person person) throws IOException {
    generator.writeStartObject();
    generator.writeStringField("name", person.name());
    generator.writeNumberField("age", person.age());
    generator.writeEndObject();
  }
  
  // Other required methods...
}

Repository with Custom Operations

public class UserRepository extends Repositories.Repository<User> {
  
  public UserRepository(RepositorySetup setup) {
    super(setup, "users", UserMarshaler.instance());
  }
  
  public FluentFuture<Optional<User>> findByEmail(String email) {
    return findOne(criteria().email(email));
  }
  
  public FluentFuture<List<User>> findActiveUsers() {
    return findAll(criteria().active(true));
  }
  
  public FluentFuture<User> updateLastLogin(String userId) {
    return upsert(
        criteria().id(userId),
        modifier().lastLogin(Instant.now())
    );
  }
}

Install with Tessl CLI

npx tessl i tessl/maven-org-immutables--immutables

docs

attributes.md

bean-style.md

code-generation.md

collections.md

core-immutable.md

index.md

integrations.md

json-marshaling.md

runtime-marshaling.md

styling.md

tile.json