Saturday, December 29, 2012

Netbeans-Like Distribution with Maven

When it comes to creating standalone Java applications, out of the box maven projects are not easy to distribute, they don't have configured some default main class (or some convention), dependencies are not specified on the manifest and also dependency jars are not packaged even near the final jar file.

On the other hand, if you have used Netbeans IDE to create standalone Java apps, you can notice that upon any build, the default Netbeans ant build script places a "dist" folder inside your project with the following structure:

This folder is the distribution of your app and you may simply run it with the java -jar command line.

Even though Maven projects have a lot of advantages, I personally miss how handy it is this structure for distribution; so I managed to make this happen with maven and it's assembly plugin.

Building the Distribution Structure

In order to create the desired distribution, I started with maven's jar-with-dependencies predefined assembly and customized it to look like the following:

What this does is the following:

  • It compresses the whole distribution into a nice zip file inside the target directory.
  • The first dependency set is there to copy the application jar on the root of the distribution, I added the none scope to make sure that no other dependencies are copied there.
  • The second dependency set is to copy all dependencies and transitive dependencies into the lib folder.
Now this takes care of the packaging but there is still some work to do, so we need to edit our project's pom.xml file and add the following configurations:

First of all, I've changed the final name of the archive to be short and sweet. Next, I've configured the assembly plugin to point to the right configuration file. Finally I've configured the jar plugin to set in the MANIFEST.MF file the main class and the jars that should be included on the classpath. Please note that you should alter the mainClass configuration to match you main class.

After this, we can create our distribution by simply running:
$ mvn clean package assembly:single

You should find a zip file called like your artifact's ID-dist.zip, which you can nicely share and it's easily run.

Sunday, October 7, 2012

Enterprise Integration with Mule ESB

Why Enterprise Integration?

Beginning on the 90's, having a computer information system is a must for any company; even small drugstores have their own information system; also, starting from the 2000's, having a website is a must for most companies. Nowadays there are lots of online businesses and companies who own a huge ecosystem of applications, websites and third party systems.

In this scenario, one thing naturally emerged: information and business processes is fragmented!

Building a completely new application to mitigate this fragmentation is not practical on most cases so, what should a company do?

The answer is quite simple, something there must be on the middle whether people or software and there is where enterprise integration comes into play.

There is on the Java world also a number of enterprise middleware vendors, some are Mule ESB and Apache Camel and today I'll try to demonstrate how to use the first one which is the one I know better.

Mule ESB

Mule is an open source enterprise service bus which aims to be powerful and simple at the same time. It is very configurable and rather complex integrations can be achieved in a matter of hours.

In order to use Mule ESB, the developer has two main options: It can be used as an application container (with deployment based on archives) or embedded inside a java application.

Every Mule ESB application consists of an XML file which combines a number of built-in building blocks to perform a specific integration task, this task has the name of "flow".

Mule also provides some visual tooling, an IDE based on Eclipse, called "Mule Studio" which greatly helps the developer, to create, package and deploy Mule applications, specially it has visual tooling to create interfaces making the learning curve really flat.

A Sample Mule Application 

In order to explain further, let's take a look at a simple Mule Application, this application takes requests from http, logs some information, sends information through JMS and inserts records into a database. Any java developer knows that this task may take a couple of hours, but with Mule, this can be done in a matter of minutes. Here is how this application looks in Mule Studio:


Here we have defined a flow (integration), an application may have many flows; the first building block is an HTTP endpoint (called http inbound endpoint) and through the arrows travels a message (actually an instance of MuleMessage). This message contains headers and a payload (also other things such as attachments and other information), with each building block we'll be manipulating or extracting information from it.

I'll not cover in depth the concept of the message but is enough to say that this concept is key for understanding the tool. As an example, imagine a HTTP request, it has headers and a request body, the inbound endpoint will create a mule message with these request headers as the message headers and the request body as the payload. Now, for example, to send the message through JMS, the JMS outbound endpoint would create a JMS message with the Mule message headers as headers and the payload as the JMS payload.

The sample application looks on it's XML form like the following:

The first thing to note is the presence of connectors, these can be seen as a global configuration elements for each transport (in this case JMS and JDBC).

Next we can see the definition of the flow in which we just log the message; set the payload to be a hash map created out of the request query string; send this to an ActiveMQ broker; insert an audit record and finally build a generic JSON response, as you can see a lot is going on for so few configuration lines!

Mule ESB provides out of the box support for several transports such as HTTP, FTP, SMTP, IMAP, SOAP, REST, JMS, JDBC, etc and also ready-to-go clients (called cloud connectors) for popular cloud applications such as Facebook, Twitter, Salesforce and many more.

This completes this short introduction of this tool which is definitely worth looking into when it comes the time for integrating two or more applications.

Monday, August 27, 2012

Apache CXF Working with Spring

These days I have been playing with Apache CXF, which is great open source java-based library for creating both SOAP and REST web services. CXF is a great library, specially if you are using the Spring Framework and despite the outdated and inaccurate documentation, I managed to make it work and here is how to do it.

I have assembled a sample project which is on my GitHub repository.

A Small Introduction


CXF is designed with a very flexible architecture based on interceptors, this architecture allows the developer to make CXF work with different types of front end technologies such as JAX-WS, JAX-RS, CORBA and more!

CXF is also very friendly with the Spring framework so it is (or at least should be) very easy to integrate in this kind of applications.

Working with Maven

CXF artifacts are published on the central maven repository, so first of all, you need to add the dependencies into your project:


<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>${cxf.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>${cxf.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>${cxf.version}</version>
</dependency>

At the moment of writing this post CXF latest version is 2.6.2. Also you need to include dependencies for the Spring Framework, please refer to the sample project for these.

Spring Configuration

To start with this little how to, I created a service class with has mixed JAX-WS and JAX-RS annotations. This makes easy to export the same functionality as SOAP and REST web services:


@WebService
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface MyWebService {

    @WebMethod
    String doSomeWork(String work);
    
    
    public String beRestful(String name);
    
    
    @WebMethod
    public ArrayList<Customer> findCustomers(CustomerRequest request);
}

And the implementation:


@WebService
public class MyWebServiceImpl implements MyWebService {
    
    @WebMethod
    @Override
    public String doSomeWork(String work) {
        return "Doing some work with this: "+work;
    }
    
    
    @Override
    @GET @Path("/beRestful") @Produces("text/plain") //REST Annotations
    @WebMethod //SOAP Annotations
    public String beRestful(@QueryParam("name") String name) {
        return "Your name is: "+name;
    }
    
    
    @WebMethod
    public ArrayList<Customer> findCustomers(CustomerRequest request) {
        
        
        ArrayList<Customer> ret = new ArrayList<Customer>();
        
        Customer customer = new Customer();
        
        customer.setCustomerName(request.getName());
        customer.setMembershipLevel(request.getMembershipLevel());
        customer.setCustomerSince(new Date());
        
        ret.add(customer);
        
        return ret;
    }
    
}


The Customer and CustomerRequest classes are pretty simple and therefore not shown here, please refer to the sample project for the source code.

These exposes three methods through SOAP and one through REST, CXF has its own XML namespaces for JAX-WS and JAX-RS, the header of the applicationContext.xml file looks like the following:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd/spring-spring-context-3.1.xsd-3.1.2.RELEASE.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
          http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
          http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
">


CXF also has its own configuration files included inside the JAR files, even though these files look empty, the documentation suggests to include them so here are the lines for it:


    <!-- import cxf webservices -->
    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

Finally, we need to declare the bean we just created as a Spring Bean and reference it in a SOAP and a REST endpoint:


    <jaxws:endpoint 
        id="mywebservice" 
        implementor="#webserviceImpl" 
        address="/myws" />
    
    
    <jaxrs:server id="myrestservice" address="/rest">
        <jaxrs:serviceBeans>
            <ref bean="webserviceImpl" />
        </jaxrs:serviceBeans>
    </jaxrs:server>
    
    <bean id="webserviceImpl" class="com.juancavallotti.cxfdemo.MyWebServiceImpl" /> 

The last ingredient is configuring the CXF servlet in our web.xml file.

Configuration of web.xml

The configuration of this file is pretty standard, first I have declared the CXF servlet and map it to the /ws/* URL pattern, and then I just declared the standard listeners for the Spring Framework to work on a web environment.


    <!-- the cxf servlet -->
    <servlet>
        <servlet-name>cxfservlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>cxfservlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>
    
    <!-- spring context and request listeners -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

Running the example


After following these steps we are ready to run the example application, if you have forked or cloned the sample application just run: $ mvn tomcat:run command line and after the startup, point the browser to: http://localhost:8080/CxfDemo/ws, you should see a very simple webpage that informs the webservices running on the CXF servlet and links to the WSDL and the WADL:


Conclusions

CXF is a very powerful and complete framework for exposing services as web services, I think it is the natural choice if you want to enable web services in your spring application. Be aware that you will find outdated documentation and be sure to read the documents about the architecture before planning to reverse-engineer the framework or else you'll find the task rather frustrating.


Sunday, July 15, 2012

Concurrency Tests with JUnit

Sometimes in the life of a programmer, a concurrency test is needed to check if a given framework function doesn't break the data when used simultaneously by different threads.

JUnit provides some sense of AOP by using the @Rule annotation which allows us to modify how a given test runs. I was trying to create these kind of tests for my DTO framework (jDTO Binder) and inspired by this blog post, I created a test rule that allows the programmer to specify the number of threads to run a given test case and collect some little statistics about the running time of the test.

First of all I created an implementation of TestRule.


The previous gist may be used by anyone who would like to create concurrency tests and dont care that much about the execution exceptions but rather the overall results of the tests.

The code does the following:

  1. Create a ThreadPoolExecutor with the size of the tests, you may use other executor implementation if you wish so.
  2. Create a CountdownLatch to make sure all the tests start almost at the same time.
  3. Create a CountdownLatch to block the test thread until all tests finish.
  4. Add all the required tasks to the executor, which will wait until all all have been scheduled.
  5. If some test fails, then a flag will be set to true.
  6. Log the execution time.
  7. Fail the test if some of the threads had an exception.
So at this point we're ready to use the rule on a simple concurrency test:


And as simple as that we have a concurrency test with some statistics on the running time.

Tuesday, June 19, 2012

Websockets on Tomcat 7

Recently I discovered Tomcat 7 supports websockets, I looked at the support and found it quite easy to use.

I have created a very simple websocket servlet that echoes the input from the user, first of all you need to create a class that extends from WebSocketServlet, then, for every subprotocol you want to handle, you need to create a subclass of the abstract MessageInbound. There you may choose to answer to text or binary messages, here is the source:


Now we can connect to the websocket from our javascript client code:


And as simple as that we have our web sockets working for our java application deployed on Tomcat 7.

Sunday, May 20, 2012

Wicket 1.5 + Spring Framework + Hibernate + jDTO Binder Sample Application

In this post I'll go through a sample project I've created to demonstrate jDTO Binder in action with some of the most popular frameworks on the Java world. The sample project is publicly available on GitHub.

To get the project running without too much fuss, then just checkout the project, open it on netbeans 7.1.2 and hit run :)

If you're on linux or mac os X then you can do something like this:

$ git clone git://github.com/jDTOBinder/jdto-sample-projects.git
$ cd jdto-sample-projects/jdto-wicket-demo/
$ mvn clean tomcat:run

After that you may point your browser to http://localhost:8080/jdto-wicket-demo/ and that's it, you should see something like this:


The CSS3 Highlights:

The styling is pretty standard styling what can be kind of uncommon is the menu box which is rotated and it has a little shadow, also some google web fonts are being used, let's go with the easiest first, the shadow:

box-shadow: 6px 6px 5px #888;

The parameters mean in order, the horizontal distance, the vertical distance the blur distance and the shadow color.

Also you can see that the box is kind of rotated let's say 8 degrees to the left? Normally that would have been defined by using the transform property, but it seems that is still not that supported in all browsers, so I have added three rules to support webkit, mozilla and internet explorer 9:

-webkit-transform:rotate(-8deg);
-moz-transform:rotate(-8deg);
-ms-transform: rotate(-8deg);

Finally, to include some web fonts, some import statements must be added:

/* import the google web font  */
@import url(http://fonts.googleapis.com/css?family=Averia+Libre:700);
@import url(http://fonts.googleapis.com/css?family=Oxygen);

That enabled me to use the "Averia Libre" and "Oxygen" fonts on my styles.

The Wicket Highlights

Apache Wicket is a really nice web framework that you can use to build everything in Java, from websites to web applications, there are some things that may be uncommon for some developers, I've used the wicket:link tag to include css resources packaged on the classpath:

<head>
    <title>jDTO Binder Pizza Orders!</title>
    <wicket:link>
        <link rel="stylesheet" type="text/css" href="jdtopizzas.css" />
    </wicket:link>
</head>

Normally one would have had that css resource included on the java code but this wicket magic makes it more intuitive and consistent.

Another use of the tag is to link between pages, as I show in the following example:

<p>Take a look at the <wicket:link><a href="ViewOrdersPage.html">orders you have already created</a></wicket:link>.</p>

In this case, I have a ViewOrdersPage.java file and by creating the link this way, wicket takes care of pointing the href to the right place without adding extra Java code.

DTOs as the Wicket Models

Wicket extensively uses "intermediate" objects to act as the model of it components this is where DTOs come in handy, since you can modify the data they carry without affecting the data on the database, they are perfect for using them as the components model. The following code shows how you bind a wicket form with the "form" that takes the service to create a new pizza order:

PizzaOrderForm form = new PizzaOrderForm();
form.setPizzas(new ArrayList<PizzaDTO>());

//create the order form.
orderForm = new Form<PizzaOrderForm>(
        "orderForm",
        new CompoundPropertyModel<PizzaOrderForm>(form));

//for the case you want to add pizzas and you have already filled the form elements.
//this is only necessary because I left out the menu list from the form.
orderForm.add(new TextField("customerName").add(new BlurAjaxFormSubmitBehavior()));
orderForm.add(new TextField("customerPhone").add(new BlurAjaxFormSubmitBehavior()));
orderForm.add(new TextField("customerAddress").add(new BlurAjaxFormSubmitBehavior()));

With the use of CompoundPropertyModel things are really easy. I've added a behavior that submits the form data every time the field losses focus, this prevents unwanted data erasing on the client side. (Also I could have designed my page a little better hehe).

Spring and Hibernate Highlights

As this is a sample application but is intended to show real-life stuff, it uses spring framework and hibernate, but if you had to install and configure a database server to test the application, you probably wouldn't test it, so here is how I've used the H2 embedded database engine to use just your computers memory a little bit more:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:mem:pizza"/>
</bean>

As you can see, the database connection pool has the url "jdbc:h2:mem:pizza" and that is all what it takes to tell H2 that you don't want to persist anything.

Finally, I've used a singleton bean to load the sample data when the application starts, this bean loads the list of available products.

<!-- initial data loader bean -->
<bean id="initialDataLoader" class="org.jdto.demo.InitialDataLoader" />

class InitialDataLoader {
    
    private static final Logger logger = LoggerFactory.getLogger(InitialDataLoader.class);
    
    @Autowired
    private HibernateTemplate template;
    
    @PostConstruct
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    private void init() {
        createPizzas();
    }

    private void createPizzas() {
        logger.info("Creating initial set of pizzas!");
        
        Pizza pepperoni = new Pizza("Pepperoni Pizza", 4, 8.50);
        Pizza mozzarella = new Pizza("Mozzarella Pizza", 3, 7.50);
        Pizza special = new Pizza("Special Ham Pizza", 5, 10.0);
        Pizza onion = new Pizza("Onion Pizza", 4, 9.0);
        Pizza anchovy = new Pizza("Anchovy Pizza", 2, 7.95);
        
        template.save(pepperoni);
        template.save(mozzarella);
        template.save(special);
        template.save(onion);
        template.save(anchovy);
    }
}

One of the beauties of Spring is that you can use package-scoped classes as beans so you don't expose them to the team developers (and they don't feel tempted to use them).

Since this bean will be executed on startup time we will need a brand new transaction, so I've set the propagation attribute to "requires new".

jDTO Binder Highlights

In this application, jDTO Binder takes care of copying data between domain objects and DTO objects, how it's being used is described on the project's README file.


That would be all for now, please feel free to make comments on the post and I hope you find it useful for starting a new project with this great technologies.

Sunday, March 25, 2012

Java architecture with DTOs

The DTO Discussion

The DTO (Data transfer objects) pattern is really useful if you intend to achieve a clean separation between the service layer and the presentation layer of the application. DTOs are part of the service layer API and therefore something that is best to have than not to.

DTOs also serve another purpose: Adapt model values, which in most cases are normalized, to view-friendly values, which most of the time presents particular values from an object graph and also calculated values.

Very often, applying the DTO pattern in a given architecture is not an easy task, you earn an application easy to maintain  by spending a lot of time (shallow) copying data from one object to another.

One solution for the data copy problem can be found by using a framework, in this case jDTO Binder. jDTO Binder makes easy for the programmer to achieve some tasks:


  • Receive form values and copy them to target business objects.
  • Create lists with data from particular properties of an object graph.
  • Add to those lists calculated values.
  • Change the format of the data to be more appropriate for display or network transmission.
I've taken the time to create a sample maven project with a very popular setup: Spring Web MVC, Spring Framework and Hibernate. Although you can use this project as a starting point to build a web application with this technologies, this project incorporates jDTO Binder into its ecosystem and demonstrates how it makes your life a lot easier.

To run the project, just unzip the file, open the terminal and type the following commands:

$ cd <path to the unzipped folder>
$ mvn clean install tomcat:run

Project Description and Walkthrough.


Required Skills: To go through this project, basic Spring Web MVC knowledge is required. Even though the important part is written on the service layer, Spring MVC and Spring Context knowledge helps a lot to put all the pieces together.

The DTOs

The following snippets shows the DTOs this project uses and its purpose:

public class PizzaDTO implements Serializable {
    
    @Source("id")
    private Long pizzaId;
    
    
    @Sources(value={@Source("pizzaName"), 
        @Source("price")}, merger=StringFormatMerger.class, mergerParam="%s ($ %.2f)")
    private String description;
    
    private double price;
    private int rating;
    ...
}


The first DTO to analyze is the PizzaDTO, this one is intended to serve in a listing of available pizzas. It has a description attribute which is intended for display and is created from the pizza name and the pizza price in a formatted string.

public class PizzaOrderForm implements Serializable {
    
    @NotEmpty //validation annotation
    @Source("whoOrderedName")
    private String customerName;
    
    @NotEmpty //validation
    @Source("contactNumber")
    private String customerPhone;
    
    @NotEmpty //validation
    private String customerAddress;
    
    @Size(min=1) //validation
    @DTOTransient
    private List<PizzaDTO> pizzas;
    ...
}

The second DTO is really the model of a form to take a pizza order, it does not only have DTO binding annotations but also standard JSR 303 bean validation annotations so the data can be validated automatically.

public class OrderDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private Long id;
    
    @Source("whoOrderedName")
    private String customerName;
    
    private String customerAddress;
    
    @Source("contactNumber")
    private String customerPhone;
    
    @Source(value="orderDate", merger=DateFormatMerger.class, mergerParam="MM/dd/yyyy hh:mm")
    private String orderDate;
    
    @Source(value="pizzas", merger=SumMerger.class, mergerParam="price")
    private Double orderPrice;
    ...
}

Next on the line is a DTO intended for a list of pizza orders, it contains most of the data the pizza order has but also it calculates the price of each order so you don't have to do it manually or save the amount in an extra field on your database table.

The Service Class

Now we've got to the interesting part, how the service layer takes advantage of these DTOs to make your life easier. The following is the declaration of the PizzaOrderService, I'll show separately the implementation methods so I can give a little more explanation of each without having you to scroll up and down repeatedly :).

@Service
@Transactional
class PizzaOrderServiceImpl implements PizzaOrderService, Serializable {

    private static final long serialVersionUID = 1L;
    @Autowired
    private HibernateTemplate hibernate;
    @Autowired
    private DTOBinder binder;
    @Autowired
    private Validator validator;
    
    ... //implementation goes here
}


This is a normal service class, it is transactional because it interacts with hibernate, it has injected an instance of the very helpful class HibernateTemplate, also has injected an instance of the DTOBinder (which is configured as a spring bean in applicationContext.xml), finally the JSR 303 standard bean validator to perform validations on objects (also declared as a spring bean).

This class is serializable because it may be serialized for example in a web session.

    @Override
    public List<PizzaDTO> listAvailablePizzas() {

        DetachedCriteria criteria = DetachedCriteria.forClass(Pizza.class);
        criteria.addOrder(Order.asc("pizzaName"));

        return binder.bindFromBusinessObjectList(PizzaDTO.class, hibernate.findByCriteria(criteria));
    }

This method queries the database for pizzas, and returns the list as a list of PizzaDTO by taking advantage of the DTO Binder. Please note that if we hadn't used the DTO framework, we would have had to iterate over the list returned by hibernate template and build the DTO instances ourselves by setting and formatting the values; all is taken care by the framework.

    @Override
    public boolean placeOrder(PizzaOrderForm form) {

        //may validate with hibernate validator
        if (!validator.validate(form).isEmpty()) {
            return false;
        }

        PizzaOrder order = binder.extractFromDto(PizzaOrder.class, form);


        order.setOrderDate(new Date());
        order.setPizzas(new ArrayList<Pizza>());

        for (PizzaDTO pizzaDTO : form.getPizzas()) {
            Pizza pizza = hibernate.get(Pizza.class, pizzaDTO.getPizzaId());
            order.getPizzas().add(pizza);
        }

        hibernate.save(order);

        return true;
    }

This method may look familiar to you if you had to build functionality for adding data to a database in the past :). In this case we get a PizzaOrderForm as a parameter, use the validation framework to check the data, extract the form values into a proper business object using de DTO framework, set data that was not inputted, relate the order with the actual pizzas and finally persist the order!

That's a lot for the few lines of code we've written! If we hadn't had use the DTO framework, then we would have had to manually copy each property of the form into the appropriate property of the business object, which can take several more lines.

    @Override
    public List<OrderDTO> listOrders() {
        DetachedCriteria criteria = DetachedCriteria.forClass(PizzaOrder.class);
        criteria.addOrder(Order.desc("orderDate"));

        return binder.bindFromBusinessObjectList(OrderDTO.class, hibernate.findByCriteria(criteria));
    }

The last method is much the same as the first one so no further discussion is needed.

A couple of final words.

As we may have noticed, this architecture is rather simple but full featured. It uses data validation, transactional behavior and the code is kept really small and clean thanks to the DTO Binding framework.

When used the right way, DTOs are a very powerful tool and makes our application even more bullet-proof by isolating completely the database code (persistent objects included) from the presentation tier.

Another thing to note is that, if you need to change from where data is acquired, add or remove fields is just a matter of configuring the DTO object and nothing else! Compare this to the traditional approach in which you would have added the extra field and then going through each loop when you populated the DTO and add the extra data copy operation.

Saturday, March 10, 2012

Web Based VS Native - Mobile Application Development

I think one of the biggest challenges of mobile application development is supporting an acceptable number of devices, which have different screen sizes (and generally speaking hardware abilities), which can be a real problem because developers need to build multiple versions of the application, say one per device they want to support. The question is: is there any way around this?

Well, some would say, "just build the thing web-based", of course, this has some advantages (at first sight at least) you code it in javascript with HTML 5 and it theoretically will run on most of the devices since most of them have webkit-based web engines!  This approach has proven on the past to work really well for desktop environments, so let's listen to the story of an embedded-web app development.

The story of a mobile web development.
Say we start building the app with this approach. For now everything is working fine, we spent 3 or 4 days just coding plain html and javascript with one framework like Sencha touch or jQuery Mobile and it runs fine on the device (say iphone) emulator, then we spent 4 to 6 days coding a data layer using local storage or web SQL and finally a couple more of days testing on a real device. 

Well, let's try it on the Android emulator.... "DANG! those animations were supposed to work!, and also why the layout is so off? And this looks like an iOS app, my android users won't dig that!

After going through the first experience you realize, you need a theme engine!! and switch the theme for each device... also it would be nice to add some code to adapt the components layout for each screen size and done! after 4 more days of writing javascript your app works fine on the iphone and android, now what? My friend has a blackberry!! Well, a couple more days to build the blackberry theme...

And the story could go on and on while testing on tablets of different brands and screen sizes, but finally... why the app is so slow?? it leaves me without enough battery to make phone calls!

Well finally we wrote just one application that works (awful) on every device, and also we as developers had to deal with thinks like there's no javascript debugger on the device emulators.

The story of a native mobile app development.
After going through the mobile experience we decided to give native application development a try, so started eclipse with the Android plugin and created the user interface with the visual designer, after a couple of hours we have the same 10 screens our web app used to have, with android user experience, ok, we found we have frameworks for data storage so after two days of work we have the same app running.

Ok, now let's bring the iPhone version! We create an Xcode project, after a couple of hours we have the iPhone and iPad user interface, then by taking advantage of the data APIs build the business logic and done!, the app is ready to test on the new platform.

Same story goes for blackberry, and other mobile platforms, now we take a look at the apps, they're working fine but oh no!! we have the same codebase all over the place, in different programming languages and development environments! That's not good for sure.

Time for comparison.
After telling the two stories we had a not-so-happy ending for each. So we need to choose now!! What should we do for our mobile apps.

Well It depends of a few things: manly development costs, delivery time constraints and importance of the user experience, so let's take a look of each point for both platforms.

Development Costs.

On the one hand for a web development you need a web developer with basic knowledge of each platform on the native side, this is because even though embedded web applications are mostly wrote on javascript, you need to build and embedded app environment (or use something like PhoneGap which entails the same basic knowledge), also you need the native development environment to build and package the embedded app environment for each platform. 

On the other hand you need an application developer who has medium to advanced skills on building native mobile applications and also the same native development environments. 

Adding features to the application is relatively simple for embedded web applications while adding features to native applications would take to over and over add the same thing for each platform codebase. We can think here that since the user experiences and the capabilities of mobile devices are different, adding a feature would also be an easy thing for native but complex for web.

Another important thing is tooling, web applications have somehow basic tooling while native applications have very powerful tooling and also the ability to debug and profile the code.

So in my opinion, at the end od the day, the cost is greater for embedded web apps than native web apps even considering that the codebase is repeated.

Delivery Timing.

As the year 2012, people has a lot of experience writing web applications, we have a lot of frameworks and tools to write these things, but most of this is by taking advantage of powerful servers and helping the developers on not writing HTML and CSS, because writing HTML and CSS is a slow process! They're not meant for creating user interfaces but for creating documents, so we made a lot of things to manage achieving the look and feel of user interfaces. Even though frameworks like Sencha Touch or jQuery mobile makes creating the user interfaces rather simple, you still have the three to four days time to create a 10 screens app, and then lots of time and hacks to make it look native for each platform.

With the availability of developer tooling, native applications can be built very quickly, the pitfall is having to deal with lots of programming languages, a not-so-skilled developer could find writing code on different programming languages a hard task, but let's face it, data-driven mobile apps actually entails caching data locally and sending it to (or reading from) a server, with some documentation and examples the logic should be done in a couple of days.

So speaking of time, for web apps, you could have say three developers working on the same codebase, but truth is, the more developers are working on the same codebase the more they get into each others way.

If you have three targeted platforms and three developers you can start the development for each platform at the same time and see it code-complete in 4 to 6 days.

So in my opinion, at the end of the day, you can make delivery rather quicker if you pick native development since the tooling is better and you can have people working independently, with proper project management all the platforms will be finished mostly at the same time.

User Experience.

Finally, the user experience, every platform has its own user experience, meaning for touch gestures, ways of navigating through screens and so on, for example android apps have a back button and a home button which removes the need for applications to provide a "software" navigation button, iOS phones doesn't have this button but all the applications have the same set of ways for navigating.

Also widget layout, colors, sizes and icon meanings are different, also you may have to provide localization and so on. This on an embedded web app will take lots of lines of javascript, and the more lines of javascript you write, the more battery you consume which is also a really bad thing for user experience.

Finally, HTML user interfaces need to be parsed, and rendered by a relatively slow processor so the user would notice some degree of unresponsiveness while interacting with the application.

Native apps doesn't have this advantages, they are built for each platform and for that, you just build the user experience the platform has and later you don't need to adapt it for another platform (maybe only phone/tablet adjustments), so they run fast, very responsive and with low battery consumption.

Conclusion

At this point I hope you're more than convinced that creating embedded web apps for different mobile devices has only the advantage of one single codebase, which is also a drawback because on different platforms things are different. Taking the approach of creating unified user experiences will result on confusing the user and making him to learn new things while he only wants to get the task done; this only works for a little set of apps that has really well-known user interface interactions (like facebook).

In my opinion, building native apps is way better than building embedded web apps, specially thinking on the user experience.

It would be really nice to have a serious scientific study for this, but at least for me, I'm a lot more skilled for web development than native development and with all that, it takes me a lot less time to build the same app native than web based.

Thursday, January 5, 2012

jDTO Binder 0.7 Released

I'm proud to announce the release of version 0.7 of jDTO Binder, the java framework to populate DTO objects easily.

This release includes the latest bugfixes and two new features:

Default configuration file.

The jDTO framework has the "convention over configuration" philosophy and therefore a new convention was introduced: If there is a package resource called jdto-mappings.xml on the default package, then it will use that configuration file instead of the annotations config, so now, if you're using CDI, you have the option to map your DTOs using an XML configuration file.

Read / Write Maps

The framework has gained the ability to read and write maps, so now implementations of the java.util.Map interface can be used to populate DTO's and can be populated out of objects.

The following code snippets demonstrates how to use this feature.

Map from object:

SimpleEntity entity = new SimpleEntity("myString", 23, 34.45, true);

HashMap<String, Object> map = binder.extractFromDto(HashMap.class, entity);


String strVal = (String) map.get("aString");
int intVal = (Integer) map.get("anInt");
double doubleVal = (Double) map.get("aDouble");
boolean boolVal = (Boolean) map.get("aBoolean");

Object from map:

HashMap<String, String> values = new HashMap<String, String>();

values.put("myString", "simpleString");
values.put("related.aString", "relatedString");

SimpleAssociationDTO dto = binder.bindFromBusinessObject(SimpleAssociationDTO.class, values);

These new features enables the users of the framework to explore new posibilites for example populating objects from properties files in a really elegant way.