Android, Java

Failed to find target android-18… D’oh!

One of the first problems I’ve found on my Android adventure is to configure the environment. Although there are lots of tutorials and IDEs to do it for me, I’ve decided to start building my “toys” with the newest building tool, Gradle (http://www.gradle.org).

The first impressions with gradle were good, however once I started to configure the project as Android application, a strange issue started to appear in my console, an error telling me that the compiler failed to find the target android:

My Computer:project-dir user$ gradle assemble

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':mobile-app:packageDebug'.
> failed to find target android-18

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.56 secs

This started to happen once I introduced the android plugin in the gradle config file:

apply plugin: 'android'

android {
compileSdkVersion 18
buildToolsVersion "18.0.0"
}

dependencies {...}

So, after googling a bit, I discovered that the problem was that I wasn’t pointing to the sdk version I had installed, so I opened /adt/sdk/tools/android:

android_sdk_manager

And, change the buildToolsVersion with the installed version:

apply plugin: 'android'

android {
compileSdkVersion 19
buildToolsVersion "19.0.3”
}

dependencies {...}

Once I did this everything started to work fine. Easy, simple and… obvious, d’oh!

Advertisements
Standard
Java

JSF + Primefaces 4 + Spring 4 + Hibernate 4 + Maven Multi-module = JTemplate

Introduction

In the last days I’ve been working on a Java project template. After reading some inspiring articles, I’ve decided to mix up some of the concepts explained on them with other nice features which they don’t cover, and adding some improvements.

The basics

The idea is to present how to structure a Java multi-module project using maven. So, the project is divided into the following parts:

  • main: It contains the main files to build the application, the “Parent” pom
  • persistence: The module with the data access components
  • common: The inter-module common parts will go here. E.g.- Parsers, Utility classes, etc
  • business: Models the business logic of our application
  • web: Where the views and the webapp structure will be modeled

Moreover, the project code will be configured with as much annotations as possible, for two reasons, avoid to locate the configuration files in deeply hidden places, and to take advantage of the compliance of Spring and Hibernate with the JSR-330 and JSR-317, respectively.

Multi-module with Maven

The project uses the multi-module feature provided by Maven. It is defined in a “Parent” pom file which is located into the main project, and as we’ll see later it has to be located into the root directory (where all the projects are located). The parent looks like:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<groupId>com.mm.jtemplate</groupId>
<artifactId>jtemplate</artifactId>
<version>0.1-SNAPSHOT</version>

<modules>
<module>jtemplate-main</module>
<module>jtemplate-common</module>
<module>jtemplate-persist</module>
<module>jtemplate-module</module>
<module>jtemplate-web</module>
</modules>

<properties>
<spring.version>4.0.0.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- Log4j library -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>

<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.7</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>tomcat</server>
<path>/jtemplate</path>
</configuration>
</plugin>
</plugins>
<finalName>jtemplate</finalName>
</build>
</project>

The file is structured in two blocks, the first one is used to identify the modules. The second block refers to the dependencies and the needed configuration stuff to construct the project.

How-to build

There is only one required step to be done before building the project with maven normally, copy the “Parent” pom from the main project to the root directory:


cp ./main-module/parentPom.xml ./pom.xml

After this step is done, the project can be build normally with the common maven command:


mvn clean install

And, after a few seconds everything has to be build and on fire!

The components

Entity


package com.mm.model.domain;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@javax.persistence.Entity(name="Entity")
public class Entity {

 @Id
 @GeneratedValue
 @Column(name="id")
 private int id;
 @Column(name="attribute")
 private String attribute;

 public Entity(){}

 public Entity(int id, String attribute) {
 super();
 this.id = id;
 this.attribute = attribute;
 }

 public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 public String getAttribute() {
 return attribute;
 }
 public void setAttribute(String attribute) {
 this.attribute = attribute;
 }
}

EntityDAO


package com.mm.model.dao.impl;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.mm.model.dao.IEntityDAO;
import com.mm.model.domain.Entity;

@Named
public class EntityDAO implements IEntityDAO {
 @Inject
 private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
 return sessionFactory;
 }

public void setSessionFactory(SessionFactory sessionFactory) {
 this.sessionFactory = sessionFactory;
 }

public void addEntity(Entity entity) {
 Session session = getSessionFactory().getCurrentSession();
 Transaction trans = session.beginTransaction();
 session.save(entity);
 trans.commit();
 }

public void deleteEntity(Entity entity) {
 Session session = getSessionFactory().getCurrentSession();
 Transaction trans = session.beginTransaction();
 session.delete(entity);
 trans.commit();
 }

public void updateEntity(Entity entity) {
 Session session = getSessionFactory().getCurrentSession();
 Transaction trans = session.beginTransaction();
 session.update(entity);
 trans.commit();
 }

public Entity getEntity(int id) {
 Session session = getSessionFactory().getCurrentSession();
 Transaction trans = session.beginTransaction();

 List<?> list = session
 .createQuery("from Entity where id=?").setParameter(0, id)
 .list();

 trans.commit();
 return (Entity) list.get(0);
 }

public List<Entity> getEntities() {
 Session session = getSessionFactory().getCurrentSession();
 Transaction trans = session.beginTransaction();

 @SuppressWarnings("unchecked")
 List<Entity> list = (List<Entity>) session.createQuery("from Entity").list();

 trans.commit();
 return list;
 }

}

EntityService


package com.mm.module.one.impl;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.transaction.annotation.Transactional;

import com.mm.model.dao.IEntityDAO;
import com.mm.model.domain.Entity;
import com.mm.module.one.IEntityService;

@Named
@Transactional(readOnly = true)
public class EntityService implements IEntityService {

@Inject
 IEntityDAO entityDAO;

@Transactional(readOnly = false)
 public void addEntity(Entity entity) {
 getEntityDAO().addEntity(entity);
 }

@Transactional(readOnly = false)
 public void deleteEntity(Entity entity) {
 getEntityDAO().deleteEntity(entity);
 }

@Transactional(readOnly = false)
 public void updateEntity(Entity entity) {
 getEntityDAO().updateEntity(entity);
 }

public Entity getEntityById(int id) {
 return getEntityDAO().getEntity(id);
 }

public List<Entity> getEntitys() {
 return getEntityDAO().getEntities();
 }

public IEntityDAO getEntityDAO() {
 return entityDAO;
 }

public void setEntityDAO(IEntityDAO entityDAO) {
 this.entityDAO = entityDAO;
 }
}

EntityBBean


package com.mm.web.bbean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;

import com.mm.model.domain.Entity;
import com.mm.module.one.IEntityService;

@Named("entityBBean")
@Scope("session")
public class EntityBBean implements Serializable {

 private static final long serialVersionUID = 1L;

@Inject
 private IEntityService entityService;

 private int id;
 private String attribute;
 private List<Entity> entityList;

public void addEntity() {
 try {
 Entity entity = new Entity();
 entity.setId(getId());
 entity.setAttribute(getAttribute());
 getEntityService().addEntity(entity);
 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Added!", "Message: "));

 } catch (DataAccessException e) {
 e.printStackTrace();
 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "D'oh!", "Message: "));
 }

 }

public void reset() {
 this.setId(0);
 this.setAttribute("");
 }

public List<Entity> getEntityList() {
 entityList = new ArrayList<Entity>();
 entityList.addAll(getEntityService().getEntitys());
 return entityList;
 }

public IEntityService getEntityService() {
 return entityService;
 }

public void setEntityService(IEntityService entityService) {
 this.entityService = entityService;
 }

public void setEntityList(List<Entity> entityList) {
 this.entityList = entityList;
 }

public int getId() {
 return id;
 }

public void setId(int id) {
 this.id = id;
 }

public String getAttribute() {
 return attribute;
 }

 public void setAttribute(String attribute) {
 this.attribute = attribute;
 }
 }

index.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">

<h:head>

<title>Welcome to JTemplate</title>

</h:head>

<h:body>

<p:messages></p:messages>

<h:form>

<table>

<tr>

<td><h:outputLabel for="id" value="Id : " /></td>

<td><p:inputText id="id" value="#{entityBBean.id}"

disabled="true">

<f:converter converterId="javax.faces.Integer" />

<p:ajax event="blur" update="idMsg" />

</p:inputText> <p:message id="idMsg" for="id" display="icon" /></td>

</tr>

<tr>

<td><h:outputLabel for="attribute" value="Attribute : " /></td>

<td><p:inputText id="attribute"

value="#{entityBBean.attribute}">

<f:validateLength minimum="5" />

<p:ajax event="blur" update="attributeMsg" />

</p:inputText> <p:message id="attributeMsg" for="attribute" display="icon" /></td>

</tr>

<tr>

<td><p:commandButton id="addUser" value="Add"

actionListener="#{entityBBean.addEntity}" ajax="false" /></td>

<td><p:commandButton id="reset" value="Reset"

actionListener="#{entityBBean.reset}" ajax="false" /></td>

</tr>

</table>

&nbsp;

Elements:

&nbsp;

<p:dataTable id="entities" var="entity" value="#{entityBBean.entityList}"

style="width: 10%">

<p:column>

<f:facet name="header">

<h:outputText value="ID" />

</f:facet>

<h:outputText value="#{entity.id}" />

</p:column>

<p:column>

<f:facet name="header">

<h:outputText value="Name" />

</f:facet>

<h:outputText value="#{entity.attribute}" />

</p:column>

</p:dataTable>

</h:form>

&nbsp;

</h:body>

</html>

Where is the code?

Feel free to fork the code from https://github.com/miquelmillan/jtemplate

References

http://www.javacodegeeks.com/2012/04/jsf-2-primefaces-3-spring-3-hibernate-4.html

http://www.mkyong.com/maven/how-to-create-a-web-application-project-with-maven/

http://www.mkyong.com/maven/how-to-deploy-maven-based-war-file-to-tomcat/

http://books.sonatype.com/mvnex-book/reference/multimodule.html

– https://jcp.org/en/jsr/detail?id=330

https://jcp.org/en/jsr/detail?id=317

Standard
Hibernate, Java

Hibernate Named Queries and non-mapped objects… sweetness!

Introduction

One of the main goals of Hibernate ORM is to recover data from database. In the normal behaviour, It is conceived to map the entities of our database to objects in our domain. However, in some cases this is not the desired behaviour. For example, in case we want to recover a set of concrete columns from some tables using Named Queries (NQ).

The Hibernate Named Queries are a powerful mechanism to have our queries specified in Strings or even in XML files (in my opinion, the best solution). Such queries can be written in HQL (Hibernate Query Language) or SQL. In the case we use. As a first option probably we’ll use HQL, which maps directly the results to our domain objects. This feature is as powerful that will cover our requirements in the most of our cases.

However, sometimes we’ll need some specific utilities of our DBMS, like special functions, search hints, etc. In such case we can use SQL queries. With SQL queries we’ll have the flexibility (and sometimes the problem) to write totally customized queries, however, we lose the possibility to map the results directly to our domain objects (not really true, as we’ll see later).

Hibernate HQL-NQ and non-domain objects

Sometimes, for performance reasons or simply because we don’t need all the data, we’ll need to recover only some specific values of some tables. However, if such information is located in different tables we’ll have to join that data, and recover it following one of the following strategies:

1.- Recover it as an array, where each element of the array maps to one of the columns recovered. Bad solution, as we lose the semantics of each column, and we have to do extra job in our code.

2.- Encapsulate the columns in a DTO. “The solution”, as we won’t lose the semantics, we won’t have to do extra job and the recovered objects can go directly to our business layers, without having any data-adaptation algorithm.

To do the solution, we have to follow the next steps. Let’s suppose we have a DTO called ExampleDTO with 2 attributes id and desc. Our model has a table called Entity with 6 columns id, desc, name, cre_date, mod_date, exp_date.

In our DAO we’ll have a method like the following:

//Search method
public List findByNamedQuery(String q, Map<String,Object> params) throws Exception {
 //gimme a session
 Session session =HibernateUtil.currentSession(user);
 List result = null;
 try {
    Query qu = session.getNamedQuery(q);
    if (qu.getNamedParameters().length != params.size()){
       throw new HibernateException("Parameters needed");
    }

    for (String param: params.keySet()){
       qu.setParameter(param, params.get(param));
    }
 result = qu.list();
 } catch (Exception e){
    throw e;
 }
 return result;
}

And in the NQ’s file (supposing we have the NQ in one separated file), a query like the following:

<query name="findEntitiesById">
   SELECT new org.my.example.exampleDTO(ent.id, ent.description)
   FROM Entity ent
   WHERE ent.id = :id
   ORDER BY ent.id ASC
</query>

Hibernate SQL-NQ and non-domain objects

The solution exposed in the former section is practical, simple and clean, but it has a clear problem, it only can be used with HQL. In the case that SQL is needed, we need to apply a simple trick in our DAO code, like the following:

public List findByNamedQuery(String q, Map<String,Object> params, Class clazz ) throws Exception {
   //gimme a session
   Session session =HibernateUtil.currentSession();
   List result = null;
   try {
      Query qu = session.getNamedQuery(q);
      if (qu.getNamedParameters().length != params.size()){
         throw new HibernateException("Parameters needed");
      }
      for (String param: params.keySet()){
         qu.setParameter(param, params.get(param));
      }
      resultat = qu.setResultTransformer(Transformers.aliasToBean(clazz)).list();
   } catch (Exception e){
      throw e;
   }
   return result;
}

The query in our SQL queries file will look like this:

<sql-query name="findEntitiesByIdUsingSQL">
<return-scalar column="id" type="string"/>
<return-scalar column="desc" type="string"/>
   SELECT ent.id AS id, ent.desc AS desc
   FROM DDBB_ENTITY ent
   WHERE ent.id = :id
   ORDER BY ent.id ASC
</sql-query>

The main difference is in our DAO method. In this case we have to pass to it the class in which we want to encapsulate the data. Doing this Hibernate will automatically assign to each new register the values obtained using a Result Transformer. It is very important to make sure that the columns in our query, and the attributes of our returning DTO have the same name, otherwise our code won’t work.

Conclusion

In conclusion, with Hibernate and “a pair of tricks” present in its API, it’s possible to interact and use both SQL and HQL queries, and the most important point, without treating them with very different code.

Standard
Java

Warning!! Bootstrap classpath lost in combat

I’m not really sure, but from JVM version 7, when you’re compiling with legacy code or simply you’re a everything-must-be-under-control person who uses the flag “-source” of the javac:

% javac -source 1.6 MyClass.java

you get with the following compilation warning:

warning: [options] bootstrap class path not set in conjunction with -source 1.6

As the javac doc explains , this happens because the compiler will use the old language rules in combination with the new bootstrap classes, which can result in class files that do not work on the older platform (in this case, Java SE 6) because reference to non-existent methods can get included. This behaviour can end in some kind of programmer-crazyness, so the documentation gives us a simple solution, the usage of the bootclasspath and extdirs params:

% javac -source 1.6 -target 1.6 -bootclasspath jdk1.6.0/lib/rt.jar \ -extdirs "" MyClass.java

With this, the compiler uses the correct bootstrap classes, and it does not warning us about strange mixes of compiled versions.

References:

Javac doc: http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.html#crosscomp-example

Standard