Sunday, September 26, 2010

Developing a GWT Hosted on AppEngine

GWT

Using Eclipse with Google plugin:
  • to run application  locally: Google->Compile GWT (red toolbox toolbar icon) and run as Run As->Web Application

Thursday, May 20, 2010

Wednesday, May 19, 2010

Flex with Cairngorm 2 - Popups Strategy

This post is a brief summary how we use Cairngorm 2 methodology for popups in Flex applications in the IT shop I work at:

  • Three files are created for each popup:
    • popup view
    • Cairngorm event to initiate showing of the popup
    • Cairngorm command to actually show the popup using PopupManager
  • Any data that needs to be passed to the popup is attached to the event.
  • When user closes the popup, the popup view simply removes itself from PopupManager.
  • The results of the popup, if any, are updated (can be done via data binding) in the ModelLocator, to which other controlls are bound as well, if needed.

Wednesday, May 12, 2010

Options for Java Middle-Tier of an RIA Application

Choice of Standard/Framework
Here's my best option or two for each area:
  • Persistence:

    • JPA. Use implementation-specific annotations only where unavoidable, and mark them in a way that will allow you to find all of them easily.
     
  • Transaction Management: EJB 3.1
  • Dependency Injection: EJB 3.1
  • Security: EJB 3.1
  • Exposing required web services:EJB 3.1
  • AOP: EJB 3.1 if their support for AOP is sufficient for you. Otherwise: Spring
  • Other:

    • Singletons: EJB 3.1
Providers
  • JPA: I use Hibernate, but the whole advantage of JPA is, that which provider you use is much less important than it used to be.
  • Application Server: Glassfish 3. It does support EJB 3.1.

Wednesday, April 28, 2010

Flex 3 and Flex 4 - Tips

  • When manually dispatching an event, using uiComponent.dispatchEvent(your-event), you need to add listener to the same component uiComponent. So, uiComponent.addEventListener(type,handler) will work, but uiAnyOtherComponent.addEventListener(type,handler) will not work.
  • The state changes-related transition effects have to correspond to the type of changes between the corresponding states.
    Example: I had a vertical group with two components. In State 1, both components show. In State2, Comp1 is not included. I set a Resize transition for Comp1 and a Move transition for Comp2. The effect was surprising: when state changed, Comp1 disappeared and appeared at the bottom of the screen. There it was re-sized. The right fix was to change Comp1: instead of includeIn=State1, I did height.State2=0. That did the trick.
  • Constraint-based layout is supported only in a container with BasicLayout. If you want to use it inside a VGroup, for example, you can put it inside a Group for which you don't specify any layout (BasicLayout is the default).

    Thursday, April 22, 2010

    Installing Samsung Printer ML-2510 on a Network Server under Win7

    • Go to: Control Panel > Hardware and Sound > Devices and Printers.
    • Click "Add a Printer" and in a new window: Click "Add a local printer".
    • Select "Create a new port" via radio buttons. Select "Standard TCP/IP Port" via dropdown. Click "Next".
    • Enter "192.168.0.2"  or whatever is your print server IP address via textbox "Hostname or IP Address". Modify "192.168.0.102" via textbox "Port Name" if desired. Unselect "Query the printer [...]" via checkbox.
    • Select custom settings and set:
      • Protocol LPR and Queue Name L1 and enable LPR Byte Counting.
    • Reach page "Install the print driver".
    • Select "Samsung" via scroll list "Manufacturer". Click "Windows Update" if "Samsung ML-2510 Series" does not appear in scroll list "Printers".
    • [Additional procedures may be needed to continue with printer addition]
    • Reach situation in previous step. Select "Samsung" and "Samsung ML-2510 Series". Click "Next".
    • [Additional procedures may be needed to complete printer addition]

    Monday, April 19, 2010

    Persistence Layer for Flex-and-Java Applications And The Like

    1. Introduction

    When architecting an RIA (aka Web 2.0) application, you have to decide how do you implement the persistence layer. Using the ORM is a standard nowadays, so it's given.  Question as to which ORM to use, got easier with strong acceptance of the Sun's JPA standard by the industry. But, how do you apply ORM in an RIA application is not a question with just a one obvious answer. On one side, the choice of the framework (and the architecture with it). This is presented in section 2. Section 3 presents another aspect of persistence layer: session management, that is how you actually use ORM to persist detached objects (detached, because they are received from outside of the application, namely from the client, for example a Flex client).

    2. ORM in an RIA Application

    Popular options are listed below. Each with advantages and disadvantages.

    2.1. Just-JPA Approach:
    • LCDS, BlazeDS or another Flex remoting framework
    • JPA (in general: ORM) on the server-side, with an object mapper like Dozer
    Pros and Cons:
    • Pro: Simple and a popular choice.
    • Con: Doesn't let you take advantage of ORM's lazy loading and lazy initialization.
      2.2. LCDS with Built-In Hibernate Adapter:

      This solution requires you to purchase a commercial heavy-duty Flex remoting framework Adobe LCDS (LiveCycle Data Services). If you go this way, to integrate it with persistence layer, you create a Hibernate assembler class on the server (Java) and point the LCDS destination to it, as described here.

      Pros and Cons:
      • Pro: (I believe) it takes advantage of lazy loading and initialization.
      • Cons: all of the persistence layer is implemented on the client which can lead to bigger/fatter client.
      • Cons: expense.
      • Cons: proprietary solution.
      2.3. BlazeDS with Gilead:

      Open source solution. Described in detail here.

      Pros and Cons:
      • Pro: open-source; no vendor lock-in.
      • Cons: unknown.
      2.4. GraniteDS:

      Provides a complete open-source solution. Described in a nutshell in comment to this article. More complete information, and a comparison with LCDS-with-Hibernate-assembler option, can be found in this article by the same person (as the comment), William Drai. This article has also more general, highly useful, background on the topic as a whole.

      Pros and Cons:
      • Pro: open-source; no vendor lock-in.
      • Cons: unknown
      3. Persisting Detached Objects

      The three most common applicable persistence design patterns are (as described by Hibernate documentation):
      • session per requestThe most common solution. A single Session and a single database transaction implement the processing of a particular request event. Do never use the session-per-operation anti-pattern.
      • session per conversationOnce persistent objects are considered detached during user think-time and have to be reattached to a new Session after they have been modified.
      • session-per-request-with-detached-objectRecommended. In this case a single Session has a bigger scope than a single database transaction and it might span several database transactions. Each request event is processed in a single database transaction, but flushing of the Session would be delayed until the end of the conversation and the last database transaction, to make the conversation atomic. The Session is held in disconnected state, with no open database connection, during user think-time.
      For another good article on this topic see this.

      3.1 More about Session-Per-Request Pattern

      Let's assume we have an application an RIA with stateless EJB's on the server side. Each request gets a new EntityManager injected. I suggest the following approach to implement session-per-request:
      • if we receive a new object, persist it using
            entityManager.persist(entity)
      • if we receive an object, that is already in the database, use
            entityManager.merge(entity)
      There is one narrow case, when this wouldn't work as expected: when we have a bidirectional association between Invoice and InvoiceDetail and we receive and invoiceDetail with the field invoice set to null. If we apply the method as above, the merge() will reset the invoice in invoiceDetail to null, while the field invoiceDetails in invoice object will continue pointing to invoiceDetail. However, I consider this not a practical case.

      4. Conclusion
      So, a simple starting point that I recommend for your RIA application is to use just JPA with a session-per-request persistence pattern. It can be as simple as:

      JpaDao {
        public void persist(E entity) {
          if (entity.getId() == null) {
            entityManager.persist(entity);
          } else {
            entityManager.merge(entity);
          }
        }
      }
      as suggested by Marcell Manfrin (in a comment).

      4. My Recommended Solution

      • Use JPA with an ORM provider of your own. 
      • Use only JPA annotations and avoid using native provider's annotations. If you have to use a provider's native application, mark it in the code in an easy to discover way.
      • Use session-per-request approach with object mapper like Dozer.
      • Unless domain model is very simple and used only in CRUD-like way, use DTO objects to transfer data between client and server (article).

        • Question: use simple domain objects with public fields?
      • Use service facade layer to:

        • manage session-per-request
        • map domain to/from DTO objects
        • isolate the client from the server
        • provide an lightweight API for the client rather than exposing the client to a complex domain model.

      Flex 4, Spark Architecture Overview: Notes

      Based on a great article by Deepa Subramaniam.

      Intro
      • Every Spark component consists of the skin class (defined declaratively via an MXML file) and a component class (defined via ActionScript).
      • Previous Flex component architecture and component set was MX, aka as Halo.
      • Spark components extend the MX class mx.core.UIComponent, and so Spark containers can hold MX components and vice-versa, and Spark and MX components can live side-by-side. The same component lifecycle methods, properties, and events that existed for the MX components apply to Spark components.
      Skinning

      Three key elements— data, parts, and states—define the skinning contract upon which Spark is founded:
      • Every Spark component class:

        • defines the data the component expects, 
        • defines the constituent parts that make up the component (aka skin parts), and 
        • defines the states the component can enter and exit; responsible for all of the event handling needed to identify when a state change has occurred and ensures the component is put in the right state.
      • The corresponding skin class:

        • how that data is visually displayed, 
        • how the parts are laid out and visualized (it instantiates the parts), and 
        • what the component looks like as it enters and exits different states.
      New Capabilities of Spark Architecture
      • Effects in Spark: faster and more capable; can be invoked directly within Spark skin classes through state-based transitions.
      • New layouts


        • APIs for robust 2D and 3D transformations,
        • the ability to easily implement custom layouts
        • assignable layout

        • FXG and MXML Graphics: graphics library that captures drawing primitives as simple MXML tags. FXG is a declarative XML syntax for defining vector graphics in applications built with Flex and can be created by Adobe Illustrator (or manually) and understood by other Adobe CS tools as well as by FlashPlayer (and probably created and read by Catalyst).
        What Next
        For more information, read references from the base article  by Deepa Subramaniam. For examples and details on skinning read article by Ryan Frishberg. For more information on FXG, read this Adobe well written documentation.

          Thursday, April 1, 2010

          JPA with Hibernate on Glassfish 3

          Intro
          This post is simply a summary of a simple proof of concept. It shows how to:
          • create a stateless EJB3 bean
          • persist an entity using JPA with Hibernate as a JPA provider
          • configure JPA to use a datastore defined on Glassfish (uses pre-installed java/__default datastore, which uses pre-installed Derby/JavaDB) 
          You can download the source code for this sample from here (EJB3_First_Project_with_Test.zip).
           

          Entity
          @Entity
          public class Book implements Serializable {
           @Id
           @GeneratedValue(strategy = GenerationType.AUTO)
           private int id;
           private String title;
           private float price;
           
           public Book() {
              super();
           }
          ...
          }
          
          Here, I have annotated the property, rather than the getter (not shown for brevity), since it feels more intuitive to me. I don't know if there is any advantage/difference of one vs the other other than my personal preference. The "@GeneratedValue(...)" annotation for primary key in JPA entity definition is not optional, as I expected. Using just the "@Id" annotation results in the primary key being not set (set to 0).


          EJB Bean
          The interface:
          @Remote
          public interface BookManager {
           public abstract int addBook(Book book);
           public abstract Book find(int bookId);
          }
          

          And the bean implementation:
          @Stateless(name="BookManager", mappedName = "ejb/BookManagerJNDI")
          @TransactionAttribute(TransactionAttributeType.REQUIRED)
          public class BookManagerImpl implements BookManager {
          
           // Dependency injection of Entity Manager for
           // the given persistence unit
           @PersistenceContext(unitName="pu1") EntityManager em;
           
           public int addBook(Book book) {
          
            // Transitions new instances to managed. On the
            // next flush or commit, the newly persisted
            // instances will be inserted into the datastore.
            em.persist(book);
            
            return book.getId();
           }
           
           @Override
           public Book find(int bookId) {
            return em.find(Book.class, bookId);
           }
          }
          

          The annotation @Stateless with the mappedName make the bean to get registered with JNDI. The
          TransactionAttributeType.REQUIRED tells the container to wrap each method in the class with a transaction.
           
          JPA Setup
          The persistence.xml file (put it into META-INF folder under src folder so it will be deployed onto the server)
          <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
              <persistence-unit name="pu1">
               <!-- Persistence provider -->  
                  <provider>org.hibernate.ejb.HibernatePersistence</provider>
                  <jta-data-source>jdbc/__default</jta-data-source>
          
                  <properties>
             <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
             <property name="hibernate.hbm2ddl.auto" value="create" />
             <property name="hibernate.show_sql" value="true" />
                  </properties>
              </persistence-unit>
          </persistence>
          

          The "hibernate." prefix in persistence.xml file is not optional when adding properties of the JPA provider (Hibernate in this case). They are ignored without it, without a warning.

          Glassfish Setup
          Nothing other than installing the Hibernate component using the Glassfish console.

          Unit Tests
          The unit test:
          try {   
             InitialContext ctx = new InitialContext();
             BookManager bean = (BookManager) ctx.lookup("ejb/BookManagerJNDI");
             Book book = new Book("Chocolate Rain", 25.10f);
             int bookId = bean.addBook(book );
             book = null;
             
             book = bean.find(bookId);
             Assert.assertEquals("Chocolate Rain", book.getTitle());
            } catch (NamingException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
             Assert.fail("Failed. Exception thrown.");
            }
          

          A Few Notes
          • Can JPA be used to create and index? Yes and no. Not in general. But it provides a limited capability. To create a unique constrain on a table, use @UniqueConstraint(columnNames={"EMP_BDAY", "EMP_NAME"})
            • How to specify the character column type length? Use @Column(length=50).
            • What the client can understand about the remote exception, in case the EJB bean fails? The remote exception is wrapped in a EJBException and returned to the client. For example, if the password for the DB is incorrect, the org.hibernate.exception.GenericJDBCException will be returned with a message "Cannot open connection" (when Hibernate is used as JPA provider).
             Conclusion
            A few things to try in the next proof of concept:
            • test the rollback function, if second of two persistence operations failed when both are in the same method of the BookManager class.
            • do a parent/child relationship.
             

            Thursday, March 11, 2010

            Hibernate Session and Transaction Management

            It seems, there are several approaches to manage Hibernate sessions and transactions:
            • explicitly by the application
            • explicitly by the application with ThreadLocal pattern (example)
            • via Hibernate transaction demarcation with JTA
            • via Hibernate transaction demarcation with plain JDBC
            • using Spring Framework
            • using EJB / CMT (container-managed transactions)
            For a good explanation of all options, other than ThreadLocal, see Hibernate document. Note that EJB, as well as JTA, are available even outside the J2EE container as a module. Also, supposedly, the Spring Framework can be easily used just for the functionality you decide to use from it and it doesn't require the application to use all parts of this framework.

            Basic Approach: Managed by Application
            Here's a code sample from hibernate document:
            Session session = factory.openSession();
            Transaction tx = null;
            try {
                tx = session.beginTransaction();
            
                // Do some work
                session.load(...);
                session.persist(...);
            
                tx.commit(); // Flush happens automatically
            }
            catch (RuntimeException e) {
                tx.rollback();
                throw e; // or display error message
            }
            finally {
                session.close();
            }
            
            You choose the approach.

            Monday, March 8, 2010

            Android Testing - Tips

            • What is Android Context class? It's "an interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system."
            • The native Android OS support for testing is based on jUnit 3. Don't try to use jUnit 4. The results are not predictable. I had the first test run fine, but no more tests would finish.
            • Testing support:

              • Use ActivityInstrumentationTestCase2 for functional testing of a single Activity. The selected activity will be created and managed by the system as specified by the regular activity lifecycle. Tests can interact with the UI widgets to imitate user actions.
              • Use ActivityUnitTestCase to run unit tests of an isolated activity. Activity under test will not be subject to regular activity lifecycle.
            • If you see a problem of type error: device not found and shutdown the adb.exe process. It will restart automatically and try to reconnect to the device. Sometimes, starting the intended Instrumentation on emulator (an option in Dev Tools application) does it all for you.
            • If adb does not connect after restarting it (shows "DeviceMonitor]Connection attempts: 11..." and LogCat nic nie pokazuje), restart PC.

            Tuesday, March 2, 2010

            JSON RESTfull Service Using Jersey with Hibernate Persistence on Glassfish - Part 2

            This is continuation of my blog on this topic. I'm adding the solution to the questions/issues left out in that first blog as delineated in the last part of the blog. Actually, this effort wasn't successful. I wasn't able to make it work. Although made a good progress, I had to go back to the approach presented in my previous blog. This post is just to document what I was able to achieve.

            JTA
            Switch to use JTA, instead of native JDBC transactions. All new application servers support JTA natively. With JTA, the session is bound to the transaction. If you call sessionFactory.getCurrentSession(), anytime between userTransaction.begin() and userTransaction.commit(), a session bound to this transaction is returned. User transaction is usually obtained via JNDI. So, an example of code:
            UserTransaction tx = (UserTransaction)new InitialContext()
             .lookup("java:comp/UserTransaction");
            
            SessionFactory factory = HibernateUtil.getSessionFactory();
            PersonDao dao = new PersonDao(factory);
            
            try{
             tx.begin();
             
             dao.saveOrUpdate(person);
             
                tx.commit();
            
            } catch( Exception ex) {
             tx.rollback();
            }
            
            while the only thing that the Dao needs to do is to request the session via: factory.getCurrentSession().

            The required Hibernate configuration file hibernate.cfg.xml:
            <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
            <hibernate-configuration>
                <session-factory name="hibernate/sessionFactory">
                 <property name="transaction.manager_lookup_class">org.hibernate.transaction.SunONETransactionManagerLookup</property>
                 <property name="transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
                    <property name="connection.datasource">jdbc/xaderby</property>
                    <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
                    <property name="current_session_context_class">jta</property>
                    <property name="hbm2ddl.auto">create</property>
                
                 <mapping resource="olcc/entity/Person.hbm.xml"/>
                </session-factory>
            </hibernate-configuration>
            
            where jdbc/xaderby is a data source defined on Glassfish, of type javax.sql.XADataSource.

            Configuration
            Glassfish 3
            Hibernate 3.5
            JDK 6 (Derby included)

            Result
            This configuration results in the following error message:

            FINEST: saving transient instance
            FINE: surrounding JTA transaction suspended [JavaEETransactionImpl: txId=1 nonXAResource=null jtsTx=null localTxStatus=0 syncs=[org.hibernate.transaction.CacheSynchronization, org.hibernate.context.JTASessionContext$CleanupSynch@1d069e4]]
            FINE: opening JDBC connection
            INFO: JTS5014: Recoverable JTS instance, serverId = [100]
            
            FINE: select next_hi from hibernate_unique_key for read only with rs
            FINE: update hibernate_unique_key set next_hi = ? where next_hi = ?
            FINE: closing JDBC connection (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)
            SEVERE: org.hibernate.HibernateException: unable to resume previously suspended transaction
                at org.hibernate.engine.transaction.Isolater$JtaDelegate.delegateWork(Isolater.java:179)
                at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:64)
                at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:74)
                at org.hibernate.id.TableGenerator.generate(TableGenerator.java:118)
                at org.hibernate.id.TableHiLoGenerator.generate(TableHiLoGenerator.java:84)
                at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
            When I tried using a plain javax.sql.DataSource instead of XADataSource, I was getting XAResource.start error.

            Remaining Questions:
            • findAllByProperty(), findByCriteria() and/or findByExample() methods. Commonly used. What is the right way to implement them?

            J2EE - Tips and Tricks

            • Sun/Oracle's J2EE 5 SDK is installed in small pieces. Unlike previous versions of J2EE, there is no j2ee.jar. And so, pieces of it are installed in glassfish\modules folder, as separate jars. For example, the JTA stuff is installed as jta.jar (the implmementation stuff, com.sun....* classes) and javax.transactions.jar, which holds the core of the JTA API.

            Saturday, February 27, 2010

            Android Development Tips and Issues

            General
            • After importing a project created by someone else, you may need to correct the Project Build Target via project Properties -> Android panel.
            UI
            • The attribute layou_height=fill_parent doesn't work as usually inside the ScrollView. Set the size explicitly, possibly using minHeight and MaxHeight.

              Friday, February 19, 2010

              JSON RESTfull Service Using Jersey with Hibernate Persistence on Glassfish

              Tips:
              • to setup Hibernate to use a datasource defined under Glassfish, see my other post.
              • usefull Jersey annotations:
                • for the resource class: @Path("/person/")
                • for a method: @GET @Path("{personId}/") @Produces("application/json"). Then, you can use public Person getUser(@PathParam("personId") int personId) for method declaration.
                • add @Consumes("application/json") with public Person post(Person person) method declaration. Jersey takes care of unmarshaling the Json into Person object.
              • to return an error code from the restfull webservice, throw a new WebApplicationException(Response.Status.NOT_FOUND), for example. This one would return 404 error. No Need to declare the jersey handler method as "throws ...".
              • to unit test the service, use com.sun.jersey.api.client.Client:
                Person result = Client.create().resource("http://localhost:8080/myapp/person")
                   .type("application/json")
                   .post(Person.class,new Person("Jon Smith",133));
                Assert.assertEquals("Jon Smith", result.getName()); 
              • To pass an object retrieved via Hibernate as a response from a webservice, it needs to be serializable. But objects retrieved this way have additional members and so they need to be converted to a pure entity object (Person, in my case). I have used the Dozer library for this purpose (see the code below).
              • The entity classes (Person and PersonCollection, in my example)need to be annotated with @XmlRootElement.

              Code:
              Complete web service implementation class code (in RESTfull, call a resource):
              package olcc.jersey.service;
              
              import java.util.List;
              import javax.ws.rs.Consumes;
              import javax.ws.rs.GET;
              import javax.ws.rs.POST;
              import javax.ws.rs.Path;
              import javax.ws.rs.PathParam;
              import javax.ws.rs.Produces;
              import javax.ws.rs.WebApplicationException;
              import javax.ws.rs.core.Response;
              import olcc.entity.HibernateUtil;
              import olcc.entity.Person;
              import olcc.entity.PersonCollection;
              import org.dozer.DozerBeanMapper;
              import org.dozer.Mapper;
              import org.hibernate.Transaction;
              import org.hibernate.classic.Session;
              
              @Path("/person/")
              public class PersonResource {
               
               @GET @Path("{personId}/") @Produces("application/json")
               public Person getPerson(@PathParam("personId") int personId) {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                Transaction tx = null;
                Person personClean;
                
                try{
                 tx = session.beginTransaction();
                 Person person = (Person) session.load(Person.class,personId);
                 
                 Mapper mapper = new DozerBeanMapper();
                 personClean = mapper.map(person,Person.class);
              
                 session.getTransaction().commit();
              
                } catch( Exception ex) {
                 if( tx != null ) tx.rollback();
                       throw new WebApplicationException(Response.Status.NOT_FOUND);
                }
                return personClean;
               }
               
               @GET @Produces("application/json")
               public PersonCollection get() {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                  session.beginTransaction();
                List<person> result = session.createQuery("from Person").list();
              
                Mapper mapper = new DozerBeanMapper();
                PersonCollection persons = new PersonCollection();
                      
                for( Person person : result ) {
                  persons.add(mapper.map(person,Person.class));
                }
                session.getTransaction().commit();
                      
                return persons;
               }
               
               @POST @Consumes("application/json")
               @Produces("application/json")
               public Person post(Person person) {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();
                
                session.save(person);
                
                session.getTransaction().commit();
                return person;
               }
              
               @GET @Path("delete/{personId}/") @Produces("application/json")
               public Person deleteOne(@PathParam("personId") int personId) {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();
                Transaction tx = null;
                      Person personClean;
                
                try{
                 tx = session.beginTransaction();
                 Person person = (Person) session.load(Person.class,personId);
                 session.delete(person);
                 
                 Mapper mapper = new DozerBeanMapper();
                 personClean = mapper.map(person,Person.class);
              
                 session.getTransaction().commit();
              
                } catch( Exception ex) {
                 if( tx != null ) tx.rollback();
                       throw new WebApplicationException(Response.Status.NOT_FOUND);
                }
              
                return personClean;
               }
              }

              Open Questions:
              • I'm not sure where the Hibernate session should be closed. I don't think this can be done at the end of each handler method.
              • How to use JTA for transaction management instead of direct JDBC transaction management?
              • Most of the Hibernate-specific code should go into a DAO, with most of it into a generic DAO. But the recommended by Hibernate documentation generic DAO is defined in terms of state-oriented data access API (makePersistent() and makeTransient() methods), which are less intuitive for me. What is the advantage of using them and how to use them from CRUD operations?

              Wednesday, February 17, 2010

              Configure Hibernate to Use A Datasource

              I'm using Glassfish application server, on which (using its Console) I have created a JDBC datasource (JDBC Resource). I'd like configure the hibernate framework to use it. The resons:
              • Connection pooling (it's true that I could use the Hibernate's own connection pooling)
              • Portability: moving the application to another application server is easy, as long as they both provide a datasource with the same name (Hibernate dialect may still need to be changed appropriately).
              hibernate.cfg.xml File
              <?xml version="1.0" encoding="UTF-8"?>
              <!DOCTYPE hibernate-configuration PUBLIC
                "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
              <hibernate-configuration>
                  <session-factory name="hibernate/sessionFactory">
                      <property name="connection.datasource">jdbc/derbydb</property>
                      <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
                      <property name="current_session_context_class">thread</property>
                      <property name="hbm2ddl.auto">create</property>
                  
                   <mapping resource="olcc/entity/Person.hbm.xml"/>
                  </session-factory>
              </hibernate-configuration>
              


              HibernateUtil.java File
              private static SessionFactory buildSessionFactory() {
                  return new Configuration().configure().buildSessionFactory();
              }
              


              The Application Code
              Session session = HibernateUtil.getSessionFactory().getCurrentSession();
              
              

              Thursday, February 11, 2010

              Using Powermock to Mock Java Objects for Unit Testing

              This test uses the EasyMock style (as opposed to Mockito style), so it needed the corresponding file download. The code sample (click on view source icon to see it better):
              import org.junit.Test;
              import org.junit.runner.RunWith;
              
              import static org.easymock.EasyMock.expect;
              import static org.powermock.api.easymock.PowerMock.*;
              import org.powermock.core.classloader.annotations.PrepareForTest;
              import org.powermock.modules.junit4.legacy.PowerMockRunner;
              
              @RunWith(PowerMockRunner.class)
              @PrepareForTest({Person.class })
              public class PersonResourceTest {
              
                  @Test
                   public void testPost() {
              
                      Person personMock = createMock(Person.class);
                      expect(personMock.getName()).andReturn("Jon Smith");
                      replay(personMock);
              
                  // do the test...        
              
                      Assert.assertEquals("Jon Smith", result.name);
                  }
                  
              }

              Wednesday, February 10, 2010

              SQL Checks And Rules

              In most data models, there are columns that should take values only from a limited set.  For example, a state of License (as in our current project) may only take three values: AppliedFor, Granted or Denied. This kind of restriction is part of what is called Domain Level Integrity. How do you implement it?

              Old Way: Separate Table
              I used to create a separate table for the allowed values. It can be done, but this table has only couple records in it, is rarely updated and using a whole table for this is almost an overkill. Also, you end up writing more code to manipulate it.

              New Way: SQL Rules
              There is an SQL construct purpose of which is exactly this kind of constraint: SQL Rule (for Sybase docs: see this). An example:

              create rule pub_idrule 
              as @pub_id in ("1389", "0736", "0877", "1622", "1756")
              or @pub_id like "99[0-9][0-9]" 
               

              Wednesday, February 3, 2010

              Persistence Frameworks, ORMs

              The big three, I consider mainstream (from Java perspective):
              • Hibernate
              • JPA
              • JDO
               I have sorted them in the market share order, but there are some interesting facts that make all three important:
              • Hibernate is definitely the strongest, most popular ORM framework for Java and .Net, but it's not a standard per se.
              • JPA is a standard and it's fully supported by HIbernate, so choosing it gives you some advantages over Hibernate. Its design was based on Hibernate and JDO.
              • You can use Hibernate and restrict yourself to the JPA-only, which gives you a portability to another JPA-type framework, if you so choose in future.
              • JDO, although the oldest one, is the preferred persistence mechanism for Google Application Engine, the Java application hosting service of Google (although, you can also use JPA with it).
              Which framework to choose? Your choice.  Need more help choosing? Try this article.

              Saturday, January 2, 2010

              Trends in Web Application Development

              Recently, I have been exploring the landscape of web application development a little but.  Here are some of the results. Comments are welcome. What is the real trend?

              Overall Look
              Simple. I have used indeed.com trends tool to compare number of jobs openings for major web application development platforms and technologies. Result is below:

              Some conclusions that seem obvious:
              • Major development platforms had a hit in mid-2008, but recently are slowing down. Note, that the latter can't be explained with economy, since the graph shows the percentage of job postings, not the absolute numbers. Possibly, hiring in IT slowed down as compaed to other areas, though.
              • Definitely, the Web2.0 (RIA) technologies are experiencing the strongest, or better to say the only growth. Look at Ajax. More analysis on this below.
              Now, to verify this result, let's see the results from google.com/trends.

              Server-Side Technologies
              This comes from google.com/trends:
              Server-Side Technologies

              One technology, I have definitely missed on the indeed.com side, it seems, is the PHP. A strong player.

              Client-Side Technologies
              Client-Side Technologies

              The most surprising conclusion from the graph above is that Flash technology is so much above all of the rest. And it's significantly more obvious than on the job openings analysis. That may mean, that Flash is coming to the market as a strong candidate. However, since flash is not necessarily used for application development, I am adding another graph, with flex web instead of flash.
              RIA (Web2.0) Technologies

              Here. it seems we can see the currently strongest players. Ajax, which, unfortunately is split among many libraries, is still the front runner. However, it seems to give in to Flex and Silverlight. That wouldn't be a big surprise, since Ajax based on JavaScript is a rather low-level development hack, only somewhat improved by using an Ajax framework.
              Finally, one more graph. It comes from indeed.com. A comparison of job openings for Flex, Silverlight and GWT developer jobs:

              And, just for a comparison, a sample of mobile development job trends:




              Conclusion
              So, that's it for my analysis. What do you think? What is the future of web application development? Specifically:
              • What should application developers invest in for the the 2010?
              • What will in be over the next five years (futuristic prediction)?
              Waiting for your comments.