Update 2015-09-10-A-comparison-of-Microservices-Frameworks.adoc

= A comparison of Microservices Frameworks
:hp-tags: Tech, Microservices, REST

Microservice is probably one of the most used term nowadays when speaking about software architecture. Although the underlying concepts aren't new, it is one of the biggest buzzword of the two last years.

To summarize, big monolithic architectures tend to become not very maintainable and extendable when they grow over a certain size. Moreover, they don't scale well (you scale by multiplying big applications), and you can't replace old parts easily.

One of the biggest advantages of microservices is to address these concerns: instead of building an entire application as one block, one can build it as a set of services which will communicate over some kind of messaging system (most of the time, REST over HTTP). Given that, you will be able to replace one piece if you need to, you can scale only one piece because you need to, and so on.

But there is a counterpart: as you're building a distributed system, you will have the disadvantages of a distributed system. Building a distributed system as microservices architecture is not that easy, but fortunately there are many frameworks to help you. This article will present some of them.

== Requirements

I don't want to make another comparison based on some "Hello World" application. Most of the frameworks provide a simple way to start a server and respond to a simple request with only one line.

But this is not the real life. In the real life, you should not use plain HTTP. You would use REST / HTTPS and have an HTTPS client. You would add a Location header after a successful creation, and add links to your JSON or XML representations. You should have metrics included, to monitor your application. You have some kind of security to protect the access to your API.

Here is a list of what I am going to evaluate.

* I'm about to build a tiny RESTful API. UI is not considered in this article (note that every candidate framework has a mean to serve static resources easily)
* Only use HTTPS to access the API
* The API will have two sets of resources (aka two microservices). For simplicity's sake, they will be deployed in the same server, but will communicate over HTTPS.
* The resource will have a JSON representation
* Each representation will have at least a self link to the resource
* After a resource creation, client receive a Location header (the resource's link)
* The API will be accessible only by people providing a Facebook OAuth token
* Each API must have a monitoring / metrics facility
* Each service may be packaged as a standalone jar, to be run using `java -jar`.
* On the performance side, I will measure:
** request time of POST and GET
** the startup time of each server (not that important, but interesting)
** the memory footprint of the application
* Finally, I will give the final size of the package.

== The candidates

Here is the list of candidates:

* http://www.dropwizard.io/[Dropwizard]
* http://vertx.io/[Vertx]
* http://projects.spring.io/spring-boot/[Spring Boot]
* http://restlet.com/projects/restlet-framework/[Restlet]
* http://sparkjava.com/[Spark] + http://unirest.io/java.html[Unirest] (REST client, Spark doesn't provide a REST client itself)

Note that Restlet and Spark doesn't claim to be MicroServices frameworks, but Restlet is known to be a very good REST framework, and Spark is so lightweight that I couldn't resist to try it against bigger frameworks like Spring Boot.

== Prerequisites

Each sample run with a simple `java -jar` command. You will need to set some properties to enable ssl: `-Djavax.net.ssl.trustStore=... -Djavax.net.ssl.trustStorePassword=... -Djavax.net.ssl.keyStorePassword=... -Djavax.net.ssl.keyStorePath=...`.

In order to be able to run the samples, you need to create a keystore (see http://www.javacodegeeks.com/2014/07/java-keystore-tutorial.html[this tutorial] for example), and install a self-signed certificate. You will need the Facebook certificate too (see http://serverfault.com/questions/139728/how-to-download-the-ssl-certificate-from-a-website[here] how to get it), and a user token (see https://developers.facebook.com/).

Don't forget to modify the configuration files and system properties accordingly. All these steps are explained in the README file.

== Dropwizard

As stated by its website, "`Dropwizard is a Java framework for developing ops-friendly, high-performance, RESTful web services.`". It is a bundle of some successful libraries such as Jetty, Jersey and Jackson. The documentation is very good, I've found everything I needed inside; a good point, as I hate being forced to search for minutes (hours?) for something said simple.

=== Main

The main mehod is quite simple: you just build an `Application` instance and run it:
[source,java]
----
public static void main(String[] args) throws Exception {
    new DropwizardApplication().run(args);
}
----

The `DropwizardApplication` class contains all the plumbing: resource and health checks registration, Guice bootstrapping and Jackson's `ObjectMapper` configuration. It is given an instance of a configuration class (`DropwizardServerConfiguration`) which is a POJO holding the configuration properties read from the YAML file passed as parameter to our application.

The app is run with parameters: `java -jar app.jar server config.yml`. The `server` parameter is here to tell Dropwizard to start the server, but you can also manipulate the database (I didn't try this).

=== Resources

Under the hood, Dropwizard uses Jersey, so the resources are just POJOs annotated with (a lot of) JAX-RS annotations:

[source,java]
----
@Path("/cars/{id}")
@Produces(MediaType.APPLICATION_JSON)
public class CarResource {

    @Context
    UriInfo uriInfo;

    @Inject
    private CarRepository carRepository;

    @GET
    public Response byId(@Auth User user, @PathParam("id") int carId) {
        Optional<Car> car = carRepository.byId(carId);
        return car.map(c -> {
            CarRepresentation carRepresentation = new CarRepresentation(c);
            carRepresentation.addLink(Link.self(uriInfo.getAbsolutePathBuilder().build(c.getId()).toString()));
            return Response.ok(carRepresentation).build();
        }).orElse(Response.status(Response.Status.NOT_FOUND).build());
    }
}
----

All the underlying HTTP handling is done by the framework, you have no mandatory access to request and response objects. In this case, the return is a `Response` but I could simply have returned the object; however, in that case the return code would not be the right one (201), so to have full control over it, I prefer that solution. Moreover, the 404 (Status.NOT_FOUND) is set on the response; I could throw an exception instead, and write a mapper to make an adequate response, but it's overkill (and I hate so-called "Business Exceptions").

Note that injection is performed by Guice. It seems that there is a CDI container provided with Jersey (hk2), but I didn't managed to make it work. Linking is handmade, and quite easy with the `UriInfo` object.

Dropwizard uses Jackson to serialize / deserialize the object returned to JSON, so you have nothing special to do... but you have to configure the `ObjectMapper` to disable errors on unknown properties (see http://martinfowler.com/bliki/TolerantReader.html[Tolerant Reader]).

=== HTTPS

HTTPS is configured in the YAML configuration file; the framework ignores the standard Java properties. The documentation explains exactly how to set it up, and there is no surprise here.

=== REST client

The REST client is built by Guice, as a singleton; it is not managed as documented, I didn't managed to make it work this way. Otherwise, nothing special about the client, the API is fluent and simple:

[source,java]
----
@Override
public List<Car> getAllCars(String auth) {
    WebTarget target = client.target("https://localhost:8443/app/cars");
    Invocation invocation = target.request(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + auth)
            .build(HttpMethod.GET);
    Car[] cars = invocation.invoke(Car[].class);
    return asList(cars);
}
----

The `Client`, this time, uses the standard properties.

=== Security

The authentication requires two things: first, implement the `Authenticator` interface. Note that he single method `authenticate` returns an `Optional<User>`, but not a Java 8's `Optional`, the Guava's one! What a pity... Nevermind. Second, you need to register the authenticator against Jersey:

[source,java]
----
environment.jersey().register(AuthFactory.binder(
                new OAuthFactory<>(guiceBundle.getInjector().getInstance(FacebookTokenAuthenticator.class),
                        getName() + "-Realm",
                        User.class)));
----

So far so good, it works as expected.

=== Monitoring

Dropwizard has a built-in monitoring system. You can register healthchecks to ensure that the app is up, and each resource can be metered simply using annotations. You can also add custom metrics, using the metrics registry obtained from the `Environment`.

=== Conclusion

While a bit verbose due to all the plumbing involved in the setup, Dropwizard is a nice framework. It provides all the functions needed to build a MicroServices-based application. However, to build tiny services, the amount of plumbing required can be too high compared to the business code; I would not recommend to use it in that case. Otherwise, you cannot go wrong!

== Vertx

"`Vertx is a tool-kit for building reactive applications on the JVM.`". You can develop with it in Java of course, but also many languages running on the JVM (Javascript, Scala, Ruby, Python, Clojure).

It also provides an actors-like system, the "verticles", which allow deployment of independent, concurrent, and potentially written in different language, services communicating over an event bus. As stated by the documentation, you are not forced to use this model (I didn't in this case, however I will give it a try!).

=== Main

The framework abstracts low level handling of HTTP, but you need to create the server by hand:

[source,java]
----
Vertx vertx = Vertx.create();
HttpServer server = vertx.createHttpServer(serverOptions);
----

Maybe you noticed the serverOptions parameter (sure you did!). This is the definition:

[source, java]
----
HttpServerOptions serverOptions = new HttpServerOptions()
                .setSsl(true)
                .setKeyStoreOptions(new JksOptions()
                        .setPath(System.getProperty("javax.net.ssl.keyStorePath"))
                        .setPassword(System.getProperty("javax.net.ssl.keyStorePassword")))
                .setPort(8090);
----

This object allows to set the port and SSL properties. It doesn't automatically get the standard properties, so you have to do it yourself. Not really a problem.

The main method creates the HTTP client, set the authentication system and binds "resources" to routes.

=== Resources

There is no resource class in Vertx. You just give handlers to routes:

[source, java]
----
CarResource carResource = new CarResource(carRepository);
router.get("/cars/:id").produces("application/json").handler(carResource::byId);
----

`CarResource` is simply a POJO having a method named `byId` with a `RoutingContext` as parameter:

[source, java]
----
public void byId(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    String idParam = routingContext.request().getParam("id");
    if (idParam == null) {
        response.setStatusCode(400).end();
    } else {
        Optional<Car> car = carRepository.byId(Integer.parseInt(idParam));
        if (car.isPresent()) {
            CarRepresentation carRepresentation = new CarRepresentation(car.get());
            carRepresentation.addLink(self(routingContext.request().absoluteURI()));
            response.putHeader("content-type", "application/json")
                    .end(Json.encode(carRepresentation));
        } else {
            response.setStatusCode(404).end();
        }
    }
}
----

As you can see, you have a total control on the response, and no choice about that. No problem, you know what you do, exactly. The JSON encoding is done by Jackson again, and you still have to disable the "fail on unknown property" feature.

Oh, by the way, this will not work without a subtle configuration on the route:

[source,java]
----
router.route("/cars*").handler(BodyHandler.create());
----

By default, Vertx ignores the body, so you have to explicitly say "I want to read it". Otherwise, you don't get the body content.

Note that this time, there is no dependency injection, all is done manually. Not a big deal.

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

TODO...
Its style is really puzzling at first sight for people like me that are not used to asynchronous programming. But once you get the thing, it's probably one of the best tools I ever used.

== Spring Boot

=== Main

=== Resources

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

== Restlet

=== Main

=== Resources

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

== SparkJava

=== Main

=== Resources

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

...

////
Toute remarque et aide à l'amélioration est bienvenue :)
////

== A conclusion
It's been a long journey. The study is not as complete as I first wanted, but I guess it's a good start.

NOTE: TODO blah blah...

All the code is available on github (give link). You are free and encouraged to fork, play with the code and give feedback.

= A comparison of Microservices Frameworks
:hp-tags: Tech, Microservices, REST

Microservice is probably one of the most used term nowadays when speaking about software architecture. Although the underlying concepts aren't new, it is one of the biggest buzzword of the two last years.

To summarize, big monolithic architectures tend to become not very maintainable and extendable when they grow over a certain size. Moreover, they don't scale well (you scale by multiplying big applications), and you can't replace old parts easily.

One of the biggest advantages of microservices is to address these concerns: instead of building an entire application as one block, one can build it as a set of services which will communicate over some kind of messaging system (most of the time, REST over HTTP). Given that, you will be able to replace one piece if you need to, you can scale only one piece because you need to, and so on.

But there is a counterpart: as you're building a distributed system, you will have the disadvantages of a distributed system. Building a distributed system as microservices architecture is not that easy, but fortunately there are many frameworks to help you. This article will present some of them.

== Requirements

I don't want to make another comparison based on some "Hello World" application. Most of the frameworks provide a simple way to start a server and respond to a simple request with only one line.

But this is not the real life. In the real life, you should not use plain HTTP. You would use REST / HTTPS and have an HTTPS client. You would add a Location header after a successful creation, and add links to your JSON or XML representations. You should have metrics included, to monitor your application. You have some kind of security to protect the access to your API.

Here is a list of what I am going to evaluate.

* I'm about to build a tiny RESTful API. UI is not considered in this article (note that every candidate framework has a mean to serve static resources easily)
* Only use HTTPS to access the API
* The API will have two sets of resources (aka two microservices). For simplicity's sake, they will be deployed in the same server, but will communicate over HTTPS.
* The resource will have a JSON representation
* Each representation will have at least a self link to the resource
* After a resource creation, client receive a Location header (the resource's link)
* The API will be accessible only by people providing a Facebook OAuth token
* Each API must have a monitoring / metrics facility
* Each service may be packaged as a standalone jar, to be run using `java -jar`.
* On the performance side, I will measure:
** request time of POST and GET
** the startup time of each server (not that important, but interesting)
** the memory footprint of the application
* Finally, I will give the final size of the package.

== The candidates

Here is the list of candidates:

* http://www.dropwizard.io/[Dropwizard]
* http://vertx.io/[Vertx]
* http://projects.spring.io/spring-boot/[Spring Boot]
* http://restlet.com/projects/restlet-framework/[Restlet]
* http://sparkjava.com/[Spark] + http://unirest.io/java.html[Unirest] (REST client, Spark doesn't provide a REST client itself)

Note that Restlet and Spark doesn't claim to be MicroServices frameworks, but Restlet is known to be a very good REST framework, and Spark is so lightweight that I couldn't resist to try it against bigger frameworks like Spring Boot.

== Prerequisites

Each sample run with a simple `java -jar` command. You will need to set some properties to enable ssl: `-Djavax.net.ssl.trustStore=... -Djavax.net.ssl.trustStorePassword=... -Djavax.net.ssl.keyStorePassword=... -Djavax.net.ssl.keyStorePath=...`.

In order to be able to run the samples, you need to create a keystore (see http://www.javacodegeeks.com/2014/07/java-keystore-tutorial.html[this tutorial] for example), and install a self-signed certificate. You will need the Facebook certificate too (see http://serverfault.com/questions/139728/how-to-download-the-ssl-certificate-from-a-website[here] how to get it), and a user token (see https://developers.facebook.com/).

Don't forget to modify the configuration files and system properties accordingly. All these steps are explained in the README file.

== Dropwizard

As stated by its website, "`Dropwizard is a Java framework for developing ops-friendly, high-performance, RESTful web services.`". It is a bundle of some successful libraries such as Jetty, Jersey and Jackson. The documentation is very good, I've found everything I needed inside; a good point, as I hate being forced to search for minutes (hours?) for something said simple.

=== Main

The main mehod is quite simple: you just build an `Application` instance and run it:
[source,java]
----
public static void main(String[] args) throws Exception {
    new DropwizardApplication().run(args);
}
----

The `DropwizardApplication` class contains all the plumbing: resource and health checks registration, Guice bootstrapping and Jackson's `ObjectMapper` configuration. It is given an instance of a configuration class (`DropwizardServerConfiguration`) which is a POJO holding the configuration properties read from the YAML file passed as parameter to our application.

The app is run with parameters: `java -jar app.jar server config.yml`. The `server` parameter is here to tell Dropwizard to start the server, but you can also manipulate the database (I didn't try this).

=== Resources

Under the hood, Dropwizard uses Jersey, so the resources are just POJOs annotated with (a lot of) JAX-RS annotations:

[source,java]
----
@Path("/cars/{id}")
@Produces(MediaType.APPLICATION_JSON)
public class CarResource {

    @Context
    UriInfo uriInfo;

    @Inject
    private CarRepository carRepository;

    @GET
    public Response byId(@Auth User user, @PathParam("id") int carId) {
        Optional<Car> car = carRepository.byId(carId);
        return car.map(c -> {
            CarRepresentation carRepresentation = new CarRepresentation(c);
            carRepresentation.addLink(Link.self(uriInfo.getAbsolutePathBuilder().build(c.getId()).toString()));
            return Response.ok(carRepresentation).build();
        }).orElse(Response.status(Response.Status.NOT_FOUND).build());
    }
}
----

All the underlying HTTP handling is done by the framework, you have no mandatory access to request and response objects. In this case, the return is a `Response` but I could simply have returned the object; however, in that case the return code would not be the right one (201), so to have full control over it, I prefer that solution. Moreover, the 404 (Status.NOT_FOUND) is set on the response; I could throw an exception instead, and write a mapper to make an adequate response, but it's overkill (and I hate so-called "Business Exceptions").

Note that injection is performed by Guice. It seems that there is a CDI container provided with Jersey (hk2), but I didn't managed to make it work. Linking is handmade, and quite easy with the `UriInfo` object.

Dropwizard uses Jackson to serialize / deserialize the object returned to JSON, so you have nothing special to do... but you have to configure the `ObjectMapper` to disable errors on unknown properties (see http://martinfowler.com/bliki/TolerantReader.html[Tolerant Reader]).

=== HTTPS

HTTPS is configured in the YAML configuration file; the framework ignores the standard Java properties. The documentation explains exactly how to set it up, and there is no surprise here.

=== REST client

The REST client is built by Guice, as a singleton; it is not managed as documented, I didn't managed to make it work this way. Otherwise, nothing special about the client, the API is fluent and simple:

[source,java]
----
@Override
public List<Car> getAllCars(String auth) {
    WebTarget target = client.target("https://localhost:8443/app/cars");
    Invocation invocation = target.request(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + auth)
            .build(HttpMethod.GET);
    Car[] cars = invocation.invoke(Car[].class);
    return asList(cars);
}
----

The `Client`, this time, uses the standard properties.

=== Security

The authentication requires two things: first, implement the `Authenticator` interface. Note that he single method `authenticate` returns an `Optional<User>`, but not a Java 8's `Optional`, the Guava's one! What a pity... Nevermind. Second, you need to register the authenticator against Jersey:

[source,java]
----
environment.jersey().register(AuthFactory.binder(
                new OAuthFactory<>(guiceBundle.getInjector().getInstance(FacebookTokenAuthenticator.class),
                        getName() + "-Realm",
                        User.class)));
----

So far so good, it works as expected.

=== Monitoring

Dropwizard has a built-in monitoring system. You can register healthchecks to ensure that the app is up, and each resource can be metered simply using annotations. You can also add custom metrics, using the metrics registry obtained from the `Environment`.

=== Conclusion

While a bit verbose due to all the plumbing involved in the setup, Dropwizard is a nice framework. It provides all the functions needed to build a MicroServices-based application. However, to build tiny services, the amount of plumbing required can be too high compared to the business code; I would not recommend to use it in that case. Otherwise, you cannot go wrong!

== Vertx

"`Vertx is a tool-kit for building reactive applications on the JVM.`". You can develop with it in Java of course, but also many languages running on the JVM (Javascript, Scala, Ruby, Python, Clojure).

It also provides an actors-like system, the "verticles", which allow deployment of independent, concurrent, and potentially written in different language, services communicating over an event bus. As stated by the documentation, you are not forced to use this model (I didn't in this case, however I will give it a try!).

=== Main

The framework abstracts low level handling of HTTP, but you need to create the server by hand:

[source,java]
----
Vertx vertx = Vertx.create();
HttpServer server = vertx.createHttpServer(serverOptions);
----

Maybe you noticed the serverOptions parameter (sure you did!). This is the definition:

[source, java]
----
HttpServerOptions serverOptions = new HttpServerOptions()
                .setSsl(true)
                .setKeyStoreOptions(new JksOptions()
                        .setPath(System.getProperty("javax.net.ssl.keyStorePath"))
                        .setPassword(System.getProperty("javax.net.ssl.keyStorePassword")))
                .setPort(8090);
----

This object allows to set the port and SSL properties. It doesn't automatically get the standard properties, so you have to do it yourself. Not really a problem.

The main method creates the HTTP client, set the authentication system and binds "resources" to routes.

=== Resources

There is no resource class in Vertx. You just give handlers to routes:

[source, java]
----
CarResource carResource = new CarResource(carRepository);
router.get("/cars/:id").produces("application/json").handler(carResource::byId);
----

`CarResource` is simply a POJO having a method named `byId` with a `RoutingContext` as parameter:

[source, java]
----
public void byId(RoutingContext routingContext) {
    HttpServerResponse response = routingContext.response();
    String idParam = routingContext.request().getParam("id");
    if (idParam == null) {
        response.setStatusCode(400).end();
    } else {
        Optional<Car> car = carRepository.byId(Integer.parseInt(idParam));
        if (car.isPresent()) {
            CarRepresentation carRepresentation = new CarRepresentation(car.get());
            carRepresentation.addLink(self(routingContext.request().absoluteURI()));
            response.putHeader("content-type", "application/json")
                    .end(Json.encode(carRepresentation));
        } else {
            response.setStatusCode(404).end();
        }
    }
}
----

Note that this time, there is no dependency injection, all is done manually. Not a big deal.

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

TODO...
Its style is really puzzling at first sight for people like me that are not used to asynchronous programming. But once you get the thing, it's probably one of the best tools I ever used.

== Spring Boot

=== Main

=== Resources

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

== Restlet

=== Main

=== Resources

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

== SparkJava

=== Main

=== Resources

=== HTTPS

=== REST Client

=== Security

=== Monitoring

=== Conclusion

...

////
Toute remarque et aide à l'amélioration est bienvenue :)
////

== A conclusion
It's been a long journey. The study is not as complete as I first wanted, but I guess it's a good start.

NOTE: TODO blah blah...

All the code is available on github (give link). You are free and encouraged to fork, play with the code and give feedback.


Update 2015-11-11-Episode-30-38-Weeks-Old-Next-week-Brains.adoc

= Episode 30: 38 Weeks Old. Next week: Brains
:hp-tags: UI, Mac, TotM, TotW, Beta, PC, Zen
:hp-image: logo.png
:published_at: 2015-11-11

It has been thirty-eight weeks since Chris kicked off this little thing called Table of the Month (TotM)!

We talk about some challenges with running the TotM/TotW and the results from the last tourney.

There’s new UI blah, Jared goes to the dark side and tests out TPA on Steam Mac, and we talk about Evil Week and Halloween in Aussie.

== Links

http://shoutengine.com/BlahCadePodcast/38-weeks-old-next-week-brains-13658[Stream/Download/RSS]

https://itunes.apple.com/us/podcast/blahcade-podcast/id1039748922?mt=2[iTunes]

https://blab.im/BlahCade[Blab.im Live Session]

https://represent.com/blahcade-shirt[BlahCade T-shirts on represent.com]

== Timings

* Intro
* Greetings and Salutations - 0:45
* TotM Admin Challenges - 3:50
* TotM Results - 8:00
* TotW - 9:50
* New UI PC Beta Hands-on - 14:55
* Android User Guide 2.0? - 21:35
* Jared Tries out TPA for Steam Mac - 23:50
* Insurance Day On Set - 27:00
* Evil Week - 31:35
* Halloween in Aussie - 39:50
* New PTX Album - 44:00
* Interview Plans and Tshirts - 44:45
* Penny for your Thoughts? - 46:00
* Sponsors and Outro - 47:00

= Episode 29: 38 Weeks Old. Next week: Brains
:hp-tags: UI, Mac, TotM, TotW, Beta, PC, Zen
:hp-image: logo.png
:published_at: 2015-11-11

It has been thirty-eight weeks since Chris kicked off this little thing called Table of the Month (TotM)!

We talk about some challenges with running the TotM/TotW and the results from the last tourney.

There’s new UI blah, Jared goes to the dark side and tests out TPA on Steam Mac, and we talk about Evil Week and Halloween in Aussie.

== Links

http://shoutengine.com/BlahCadePodcast/38-weeks-old-next-week-brains-13658[Stream/Download/RSS]

https://itunes.apple.com/us/podcast/blahcade-podcast/id1039748922?mt=2[iTunes]

https://blab.im/BlahCade[Blab.im Live Session]

https://represent.com/blahcade-shirt[BlahCade T-shirts on represent.com]

== Timings

* Intro
* Greetings and Salutations - 0:45
* TotM Admin Challenges - 3:50
* TotM Results - 8:00
* TotW - 9:50
* New UI PC Beta Hands-on - 14:55
* Android User Guide 2.0? - 21:35
* Jared Tries out TPA for Steam Mac - 23:50
* Insurance Day On Set - 27:00
* Evil Week - 31:35
* Halloween in Aussie - 39:50
* New PTX Album - 44:00
* Interview Plans and Tshirts - 44:45
* Penny for your Thoughts? - 46:00
* Sponsors and Outro - 47:00


Touched up ActivityStarter link

Touched up ActivityStarter link

---
layout: default
title: Parceler
documentationExpanded: false
postsExpanded: false
---

Have a question?  http://stackoverflow.com/questions/ask?tags=parceler[Ask it on StackOverflow.]

Found an issue?  https://github.com/johncarl81/parceler/issues/new[Please report it.]

image:https://badges.gitter.im/johncarl81/parceler.svg[link="https://gitter.im/johncarl81/parceler?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"]

=== Introduction

In Android, http://developer.android.com/reference/android/os/Parcelable.html[Parcelables] are a great way to serialize Java Objects between Contexts.
http://www.developerphil.com/parcelable-vs-serializable/[Compared] with traditional Serialization, Parcelables take on the order of 10x less time to both serialize and deserialize.
There is a major flaw with Parcelables, however.
Parcelables contain a ton of boilerplate code.
To implement a Parcelable, you must mirror the `writeToParcel()` and `createFromParcel()` methods such that they read and write to the Parcel in the same order.
Also, a Parcelable must define a `public static final Parcelable.Creator CREATOR` in order for the Android infrastructure to be able to leverage the serialization code.

Parceler is a code generation library that generates the Android Parcelable boilerplate source code.
No longer do you have to implement the Parcelable interface, the `writeToParcel()` or `createFromParcel()` or the `public static final CREATOR`.
You simply annotate a POJO with `@Parcel` and Parceler does the rest.
Because Parceler uses the Java JSR-269 Annotation Processor, there is no need to run a tool manually to generate the Parcelable code.
Just annotate your Java Bean, compile and you are finished.
By default, Parceler will serialize the fields of your instance directly:

[source,java]
----
@Parcel
public class Example {
    String name;
    int age;

    public Example() {}

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

Be careful not to use private fields when using the default field serialization strategy as it will incur a performance penalty due to reflection.

To use the generated code, you may reference the generated class directly, or via the `Parcels` utility class:

[source,java]
----
Parcelable wrapped = Parcels.wrap(new Example("Andy", 42));
----

To dereference the `@Parcel`, just call the `Parcels.unwrap()` method:

[source,java]
----
Example example = Parcels.unwrap(wrapped);
example.getName(); // Andy
example.getAge(); // 42
----

Of course, the wrapped `Parcelable` can be added to an Android Bundle to transfer from Activity to Activity:

[source,java]
----
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
----

And dereferenced in the `onCreate()` method:

[source,java]
----
Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
----

This wrapping and unwrapping technique plays well with the Intent Factory pattern.
In addition, Parceler is supported by the following libraries:

 * http://androidtransfuse.org/documentation.html#parcel[Transfuse] - Allows `@Parcel` annotated beans to be used with the `@Extra` injection.
 * https://github.com/sockeqwe/fragmentargs#argsbundler[FragmentArgs] - Uses the `ParcelerArgsBundler` adapter to wrap and unwrap `@Parcel` annotated beans with fragment parameters.
 * https://github.com/f2prateek/dart[Dart] - Autodetects `@Parcel` annotated beans and automatically unwraps them when using `@InjectExtra`.
 * http://androidannotations.org/[AndroidAnnotations] - Autodetects `@Parcel` annotated beans and https://github.com/excilys/androidannotations/wiki/ParcelerIntegration[automatically wraps/unwraps] them when using `@Extra`, `@FragmentArg`, `@InstanceState` and other `Bundle` related annotations.
 * https://github.com/MarcinMoskala/ActivityStarter/wiki/Parceler-Arg-Converter-usage[ActivityStarter] - Uses `ParcelarArgConverter` to allow use Parceler objects as arguments passed to Activities,  Fragments, Services, etc.

=== Parcel attribute types
Only a select number of types may be used as attributes of a `@Parcel` class.
The following list includes the mapped types:

 * `byte`
 * `double`
 * `float`
 * `int`
 * `long`
 * `char`
 * `boolean`
 * `String`
 * `IBinder`
 * `Bundle`
 * `SparseArray` of any of the mapped types*
 * `SparseBooleanArray`
 * `ObservableField`
 * `List`, `ArrayList` and `LinkedList` of any of the mapped types*
 * `Map`, `HashMap`, `LinkedHashMap`, `SortedMap`, and `TreeMap` of any of the mapped types*
 * `Set`, `HashSet`, `SortedSet`, `TreeSet`, `LinkedHashSet` of any of the mapped types*
 * `Parcelable`
 * `Serializable`
 * Array of any of the mapped types
 * Any other class annotated with `@Parcel`

*Parcel will error if the generic parameter is not mapped.

Parceler also supports any of the above types directly.
This is especially useful when dealing with collections of classes annotated with `@Parcel`:

[source,java]
----
Parcelable listParcelable = Parcels.wrap(new ArrayList<Example>());
Parcelable mapParcelable = Parcels.wrap(new HashMap<String, Example>());
----

==== Polymorphism
Note that Parceler does not unwrap inheritance hierarchies, so any polymorphic fields will be unwrapped as instances of the base class.
This is because Parceler opts for performance rather than checking `.getClass()` for every piece of data.

[source,java]
----
@Parcel
public class Example {
    public Parent p;
    @ParcelConstructor Example(Parent p) { this.p = p; }
}

@Parcel public class Parent {}
@Parcel public class Child extends Parent {}
----

[source,java]
----
Example example = new Example(new Child());
System.out.println("%b", example.p instanceof Child); // true
example = Parcels.unwrap(Parcels.wrap(example));
System.out.println("%b", example.p instanceof Child); // false
----

Refer to the <<custom_serialization,Custom Serialization>> section for an example of working with polymorphic fields.

=== Serialization techniques

Parceler offers several choices for how to serialize and deserialize an object in addition to the field-based serialization seen above.

==== Getter/setter serialization
Parceler may be configured to serialize using getter and setter methods and a non-empty constructor.
In addition, fields, methods and constructor parameters may be associated using the `@ParcelProperty` annotation.
This supports a number of bean strategies including immutability and traditional getter/setter beans.

To configure default method serialization, simply configure the `@Parcel` annotation with `Serialization.BEAN`:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
----

To use a constructor with serialization, annotate the desired constructor with the `@ParcelConstructor` annotation:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private final String name;
    private final int age;

    @ParcelConstructor
    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

If an empty constructor is present, Parceler will use that constructor unless another constructor is annotated.

==== Mixing getters/setters and fields
You may also mix and match serialization techniques using the `@ParcelProperty` annotation.
In the following example, `firstName` and `lastName` are written to the bean using the constructor while `firstName` is read from the bean using the field and `lastName` is read using the `getLastName()` method.
The parameters `firstName` and `lastName` are coordinated by the parameter names `"first"` and `"last"` respectfully.

[source,java]
----
@Parcel
public class Example {
    @ParcelProperty("first")
    String firstName;
    String lastName;

    @ParcelConstructor
    public Example(@ParcelProperty("first") String firstName, @ParcelProperty("last") String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() { return firstName; }

    @ParcelProperty("last")
    public String getLastName() { return lastName; }
}
----

For attributes that should not be serialized with Parceler, the attribute field, getter or setter may be annotated by `@Transient`.

Parceler supports many different styles centering around the POJO.
This allows `@Parcel` annotated classes to be used with other POJO based libraries, including the following:

 * https://code.google.com/p/google-gson/[GSON]
 * https://realm.io/docs/java/latest/#parceler[Realm]
 * https://bitbucket.org/littlerobots/cupboard[Cupboard]
 * http://simple.sourceforge.net/[Simple XML]
 * https://github.com/Raizlabs/DBFlow[DBFlow]

==== Static Factory support
As an alternative to using a constructor directly, Parceler supports using an annotated Static Factory to build an instance of the given class.
This style supports Google's https://github.com/google/auto/tree/master/value[AutoValue] annotation processor / code generation library for generating immutable beans.
Parceler interfaces with AutoValue via the `@ParcelFactory` annotation, which maps a static factory method into the annotated `@Parcel` serialization:

[source,java]
----
@AutoValue
@Parcel
public abstract class AutoValueParcel {

    @ParcelProperty("value") public abstract String value();

    @ParcelFactory
    public static AutoValueParcel create(String value) {
        return new AutoValue_AutoValueParcel(value);
    }
}
----

AutoValue generates a different class than the annotated `@Parcel`, therefore, you need to specify which class Parceler should build in the `Parcels` utility class:

[source,java]
----
Parcelable wrappedAutoValue = Parcels.wrap(AutoValueParcel.class, AutoValueParcel.create("example"));
----
And to deserialize:
[source,java]
----
AutoValueParcel autoValueParcel = Parcels.unwrap(wrappedAutoValue);
----

==== Custom serialization
`@Parcel` includes an optional parameter to include a manual serializer `ParcelConverter` for the case where special serialization is necessary.
This provides a still cleaner option for using Parcelable classes than implementing them by hand.

The following code demonstrates using a `ParcelConverter` to unwrap the inheritance hierarchy during deserialization.

[source,java]
----
@Parcel
public class Item {
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    public List<Item> itemList;
}
@Parcel public class SubItem1 extends Item {}
@Parcel public class SubItem2 extends Item {}

public class ItemListParcelConverter implements ParcelConverter<List<Item>> {
    @Override
    public void toParcel(List<Item> input, Parcel parcel) {
        if (input == null) {
            parcel.writeInt(-1);
        }
        else {
            parcel.writeInt(input.size());
            for (Item item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

    @Override
    public List<Item> fromParcel(Parcel parcel) {
        int size = parcel.readInt();
        if (size < 0) return null;
        List<Item> items = new ArrayList<Item>();
        for (int i = 0; i < size; ++i) {
            items.add((Item) Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader())));
        }
        return items;
    }
}
----

Parceler is also packaged with a series of base classes to make Collection conversion easier located under the `org.parceler.converter` package of the api.
These base classes take care of a variety of difficult or verbose jobs dealing with Collections including null checks and collectin iteration.
For instance, the above `ParcelConverter` could be written using the `ArrayListParcelConverter':

[source,java]
----
public class ItemListParcelConverter extends ArrayListParcelConverter<Item> {
    @Override
    public void itemToParcel(Item item, Parcel parcel) {
        parcel.writeParcelable(Parcels.wrap(item), 0);
    }

    @Override
    public Item itemFromParcel(Parcel parcel) {
        return Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader()));
    }
}
----

=== Classes without Java source
For classes whose corresponding Java source is not available, one may include the class as a Parcel by using the `@ParcelClass` annotation.
This annotation may be declared anywhere in the compiled source that is convenient.
For instance, one could include the `@ParcelClass` along with the Android Application:

[source,java]
----
@ParcelClass(LibraryParcel.class)
public class AndroidApplication extends Application{
    //...
}
----

Multiple `@ParcelClass` annotations may be declared using the `@ParcelClasses` annotation.

In addition, classes referenced by `@ParcelClass` may be configured using the `@Parcel` annotation.
This allows the serialization configuration through any parameter available on the `@Parcel` annotation including the serialization technique or classes to analyze.

One useful technique is the ability to define global custom converters for a type:
[source,java]
----
@ParcelClass(
    value = LibraryParcel.class,
    annotation = @Parcel(converter = LibraryParcelConverter.class))
class SomeClass{}
----
This allows for fine grained control over a class that isn't available for direct modification.

=== Advanced configuration

==== Skipping analysis
It is a common practice for some libraries to require a bean to extend a base class.
Although it is not the most optimal case, Parceler supports this practice by allowing the configuration of what classes in the inheritance hierarchy to analyze via the analyze parameter:

[source, java]
----
@Parcel(analyze = {One.class, Three.class})
class One extends Two {}
class Two extends Three {}
class Three extends BaseClass {}
----

In this example, only fields of the `One` and `Three` classes will be serialized, avoiding both the `BaseClass` and `Two` class parameters.

==== Specific wrapping

The Parcels utility class looks up the given class for wrapping by class.
For performance reasons this ignores inheritance, both super and base classes.
There are two solutions to this problem.
First, one may specify additional types to associate to the given type via the `implementations` parameter:

[source, java]
----
class ExampleProxy extends Example {}
@Parcel(implementations = {ExampleProxy.class})
class Example {}

ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(proxy);  // ExampleProxy will be serialized as a Example
----

Second, one may also specify the class type when using the `Parcels.wrap()` method:

[source, java]
----
ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(Example.class, proxy);
----

==== Configuring Proguard

To configure Proguard, add the following lines to your proguard configuration file.  These will keep files related to the `Parcels` utilty class and the `Parcelable` `CREATOR` instance:

----
# Parceler library
-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }
----

== Getting Parceler

You may download Parceler as a Maven dependency:

[source,xml]
----
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler</artifactId>
    <version>{{site.currentVersion}}</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler-api</artifactId>
    <version>{{site.currentVersion}}</version>
</dependency>
----

or Gradle:
[source,groovy]
----
compile 'org.parceler:parceler-api:{{site.currentVersion}}'
annotationProcessor 'org.parceler:parceler:{{site.currentVersion}}'
----

Or from http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.parceler%22[Maven Central].

== License
----
Copyright 2011-2015 John Ericksen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----

---
layout: default
title: Parceler
documentationExpanded: false
postsExpanded: false
---

Have a question?  http://stackoverflow.com/questions/ask?tags=parceler[Ask it on StackOverflow.]

Found an issue?  https://github.com/johncarl81/parceler/issues/new[Please report it.]

image:https://badges.gitter.im/johncarl81/parceler.svg[link="https://gitter.im/johncarl81/parceler?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"]

=== Introduction

In Android, http://developer.android.com/reference/android/os/Parcelable.html[Parcelables] are a great way to serialize Java Objects between Contexts.
http://www.developerphil.com/parcelable-vs-serializable/[Compared] with traditional Serialization, Parcelables take on the order of 10x less time to both serialize and deserialize.
There is a major flaw with Parcelables, however.
Parcelables contain a ton of boilerplate code.
To implement a Parcelable, you must mirror the `writeToParcel()` and `createFromParcel()` methods such that they read and write to the Parcel in the same order.
Also, a Parcelable must define a `public static final Parcelable.Creator CREATOR` in order for the Android infrastructure to be able to leverage the serialization code.

Parceler is a code generation library that generates the Android Parcelable boilerplate source code.
No longer do you have to implement the Parcelable interface, the `writeToParcel()` or `createFromParcel()` or the `public static final CREATOR`.
You simply annotate a POJO with `@Parcel` and Parceler does the rest.
Because Parceler uses the Java JSR-269 Annotation Processor, there is no need to run a tool manually to generate the Parcelable code.
Just annotate your Java Bean, compile and you are finished.
By default, Parceler will serialize the fields of your instance directly:

[source,java]
----
@Parcel
public class Example {
    String name;
    int age;

    public Example() {}

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

Be careful not to use private fields when using the default field serialization strategy as it will incur a performance penalty due to reflection.

To use the generated code, you may reference the generated class directly, or via the `Parcels` utility class:

[source,java]
----
Parcelable wrapped = Parcels.wrap(new Example("Andy", 42));
----

To dereference the `@Parcel`, just call the `Parcels.unwrap()` method:

[source,java]
----
Example example = Parcels.unwrap(wrapped);
example.getName(); // Andy
example.getAge(); // 42
----

Of course, the wrapped `Parcelable` can be added to an Android Bundle to transfer from Activity to Activity:

[source,java]
----
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
----

And dereferenced in the `onCreate()` method:

[source,java]
----
Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
----

This wrapping and unwrapping technique plays well with the Intent Factory pattern.
In addition, Parceler is supported by the following libraries:

 * http://androidtransfuse.org/documentation.html#parcel[Transfuse] - Allows `@Parcel` annotated beans to be used with the `@Extra` injection.
 * https://github.com/MarcinMoskala/ActivityStarter/wiki/Parceler-Arg-Converter-usage[ActivityStarter] - Uses ParcelarArgConverter to allow to use Parceler objects as an arguments passed to Activities (Fragments, Services etc.).
 * https://github.com/sockeqwe/fragmentargs#argsbundler[FragmentArgs] - Uses the `ParcelerArgsBundler` adapter to wrap and unwrap `@Parcel` annotated beans with fragment parameters.
 * https://github.com/f2prateek/dart[Dart] - Autodetects `@Parcel` annotated beans and automatically unwraps them when using `@InjectExtra`.
 * http://androidannotations.org/[AndroidAnnotations] - Autodetects `@Parcel` annotated beans and https://github.com/excilys/androidannotations/wiki/ParcelerIntegration[automatically wraps/unwraps] them when using `@Extra`, `@FragmentArg`, `@InstanceState` and other `Bundle` related annotations.

=== Parcel attribute types
Only a select number of types may be used as attributes of a `@Parcel` class.
The following list includes the mapped types:

 * `byte`
 * `double`
 * `float`
 * `int`
 * `long`
 * `char`
 * `boolean`
 * `String`
 * `IBinder`
 * `Bundle`
 * `SparseArray` of any of the mapped types*
 * `SparseBooleanArray`
 * `ObservableField`
 * `List`, `ArrayList` and `LinkedList` of any of the mapped types*
 * `Map`, `HashMap`, `LinkedHashMap`, `SortedMap`, and `TreeMap` of any of the mapped types*
 * `Set`, `HashSet`, `SortedSet`, `TreeSet`, `LinkedHashSet` of any of the mapped types*
 * `Parcelable`
 * `Serializable`
 * Array of any of the mapped types
 * Any other class annotated with `@Parcel`

*Parcel will error if the generic parameter is not mapped.

Parceler also supports any of the above types directly.
This is especially useful when dealing with collections of classes annotated with `@Parcel`:

[source,java]
----
Parcelable listParcelable = Parcels.wrap(new ArrayList<Example>());
Parcelable mapParcelable = Parcels.wrap(new HashMap<String, Example>());
----

==== Polymorphism
Note that Parceler does not unwrap inheritance hierarchies, so any polymorphic fields will be unwrapped as instances of the base class.
This is because Parceler opts for performance rather than checking `.getClass()` for every piece of data.

[source,java]
----
@Parcel
public class Example {
    public Parent p;
    @ParcelConstructor Example(Parent p) { this.p = p; }
}

@Parcel public class Parent {}
@Parcel public class Child extends Parent {}
----

[source,java]
----
Example example = new Example(new Child());
System.out.println("%b", example.p instanceof Child); // true
example = Parcels.unwrap(Parcels.wrap(example));
System.out.println("%b", example.p instanceof Child); // false
----

Refer to the <<custom_serialization,Custom Serialization>> section for an example of working with polymorphic fields.

=== Serialization techniques

Parceler offers several choices for how to serialize and deserialize an object in addition to the field-based serialization seen above.

==== Getter/setter serialization
Parceler may be configured to serialize using getter and setter methods and a non-empty constructor.
In addition, fields, methods and constructor parameters may be associated using the `@ParcelProperty` annotation.
This supports a number of bean strategies including immutability and traditional getter/setter beans.

To configure default method serialization, simply configure the `@Parcel` annotation with `Serialization.BEAN`:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
----

To use a constructor with serialization, annotate the desired constructor with the `@ParcelConstructor` annotation:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private final String name;
    private final int age;

    @ParcelConstructor
    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

If an empty constructor is present, Parceler will use that constructor unless another constructor is annotated.

==== Mixing getters/setters and fields
You may also mix and match serialization techniques using the `@ParcelProperty` annotation.
In the following example, `firstName` and `lastName` are written to the bean using the constructor while `firstName` is read from the bean using the field and `lastName` is read using the `getLastName()` method.
The parameters `firstName` and `lastName` are coordinated by the parameter names `"first"` and `"last"` respectfully.

[source,java]
----
@Parcel
public class Example {
    @ParcelProperty("first")
    String firstName;
    String lastName;

    @ParcelConstructor
    public Example(@ParcelProperty("first") String firstName, @ParcelProperty("last") String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() { return firstName; }

    @ParcelProperty("last")
    public String getLastName() { return lastName; }
}
----

For attributes that should not be serialized with Parceler, the attribute field, getter or setter may be annotated by `@Transient`.

Parceler supports many different styles centering around the POJO.
This allows `@Parcel` annotated classes to be used with other POJO based libraries, including the following:

 * https://code.google.com/p/google-gson/[GSON]
 * https://realm.io/docs/java/latest/#parceler[Realm]
 * https://bitbucket.org/littlerobots/cupboard[Cupboard]
 * http://simple.sourceforge.net/[Simple XML]
 * https://github.com/Raizlabs/DBFlow[DBFlow]

==== Static Factory support
As an alternative to using a constructor directly, Parceler supports using an annotated Static Factory to build an instance of the given class.
This style supports Google's https://github.com/google/auto/tree/master/value[AutoValue] annotation processor / code generation library for generating immutable beans.
Parceler interfaces with AutoValue via the `@ParcelFactory` annotation, which maps a static factory method into the annotated `@Parcel` serialization:

[source,java]
----
@AutoValue
@Parcel
public abstract class AutoValueParcel {

    @ParcelProperty("value") public abstract String value();

    @ParcelFactory
    public static AutoValueParcel create(String value) {
        return new AutoValue_AutoValueParcel(value);
    }
}
----

AutoValue generates a different class than the annotated `@Parcel`, therefore, you need to specify which class Parceler should build in the `Parcels` utility class:

[source,java]
----
Parcelable wrappedAutoValue = Parcels.wrap(AutoValueParcel.class, AutoValueParcel.create("example"));
----
And to deserialize:
[source,java]
----
AutoValueParcel autoValueParcel = Parcels.unwrap(wrappedAutoValue);
----

==== Custom serialization
`@Parcel` includes an optional parameter to include a manual serializer `ParcelConverter` for the case where special serialization is necessary.
This provides a still cleaner option for using Parcelable classes than implementing them by hand.

The following code demonstrates using a `ParcelConverter` to unwrap the inheritance hierarchy during deserialization.

[source,java]
----
@Parcel
public class Item {
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    public List<Item> itemList;
}
@Parcel public class SubItem1 extends Item {}
@Parcel public class SubItem2 extends Item {}

public class ItemListParcelConverter implements ParcelConverter<List<Item>> {
    @Override
    public void toParcel(List<Item> input, Parcel parcel) {
        if (input == null) {
            parcel.writeInt(-1);
        }
        else {
            parcel.writeInt(input.size());
            for (Item item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

    @Override
    public List<Item> fromParcel(Parcel parcel) {
        int size = parcel.readInt();
        if (size < 0) return null;
        List<Item> items = new ArrayList<Item>();
        for (int i = 0; i < size; ++i) {
            items.add((Item) Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader())));
        }
        return items;
    }
}
----

Parceler is also packaged with a series of base classes to make Collection conversion easier located under the `org.parceler.converter` package of the api.
These base classes take care of a variety of difficult or verbose jobs dealing with Collections including null checks and collectin iteration.
For instance, the above `ParcelConverter` could be written using the `ArrayListParcelConverter':

[source,java]
----
public class ItemListParcelConverter extends ArrayListParcelConverter<Item> {
    @Override
    public void itemToParcel(Item item, Parcel parcel) {
        parcel.writeParcelable(Parcels.wrap(item), 0);
    }

    @Override
    public Item itemFromParcel(Parcel parcel) {
        return Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader()));
    }
}
----

=== Classes without Java source
For classes whose corresponding Java source is not available, one may include the class as a Parcel by using the `@ParcelClass` annotation.
This annotation may be declared anywhere in the compiled source that is convenient.
For instance, one could include the `@ParcelClass` along with the Android Application:

[source,java]
----
@ParcelClass(LibraryParcel.class)
public class AndroidApplication extends Application{
    //...
}
----

Multiple `@ParcelClass` annotations may be declared using the `@ParcelClasses` annotation.

In addition, classes referenced by `@ParcelClass` may be configured using the `@Parcel` annotation.
This allows the serialization configuration through any parameter available on the `@Parcel` annotation including the serialization technique or classes to analyze.

One useful technique is the ability to define global custom converters for a type:
[source,java]
----
@ParcelClass(
    value = LibraryParcel.class,
    annotation = @Parcel(converter = LibraryParcelConverter.class))
class SomeClass{}
----
This allows for fine grained control over a class that isn't available for direct modification.

=== Advanced configuration

==== Skipping analysis
It is a common practice for some libraries to require a bean to extend a base class.
Although it is not the most optimal case, Parceler supports this practice by allowing the configuration of what classes in the inheritance hierarchy to analyze via the analyze parameter:

[source, java]
----
@Parcel(analyze = {One.class, Three.class})
class One extends Two {}
class Two extends Three {}
class Three extends BaseClass {}
----

In this example, only fields of the `One` and `Three` classes will be serialized, avoiding both the `BaseClass` and `Two` class parameters.

==== Specific wrapping

The Parcels utility class looks up the given class for wrapping by class.
For performance reasons this ignores inheritance, both super and base classes.
There are two solutions to this problem.
First, one may specify additional types to associate to the given type via the `implementations` parameter:

[source, java]
----
class ExampleProxy extends Example {}
@Parcel(implementations = {ExampleProxy.class})
class Example {}

ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(proxy);  // ExampleProxy will be serialized as a Example
----

Second, one may also specify the class type when using the `Parcels.wrap()` method:

[source, java]
----
ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(Example.class, proxy);
----

==== Configuring Proguard

To configure Proguard, add the following lines to your proguard configuration file.  These will keep files related to the `Parcels` utilty class and the `Parcelable` `CREATOR` instance:

----
# Parceler library
-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }
----

== Getting Parceler

You may download Parceler as a Maven dependency:

[source,xml]
----
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler</artifactId>
    <version>{{site.currentVersion}}</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler-api</artifactId>
    <version>{{site.currentVersion}}</version>
</dependency>
----

or Gradle:
[source,groovy]
----
compile 'org.parceler:parceler-api:{{site.currentVersion}}'
annotationProcessor 'org.parceler:parceler:{{site.currentVersion}}'
----

Or from http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.parceler%22[Maven Central].

== License
----
Copyright 2011-2015 John Ericksen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----


updated anchor name

updated anchor name

---
layout: default
title: Parceler
documentationExpanded: false
postsExpanded: false
---

=== Introduction

In Android, http://developer.android.com/reference/android/os/Parcelable.html[Parcelables] are a great way to serialize Java Objects between Contexts.
http://www.developerphil.com/parcelable-vs-serializable/[Compared] with traditional Serialization, Parcelables take on the order of 10x less time to both serialize and deserialize.
There is a major flaw with Parcelables, however.
Parcelables contain a ton of boilerplate code.
To implement a Parcelable, you must mirror the `writeToParcel()` and `createFromParcel()` methods such that they read and write to the Parcel in the same order.
Also, a Parcelable must define a `public final static Parcelable.Creator CREATOR` in order for the Android infrastructure to be able to leverage the serialization code.

Parceler is a code generation library that generates the Android Parcelable boilerplate source code.
No longer do you have to implement the Parcelable interface, the `writeToParcel()` or `createFromParcel()` or the `public static final CREATOR`.
You simply annotate a POJO with `@Parcel` and Parceler does the rest.
Because Parceler uses the Java JSR-269 Annotation Processor, there is no need to run a tool manually to generate the Parcelable code.
Just annotate your Java Bean, compile and you are finished.
By default, Parceler will serialize the fields of your instance directly:

[source,java]
----
@Parcel
public class Example {
    String name;
    int age;

    public Example(){ /*Required empty bean constructor*/ }

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

Be careful not to use private fields when using the default field serialization strategy as it will incur a performance penalty due to reflection.

To use the generated code, you may reference the generated class directly, or via the `Parcels` utility class:

[source,java]
----
Parcelable wrapped = Parcels.wrap(new Example("Andy", 42));
----

To dereference the `@Parcel`, just call the `Parcels.unwrap()` method:

[source,java]
----
Example example = Parcels.unwrap(wrapped);
example.getName(); // Andy
example.getAge(); // 42
----

Of course, the wrapped `Parcelable` can be added to an Android Bundle to transfer from Activity to Activity:

[source,java]
----
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
----

And dereferenced in the `onCreate()` method:

[source,java]
----
Example example = Parcels.unwrap(this.getIntent().getExtras().get("example"));
----

This wrapping and unwrapping technique plays well with the Intent Factory pattern.
In addition, Parceler is supported by the following libraries:

 * http://androidtransfuse.org/documentation.html#parcel[Transfuse] - Allows `@Parcel` annotated beans to be used with the `@Extra` injection.
 * https://github.com/sockeqwe/fragmentargs#argsbundler[FragmentArgs] - Uses the `ParcelerArgsBundler` adapter to wrap and unwrap `@Parcel` annotated beans with fragment parameters.
 * https://github.com/f2prateek/dart[Dart] - Autodetects `@Parcel` annotated beans and automatically unwraps them when using `@InjectExtra`.

=== Parcel attribute types
Only a select number of types may be used as attributes of a `@Parcel` class.
The following list includes the mapped types:

 * `byte`
 * `double`
 * `float`
 * `int`
 * `long`
 * `char`
 * `boolean`
 * `String`
 * `IBinder`
 * `Bundle`
 * `SparseArray` of any of the mapped types*
 * `SparseBooleanArray`
 * `List`, `ArrayList` and `LinkedList` of any of the mapped types*
 * `Map`, `HashMap`, `LinkedHashMap`, `SortedMap`, and `TreeMap` of any of the mapped types*
 * `Set`, `HashSet`, `SortedSet`, `TreeSet`, `LinkedHashSet` of any of the mapped types*
 * `Parcelable`
 * `Serializable`
 * Array of any of the mapped types
 * Any other class annotated with `@Parcel`

*Parcel will error if the generic parameter is not mapped.

Parceler also supports any of the above types directly.
This is especially useful when dealing with collections of classes annotated with `@Parcel`:

[source,java]
----
Parcelable listParcelable = Parcels.wrap(new ArrayList<Example>());
Parcelable mapParcelable = Parcels.wrap(new HashMap<String, Example>());
----

==== Polymorphism
Note that Parceler does not unwrap inheritance hierarchies, so any polymorphic fields will be unwrapped as instances of the base class.
This is because Parceler opts for performance rather than checking `.getClass()` for every piece of data.

[source,java]
----
@Parcel
public class Example {
    public Parent p;
    Example(Parent p) { this.p = p; }
}

@Parcel public class Parent {}
@Parcel public class Child extends Parent {}
----

[source,java]
----
Example example = new Example(new Child());
System.out.println("%b", example.p instanceof Child); // true
example = Parcels.unwrap(Parcels.wrap(example));
System.out.println("%b", example.p instanceof Child); // false
----

Refer to the <<custom_serialization,Custom Serialization>> section for an example of working with polymorphic fields.

=== Serialization techniques

Parceler offers several choices for how to serialize and deserialize an object in addition to the field-based serialization seen above.

==== Getter/setter serialization
Parceler may be configured to serialize using getter and setter methods and a non-empty constructor.
In addition, fields, methods and constructor parameters may be associated using the `@ParcelProperty` annotation.
This supports a number of bean strategies including immutability and traditional getter/setter beans.

To configure default method serialization, simply configure the `@Parcel` annotation with `Serialization.BEAN`:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
----

To use a constructor with serialization, annotate the desired constructor with the `@ParcelConstructor` annotation:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private final String name;
    private final int age;

    @ParcelConstructor
    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

If an empty constructor is present, Parceler will use that constructor unless another constructor is annotated.

==== Mixing getters/setters and fields
You may also mix and match serialization techniques using the `@ParcelProperty` annotation.
In the following example, `firstName` and `lastName` are written to the bean using the constructor while `firstName` is read from the bean using the field and `lastName` is read using the `getLastName()` method.
The parameters `firstName` and `lastName` are coordinated by the parameter names `"first"` and `"last"` respectfully.

[source,java]
----
@Parcel
public class Example {
    @ParcelProperty("first")
    String firstName;
    String lastName;

    @ParcelConstructor
    public Example(@ParcelProperty("first") String firstName, @ParcelProperty("last") String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() { return firstName; }

    @ParcelProperty("last")
    public String getLastName() { return lastName; }
}
----

For attributes that should not be serialized with Parceler, the attribute field, getter or setter may be annotated by `@Transient`.

Parceler supports many different styles centering around the POJO.
This allows `@Parcel` annotated classes to be used with other POJO based libraries, including https://code.google.com/p/google-gson/[GSON], https://bitbucket.org/qbusict/cupboard[Cupboard], and http://simple.sourceforge.net/[Simple XML] to name a few.

==== Static Factory support
As an alternative to using a constructor directly, Parceler supports using an annotated Static Factory to build an instance of the given class.
This style supports Google's https://github.com/google/auto/tree/master/value[AutoValue] annoation processor / code generation library for generating immutable beans.
Parceler interfaces with AutoValue via the `@ParcelFactory` annotation, which maps a static factory method into the annotated `@Parcel` serialization:

[source,java]
----
@AutoValue
@Parcel
public abstract class AutoValueParcel {

    @ParcelProperty("value") public abstract String value();

    @ParcelFactory
    public static AutoValueParcel create(String value) {
        return new AutoValue_AutoValueParcel(value);
    }
}
----

AutoValue generates a different class than the annotated `@Parcel`, therefore, you need to specify which class Parceler should build in the `Parcels` utility class:

[source,java]
----
Parcelable wrappedAutoValue = Parcels.wrap(AutoValueParcel.class, AutoValueParcel.create("example"));
----
And to deserialize:
[source,java]
----
AutoValueParcel autoValueParcel = Parcels.unwrap(wrappedAutoValue);
----

==== Custom serialization
`@Parcel` includes an optional parameter to include a manual serializer `ParcelConverter` for the case where special serialization is necessary.
This provides a still cleaner option for using Parcelable classes than implementing them by hand.

The following code demonstrates using a `ParcelConverter` to unwrap the inheritance hierarchy during deserialization.

[source,java]
----
@Parcel
public class Item {
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    public List<Item> itemList;
}
@Parcel public class SubItem1 extends Item {}
@Parcel public class SubItem2 extends Item {}

public class ItemListParcelConverter implements ParcelConverter<List<Item>> {
    @Override
    public void toParcel(List<Item> input, Parcel parcel) {
        if (input == null) {
            parcel.writeInt(-1);
        }
        else {
            parcel.writeInt(input.size());
            for (Item item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

    @Override
    public List<Item> fromParcel(Parcel parcel) {
        int size = parcel.readInt();
        if (size < 0) return null;
        List<Item> items = new ArrayList<Item>();
        for (int i = 0; i < size; ++i) {
            items.add((Item) Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader())));
        }
        return items;
    }
}
----

=== Classes without Java source
For classes whose corresponding Java source is not available, one may include the class as a Parcel by using the `@ParcelClass` annotation.
This annotation may be declared anywhere in the compiled source that is convenient.
For instance, one could include the `@ParcelClass` along with the Android Application:

[source,java]
----
@ParcelClass(LibraryParcel.class)
public class AndroidApplication extends Application{
    //...
}
----

Multiple `@ParcelClass` annotations may be declared using the `@ParcelClasses` annotation.

=== Advanced configuration

==== Skipping analysis
It is a common practice for some libraries to require a bean to extend a base class.
Although it is not the most optimal case, Parceler supports this practice by allowing the configuration of what classes in the inheritance hierarchy to analyze via the analyze parameter:

[source, java]
----
@Parcel(analyze = {One.class, Three.class})
class One extends Two {}
class Two extends Three {}
class Three extends BaseClass {}
----

In this example, only fields of the `One` and `Three` classes will be serialized, avoiding both the `BaseClass` and `Two` class parameters.

==== Specific wrapping

The Parcels utility class looks up the given class for wrapping by class.
For performance reasons this ignores inheritance, both super and base classes.
There are two solutions to this problem.
First, one may specify additional types to associate to the given type via the `implementations` parameter:

[source, java]
----
class ExampleProxy extends Example {}
@Parcel(implementations = {ExampleProxy.class})
class Example {}

ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(proxy);  // ExampleProxy will be serialized as a Example
----

Second, one may also specify the class type when using the `Parcels.wrap()` method:

[source, java]
----
ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(Example.class, proxy);
----

==== Avoiding Parcels indexing

Using Parceler in libraries can be challenging because Parceler writes a single mapping class `Parceler$$Parcels` to associate a given type with a `Parcelable`.
This mapping class can collide giving the following error during compilation:

[source, bash]
----
Error Code:
    2
Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lorg/parceler/Parceler$$Parcels$1;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
        ....
----

To avoid writing this common mapping class, set `parcelsIndex = false` to each of the library classes.
Parceler will not write a `Parceler$$Parcels` mapping class if no indexable classes exist and the Parcels utiltiy class will fallback to looking up the generated class by name.

Alternatively, using `@ParcelClass` in the root project, instead of annotating classes directly in the library can avoid this issue.

==== Configuring Proguard

To configure Proguard, add the following lines to your proguard configuration file.  These will keep files related to the `Parcels` utilty class and the `Parcelable` `CREATOR` instance:

----
# Parcel library
-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-keep class org.parceler.Parceler$$Parcels
----

== Getting Parceler

You may download Parceler as a Maven dependency:

[source,xml]
----
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler</artifactId>
    <version>${parceler.version}</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler-api</artifactId>
    <version>${parceler.version}</version>
</dependency>
----

or Gradle:
[source,groovy]
----
compile "org.parceler:parceler-api:${parcelerVersion}"
apt "org.parceler:parceler:${parcelerVersion}"
----

Or from http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.parceler%22[Maven Central].

== License
----
Copyright 2011-2015 John Ericksen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----

---
layout: default
title: Parceler
documentationExpanded: false
postsExpanded: false
---

=== Introduction

In Android, http://developer.android.com/reference/android/os/Parcelable.html[Parcelables] are a great way to serialize Java Objects between Contexts.
http://www.developerphil.com/parcelable-vs-serializable/[Compared] with traditional Serialization, Parcelables take on the order of 10x less time to both serialize and deserialize.
There is a major flaw with Parcelables, however.
Parcelables contain a ton of boilerplate code.
To implement a Parcelable, you must mirror the `writeToParcel()` and `createFromParcel()` methods such that they read and write to the Parcel in the same order.
Also, a Parcelable must define a `public final static Parcelable.Creator CREATOR` in order for the Android infrastructure to be able to leverage the serialization code.

Parceler is a code generation library that generates the Android Parcelable boilerplate source code.
No longer do you have to implement the Parcelable interface, the `writeToParcel()` or `createFromParcel()` or the `public static final CREATOR`.
You simply annotate a POJO with `@Parcel` and Parceler does the rest.
Because Parceler uses the Java JSR-269 Annotation Processor, there is no need to run a tool manually to generate the Parcelable code.
Just annotate your Java Bean, compile and you are finished.
By default, Parceler will serialize the fields of your instance directly:

[source,java]
----
@Parcel
public class Example {
    String name;
    int age;

    public Example(){ /*Required empty bean constructor*/ }

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

Be careful not to use private fields when using the default field serialization strategy as it will incur a performance penalty due to reflection.

To use the generated code, you may reference the generated class directly, or via the `Parcels` utility class:

[source,java]
----
Parcelable wrapped = Parcels.wrap(new Example("Andy", 42));
----

To dereference the `@Parcel`, just call the `Parcels.unwrap()` method:

[source,java]
----
Example example = Parcels.unwrap(wrapped);
example.getName(); // Andy
example.getAge(); // 42
----

Of course, the wrapped `Parcelable` can be added to an Android Bundle to transfer from Activity to Activity:

[source,java]
----
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
----

And dereferenced in the `onCreate()` method:

[source,java]
----
Example example = Parcels.unwrap(this.getIntent().getExtras().get("example"));
----

This wrapping and unwrapping technique plays well with the Intent Factory pattern.
In addition, Parceler is supported by the following libraries:

 * http://androidtransfuse.org/documentation.html#parcel[Transfuse] - Allows `@Parcel` annotated beans to be used with the `@Extra` injection.
 * https://github.com/sockeqwe/fragmentargs#argsbundler[FragmentArgs] - Uses the `ParcelerArgsBundler` adapter to wrap and unwrap `@Parcel` annotated beans with fragment parameters.
 * https://github.com/f2prateek/dart[Dart] - Autodetects `@Parcel` annotated beans and automatically unwraps them when using `@InjectExtra`.

=== Parcel attribute types
Only a select number of types may be used as attributes of a `@Parcel` class.
The following list includes the mapped types:

 * `byte`
 * `double`
 * `float`
 * `int`
 * `long`
 * `char`
 * `boolean`
 * `String`
 * `IBinder`
 * `Bundle`
 * `SparseArray` of any of the mapped types*
 * `SparseBooleanArray`
 * `List`, `ArrayList` and `LinkedList` of any of the mapped types*
 * `Map`, `HashMap`, `LinkedHashMap`, `SortedMap`, and `TreeMap` of any of the mapped types*
 * `Set`, `HashSet`, `SortedSet`, `TreeSet`, `LinkedHashSet` of any of the mapped types*
 * `Parcelable`
 * `Serializable`
 * Array of any of the mapped types
 * Any other class annotated with `@Parcel`

*Parcel will error if the generic parameter is not mapped.

Parceler also supports any of the above types directly.
This is especially useful when dealing with collections of classes annotated with `@Parcel`:

[source,java]
----
Parcelable listParcelable = Parcels.wrap(new ArrayList<Example>());
Parcelable mapParcelable = Parcels.wrap(new HashMap<String, Example>());
----

==== Polymorphism
Note that Parceler does not unwrap inheritance hierarchies, so any polymorphic fields will be unwrapped as instances of the base class.
This is because Parceler opts for performance rather than checking `.getClass()` for every piece of data.

[source,java]
----
@Parcel
public class Example {
    public Parent p;
    Example(Parent p) { this.p = p; }
}

@Parcel public class Parent {}
@Parcel public class Child extends Parent {}
----

[source,java]
----
Example example = new Example(new Child());
System.out.println("%b", example.p instanceof Child); // true
example = Parcels.unwrap(Parcels.wrap(example));
System.out.println("%b", example.p instanceof Child); // false
----

Refer to the <<custom-serialization,Custom Serialization>> section for an example of working with polymorphic fields.

=== Serialization techniques

Parceler offers several choices for how to serialize and deserialize an object in addition to the field-based serialization seen above.

==== Getter/setter serialization
Parceler may be configured to serialize using getter and setter methods and a non-empty constructor.
In addition, fields, methods and constructor parameters may be associated using the `@ParcelProperty` annotation.
This supports a number of bean strategies including immutability and traditional getter/setter beans.

To configure default method serialization, simply configure the `@Parcel` annotation with `Serialization.BEAN`:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private String name;
    private int age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}
----

To use a constructor with serialization, annotate the desired constructor with the `@ParcelConstructor` annotation:

[source,java]
----
@Parcel(Serialization.BEAN)
public class Example {
    private final String name;
    private final int age;

    @ParcelConstructor
    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
----

If an empty constructor is present, Parceler will use that constructor unless another constructor is annotated.

==== Mixing getters/setters and fields
You may also mix and match serialization techniques using the `@ParcelProperty` annotation.
In the following example, `firstName` and `lastName` are written to the bean using the constructor while `firstName` is read from the bean using the field and `lastName` is read using the `getLastName()` method.
The parameters `firstName` and `lastName` are coordinated by the parameter names `"first"` and `"last"` respectfully.

[source,java]
----
@Parcel
public class Example {
    @ParcelProperty("first")
    String firstName;
    String lastName;

    @ParcelConstructor
    public Example(@ParcelProperty("first") String firstName, @ParcelProperty("last") String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() { return firstName; }

    @ParcelProperty("last")
    public String getLastName() { return lastName; }
}
----

For attributes that should not be serialized with Parceler, the attribute field, getter or setter may be annotated by `@Transient`.

Parceler supports many different styles centering around the POJO.
This allows `@Parcel` annotated classes to be used with other POJO based libraries, including https://code.google.com/p/google-gson/[GSON], https://bitbucket.org/qbusict/cupboard[Cupboard], and http://simple.sourceforge.net/[Simple XML] to name a few.

==== Static Factory support
As an alternative to using a constructor directly, Parceler supports using an annotated Static Factory to build an instance of the given class.
This style supports Google's https://github.com/google/auto/tree/master/value[AutoValue] annoation processor / code generation library for generating immutable beans.
Parceler interfaces with AutoValue via the `@ParcelFactory` annotation, which maps a static factory method into the annotated `@Parcel` serialization:

[source,java]
----
@AutoValue
@Parcel
public abstract class AutoValueParcel {

    @ParcelProperty("value") public abstract String value();

    @ParcelFactory
    public static AutoValueParcel create(String value) {
        return new AutoValue_AutoValueParcel(value);
    }
}
----

AutoValue generates a different class than the annotated `@Parcel`, therefore, you need to specify which class Parceler should build in the `Parcels` utility class:

[source,java]
----
Parcelable wrappedAutoValue = Parcels.wrap(AutoValueParcel.class, AutoValueParcel.create("example"));
----
And to deserialize:
[source,java]
----
AutoValueParcel autoValueParcel = Parcels.unwrap(wrappedAutoValue);
----

==== Custom serialization
`@Parcel` includes an optional parameter to include a manual serializer `ParcelConverter` for the case where special serialization is necessary.
This provides a still cleaner option for using Parcelable classes than implementing them by hand.

The following code demonstrates using a `ParcelConverter` to unwrap the inheritance hierarchy during deserialization.

[source,java]
----
@Parcel
public class Item {
    @ParcelPropertyConverter(ItemListParcelConverter.class)
    public List<Item> itemList;
}
@Parcel public class SubItem1 extends Item {}
@Parcel public class SubItem2 extends Item {}

public class ItemListParcelConverter implements ParcelConverter<List<Item>> {
    @Override
    public void toParcel(List<Item> input, Parcel parcel) {
        if (input == null) {
            parcel.writeInt(-1);
        }
        else {
            parcel.writeInt(input.size());
            for (Item item : input) {
                parcel.writeParcelable(Parcels.wrap(item), 0);
            }
        }
    }

    @Override
    public List<Item> fromParcel(Parcel parcel) {
        int size = parcel.readInt();
        if (size < 0) return null;
        List<Item> items = new ArrayList<Item>();
        for (int i = 0; i < size; ++i) {
            items.add((Item) Parcels.unwrap(parcel.readParcelable(Item.class.getClassLoader())));
        }
        return items;
    }
}
----

=== Classes without Java source
For classes whose corresponding Java source is not available, one may include the class as a Parcel by using the `@ParcelClass` annotation.
This annotation may be declared anywhere in the compiled source that is convenient.
For instance, one could include the `@ParcelClass` along with the Android Application:

[source,java]
----
@ParcelClass(LibraryParcel.class)
public class AndroidApplication extends Application{
    //...
}
----

Multiple `@ParcelClass` annotations may be declared using the `@ParcelClasses` annotation.

=== Advanced configuration

==== Skipping analysis
It is a common practice for some libraries to require a bean to extend a base class.
Although it is not the most optimal case, Parceler supports this practice by allowing the configuration of what classes in the inheritance hierarchy to analyze via the analyze parameter:

[source, java]
----
@Parcel(analyze = {One.class, Three.class})
class One extends Two {}
class Two extends Three {}
class Three extends BaseClass {}
----

In this example, only fields of the `One` and `Three` classes will be serialized, avoiding both the `BaseClass` and `Two` class parameters.

==== Specific wrapping

The Parcels utility class looks up the given class for wrapping by class.
For performance reasons this ignores inheritance, both super and base classes.
There are two solutions to this problem.
First, one may specify additional types to associate to the given type via the `implementations` parameter:

[source, java]
----
class ExampleProxy extends Example {}
@Parcel(implementations = {ExampleProxy.class})
class Example {}

ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(proxy);  // ExampleProxy will be serialized as a Example
----

Second, one may also specify the class type when using the `Parcels.wrap()` method:

[source, java]
----
ExampleProxy proxy = new ExampleProxy();
Parcels.wrap(Example.class, proxy);
----

==== Avoiding Parcels indexing

Using Parceler in libraries can be challenging because Parceler writes a single mapping class `Parceler$$Parcels` to associate a given type with a `Parcelable`.
This mapping class can collide giving the following error during compilation:

[source, bash]
----
Error Code:
    2
Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lorg/parceler/Parceler$$Parcels$1;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
        ....
----

To avoid writing this common mapping class, set `parcelsIndex = false` to each of the library classes.
Parceler will not write a `Parceler$$Parcels` mapping class if no indexable classes exist and the Parcels utiltiy class will fallback to looking up the generated class by name.

Alternatively, using `@ParcelClass` in the root project, instead of annotating classes directly in the library can avoid this issue.

==== Configuring Proguard

To configure Proguard, add the following lines to your proguard configuration file.  These will keep files related to the `Parcels` utilty class and the `Parcelable` `CREATOR` instance:

----
# Parcel library
-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-keep class org.parceler.Parceler$$Parcels
----

== Getting Parceler

You may download Parceler as a Maven dependency:

[source,xml]
----
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler</artifactId>
    <version>${parceler.version}</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.parceler</groupId>
    <artifactId>parceler-api</artifactId>
    <version>${parceler.version}</version>
</dependency>
----

or Gradle:
[source,groovy]
----
compile "org.parceler:parceler-api:${parcelerVersion}"
apt "org.parceler:parceler:${parcelerVersion}"
----

Or from http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.parceler%22[Maven Central].

== License
----
Copyright 2011-2015 John Ericksen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----