ActiveJPA – Active Record Pattern for JPA

http://www.infoq.com/articles/ActiveJPA

ActiveJPA is a Java implementation of Martin Fowler’s Active Record pattern over JPA. It wraps around JPA and provides useful abstractions to simplify data access. With ActiveJPA, models themselves act as a DAO and interact with the database without you having to write any additional code for the DAL.

Read more here

Tech talk on Minnal Framework

I’m doing a tech talk on Minnal – RESTful Service Framework at the Bangalore Open Java Users Group (BOJUG) meetup in Bangalore on 26th Jan 2014.

If you are interested in attending the event, please RSVP here

Date/Time: 26th Jan 2014, 11:30 AM
Venue: Ebay
8th Floor, Tower 11,
Pritech Park SEZ,
Eco Space Campus,
RMZ Ecospace Internal Rd,
Adarsh Palm Retreat,
Bellandur,
Bangalore

Minnal now has Travis CI integration

Minnal builds are now running on travis ci. Every checkin to minnal now triggers a build on Travis and is tested against multiple JDKs (OpenJDK 7, OpenJDK 6, Oracle JDK 7).

The build status is now published in the github project page.

Authorizing your APIs in minnal

The latest version of minnal has support for authorizing your API’s using annotations as well as via route definition. To use the authorization support, you will have to include minnal-security in your pom.xml file.

Below is a sample code to set up auth permissions for routes via the route definition,

public class OrderApplication extends Application {
    @Override<a href="http://minnal.github.io/minnal/manual/instrumentation.html#authorizing-routes" title="Security Annotations" target="_blank"></a>
    protected void defineRoutes() {
        resource(OrderResource.class).builder("/hello").action(HttpMethod.GET,    "helloWorld").attribute(Authorizer.PERMISSIONS, "permission1,permission2");
    }
}

The same can be achieved through annotations using the minnal-instrumentation module,

@AggregateRoot
@Entity
@Table(name="Orders")
@SecureMultiple({
@Secure(method=Method.POST, permissions="CREATE_ORDER"),
@Secure(method=Method.PUT, permissions="EDIT_ORDER")
})
public class Order extends Model {

   @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
   @JoinColumn(name="orderId")
   @JsonManagedReference
   @Secure(method=Method.DELETE, permissions="DELETE_ITEM")
   private Set orderItems = new HashSet();

   @Action(value="cancel")
   @Secure(method=Method.PUT, permissions="CANCEL_ORDER")
   public void cancel(String reason) {
      setStatus(Status.cancelled);
      setCancellationReason(reason);
   }
}

Detailed usage documentation can be found here and here

minnal 1.0.2 is released

Just released version 1.0.2 of minnal. This includes two crucial enhancements,

  • Auto generate routes for your domain operations
  • Globally accessible application context

Click here to view the release notes. To know more about minnal, click here

Auto generate routes for your domain operations

You can now generate routes for your domain operations using the annotation @Action. A method marked with this annotation will automatically show up in the routes. This annotation is applicable only for domain models annotated with @AggregateRoot. Below snippet shows sample usage,


// This method will expose the route /orders/{order_id}/cancel
// Your payload should be a json structure with keys mapping to the name of the method arguments
// In this scenario the payload would be {"reason": "some cancellation reason"}
// Minnal will automatically call this method with the reason taken from payload
@Action(value="cancel")
public void cancel(String reason) {
setStatus(Status.cancelled);
setCancellationReason(reason);
}

// This method will expose the route /orders/{order_id}/order_items/{order_item_id}/cancel
// Your payload should be a json structure with keys mapping to the name of the method arguments
// In this scenario the payload would be {"reason": "some cancellation reason"}
// Minnal will automatically call this method with the reason taken from payload
@Action(value="cancel", path="orderItems")
public void cancelOrderItem(OrderItem orderItem, String reason) {
orderItem.cancel(reason);
}

Globally accessible application context

Minnal now allows configurations to be accessible from any where in the request flow. ApplicationContext will give you access to the configurations specific to the current request like RouteConfiguration, ResourceConfiguration and ApplicationConfiguration. Below is the sample usage,


ApplicationContext.instance().getApplicationConfiguration();
ApplicationContext.instance().getResourceConfiguration();
ApplicationContext.instance().getRouteConfiguration();

Auto-populating your pojos

I have been looking for FactoryGirl equivalent for Java but couldn’t find any. There are a couple of libraries created on the paths of FactoryGirl but requires us to setup test data to populate the beans. I particularly found Podam to be good enough in terms of populating the pojos automatically, but it lacked extensibility. I tried contributing to podam but some of my requirements were not in alignment with the podam’s roadmap. So decided to create my own library Autopojo for auto populating the java classes.

Autopojo is release under Apache License, Verson 2.0 and is used by minnal-generator module to auto generate test cases for the APIs generated by minnal

Introducing Minnal – Building RESTful services at ease

http://minnal.github.io/minnal

Minnal is a highly scalable and productive REST framework that helps you eliminate boiler plate code and build applications faster. It allows you to build restful applications at lightning speed through its powerful instrumentation module. It generates the API’s for your resources at runtime and eliminates the need to write controller and data access layers for your application leaving you to concentrate on enriching your domain. Minnal is extremely powerful for applications that are mostly CRUD centric but doesn’t restrict you from using it for business interfaces as well.

Our initial analysis suggest that development effort will considerably reduce by 20-30% (we are still evaluating by doing pocs with different case points).

Minnal is currently released as beta for community testing. Would really appreciate if you could spend some time on the framework and suggest enhancements / report bugs.

Introducing ActiveJpa

Follow up to my previous post on building restful services at ease, I have created a library ActiveJpa that is aimed at avoiding the need to create a layer for DAL. It does so by integrating the data access piece with the models. ActiveJpa attempts to implement the active record pattern on top of JPA to allow operations like ActiveRecord library in ruby.

Visit http://github.com/ActiveJpa/activejpa for samples and usage.

Some sample operations that you can do with ActiveJpa,

    // Get order by id
    Order order = Order.findById(12345L);

    // Get all orders for a customer that are shipped
    List<Order> orders = Order.where("customer_email", "dummyemail@dummy.com", "status", "shipped");

    // Get all orders for the product category 'books' and paginate it
    Filter filter = new Filter();
    filter.setPageNo(1);
    filter.setPerPage(25);
    filter.addCondition(new Condition("orderItems.product.category", Operator.eq, "books");
    List<Order> orders = Order.where(filter);

    // Count of orders matching the filter
    Long count = Order.count(filter);

    // Get the first order matching the filter
    Long count = Order.first("customer_email", "dummyemail@dummy.com", "status", "shipped");

    // Get the unique order matching the conditions
    Long count = Order.one("customer_email", "dummyemail@dummy.com", "status", "shipped");

    // Dump everything
    List<Order> orders = Order.all();

    // Delete all orders matching the filter
    Long count = Order.deleteAll(filter);

    // Check if order exists with the given identifier
    boolean exists = Order.exists(1234L);

    // Save order
    order.setBillingAmount(1000.0);
    order.persist();

    // Delete order
    order.delete();

    // Update attributes
    Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("billingAmount", 1000.0);
    order.updateAttributes(attributes);

    // Find order item by id within an order
    order.collections("order_items").findById(123L);

    // Search order items by filter with an order
    order.collections("order_items").findById(filter);

RESTful services at ease

In one of my current projects at Flipkart, I’m working on breaking a huge monolithic system to numerous micro services to boost the scale and performance of the system. Most of these services will be exposing simple CRUD and few business operations over a REST interface. There are very good frameworks (dropwizard, RestExpress, etc.) available in the OS community that I could choose from. But in simple CRUD services, you will end up writing lots of boiler plate code irrespective of the framework that you choose from the above. You still have to write a controller that talks to the service/repository classes to fetch/update the data. I have been thinking,

  • What if the framework can create the boiler plate code for me?
  • What if I just need to write the domain and the framework doing the rest?
  • What other ways can a framework simplify not writing boiler plate code?

There is lomok that helps avoiding boiler plate code, APT can help you generate the boiler plate code at compile time, javaagents can help you instrument classes at runtime and generate the boiler plate code for us. Why not use the power of these and simplify building REST services?

Project ‘minnal’ attempts to explore these options and will be yet another addition to the REST frameworks in Java.

Watch out this space for updates on ‘minnal’

Video Post of Distributed Transactions in SOA

Distributed Transactions in SOA – Flipkart Slashn – Developer’s conference

%d bloggers like this: