Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, October 19, 2010

Web Slices: you need to use Alternative Display Source or javascript will not work

If your WebSlices use the Basic Web Slice model, javascript will not work (this file is WebSlice.html):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

<div class="hslice" id="SliceID">
     <span class="entry-title">Title of the web slice</span>
     <div class="entry-content">Preview of the <a href="#" onclick="document.getElementById('Message').innerHTML='Hello'; return false;">web</a> slice
       <div id="Message"></div>
     </div>
     <p>
     Hola Rebanadas Web!
     </p>
  </div>

</body>
</html>

you have to use Alternative Display Source to make javascript work (this file is WebSlice.html):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

<div class="hslice" id="SliceID">
      <span class="entry-title">Title of the web slice</span>
      <a rel="entry-content" href="AlternativeDisplay.html" style="display:none;">Alternative Display Source</a>
      <p>
      Hola Rebanadas Web!
      </p>
   </div></body>
</html>

 

and in the file AlternativeDisplay.html you put the code that use to be in WebSlice.html (and that needs to use javascript):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
     <div class="entry-content">Preview of the <a href="#" onclick="document.getElementById('Message').innerHTML='Hello'; return false;">web</a> slice
        <div id="Message"></div>
      </div>

</body>
</html>

Tuesday, November 24, 2009

Scala is not mature enough for Weld

Scala is not mature enough for Weld (or any other reflection related operation). Turns out that one of the feature that make Scala so interesting (closures) is also a source of incompatibility (the internal anonymous class files that generate are invalid)

So, if for example, I have a code like this (inside any method in a class):

val classNames = Conversions.convertList(names).reduceLeft[String] { (acc, n) =>
acc + ", " + n
}


That generates an inner class that makes Java reflection unusable:



java.lang.IncompatibleClassChangeError: com.googlecode.solder.dwr.WeldContainer and com.googlecode.solder.dwr.WeldContainer$$anonfun$getClasses$1 disagree on InnerClasses attribute
at java.lang.Class.getDeclaringClass(Native Method)
at java.lang.Class.getEnclosingClass(Class.java:1085)
at java.lang.Class.getSimpleBinaryName(Class.java:1220)
at java.lang.Class.getSimpleName(Class.java:1112)
at org.jboss.weld.util.Names.typeToString(Names.java:251)
at org.jboss.weld.util.Names.classToString(Names.java:263)
at org.jboss.weld.introspector.jlr.WeldClassImpl.<init>(WeldClassImpl.java:151)
at org.jboss.weld.introspector.jlr.WeldClassImpl.of(WeldClassImpl.java:133)
at org.jboss.weld.resources.ClassTransformer$2.call(ClassTransformer.java:72)
at org.jboss.weld.resources.ClassTransformer$2.call(ClassTransformer.java:68)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at org.jboss.weld.util.collections.ConcurrentCache.putIfAbsent(ConcurrentCache.java:125)
at org.jboss.weld.resources.ClassTransformer.loadClass(ClassTransformer.java:67)
at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:59)
at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:86)
at org.jboss.weld.bootstrap.BeanDeployment.deployBeans(BeanDeployment.java:134)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:367)
at org.jboss.weld.environment.servlet.Listener.contextInitialized(Listener.java:158)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)


Apparently this is a known problem since 2008-08-03 (16 months so far) and AFAIK they are not in a hurry to fix it.



I guess that means I am going to have to start removing Scala from my Weld project. I am sad about this because Scala is IMO a really beautiful language, that feels much cleaner than Java, but if the .class files that it generates are not compatible with the rest of Java... it is just useless for me.

Monday, November 16, 2009

Playing with Weld and Scala to create a new framework for JSPs

Today I built my first "serious" example using Weld and Scala.
You can take a look at it in here.
So far, Weld looks like really good framework, I am still not able to say that it will replace Spring as my "glue framework", but that could certainly become true.
Scala also looks interesting (this also my first "serious" attempt at doing something with Scala), but the support for Scala in Eclipse is very fragile... the plug-in still needs a lot of polishing (no refatoring, no quickfixes, and the syntax coloring and cursor control sometimes goes crazy). I would not recommend the Scala plugin in Eclipse for "real work", but for hobbing is fine. (I wonder if the support for Scala in the Netbeans or the opensourced version of IntelliJ is better).

Friday, November 06, 2009

JPA Myth: EclipseLink and Hibernate are compatible. Not true: Hibernate does NOT follow the JPA Spec

Please take a look at the Hibernate JIRA issue EJB-441, seen it?

Now, please tell me if this is correct:

According to Gavin King (author of Hibernate) the JPA spec the @Column(nullable=false) is just a schema generation hint, and therefore JPA implementations should NOT use it for object level validation.

I think that means that if an entity object with a null property marked with the @Column(nullable=false) is persisted using entityManager.persist() it should crash with a java.sql.SQLException as the root exception, thrown when the "INSERT" statement failed after it was sent to the database by the JDBC driver (as it happens in EclipseLink), and not because some implementation specific mechanism "pre-validated" it and prevented it from reaching the database (as it happens in Hibernate thanks to org.hibernate.engine.Nullability.checkNullability).

Is that correct? Because I don’t know anymore!

Lets say that is correct, does that means that the following is correct too?:

Validation should be entirely the responsibility of the JSR-303, and the properties of an entity should only be checked for nullability before sending to the database if a JSR-303 implementation is there to indicate that.

Is that true? And if it is, then:

What is exactly the difference between @Basic(optional=true) and @Column(nullable=true)? What happens when this 2 are applied to the same property, but they contradict each other? (As in : @Basic(optional=false) and @Column(nullable=true) or in @Basic(optional=true) and @Column(nullable=false)

I could not find a statisfactory answer in the spec documentation, would anyone be so kind as to resolve this issue? Because it Hibernate Forums they have decided that the way to deal with this inconsistencies and contradictions in Hibernate and in the JPA standard is to plain ignore me since May of 2009.

As you can see I tried to raise the issue with 2 JIRAS, forum post and easy to reproduce unit-tests, but nothing seems to work… what should I do then?

Tuesday, September 15, 2009

Can I use JConsole to monitor an application through a firewall?

A fragment of JConsole documentation (bold type emphasis added by me):

The com.sun.management.jmxremote.port management property specifies the port where the RMI Registry can be reached but the ports where the RMIServer andRMIConnection remote objects are exported is chosen by the RMI stack. To export the remote objects (RMIServer and RMIConnection) on a given port you need to create your own RMI connector server programmatically, as described in the section

Mimicking Out-of-the-Box Management Using the JMX Remote API in the Java SE Monitoring and Management Guide.

I actually need to write code to be able to monitor a Java application through a firewall! Talk about an unfinished product! and Sun guys even have the nerve to act surprised angry when  people say that Java is over-engineered.

Sunday, June 07, 2009

JEE Development Deployment: In the order wrong

So, you start a new we project in Eclipse 3.4.1 (or in Netbeans 6.5.1) and you run it, what happens is that basically the project gets copied in to the directory the application server uses to “keep” the applications it runs, then the application server starts, looks in to its directory for applications and starts your application, and you are able to see your project,if you are using Tomcat, or JBoss as lot people do, you will be able to see you web project on port 8080. Right? Wrong!

what really happens is that then the application server starts and then the project gets copied in to the directory the application server uses to “keep” the applications it runs, then the IDE opens the web browser, that connects to the port 8080 using an url that includes the context of the application, its “name” so to speak, and then, the application server then realizes there a new application with that name in on its “directory applications” and starts it.

Noticed the difference:

What one typically believes it happens:

  1. the project gets copied in to the directory the application server uses to “keep” the applications it runs
  2. the IDE starts the application server
  3. looks in to its directory for applications and starts your application…
  4. now you will be able to see you web project on port 8080

What really happens:

  1. the IDE starts the application server
  2. the project gets copied in to the directory the application server uses to “keep” the applications it runs
  3. then the IDE opens the web browser, that connects to the port 8080 using an url that includes the context of the application
  4. the application server then realizes there a new application with that name in on its “directory applications” and starts it

Now, why is it so important to understand in what order this happens?

Well, because during development this processes is repeated again and again, until the application reach a point where it can be delivered to the customer the problem is that some times, one of the iterations of this process ends with an application so dysfunctional that it is able to crash the application server (and that will not stop until we get a real virtual machine for java).

But until we do get a better virtual machine, there is a more pressing problem, if we deploy an application that crashes the application server, the order in which the process is currently done makes it impossible to deploy the fixed version, unless we delete the previous version completely. Why do I say that: well lets analyze it, lets say we start with a fresh application server, where we have never installed our application:

  1. then the application server starts
  2. the project gets copied in to the directory the application server uses to “keep” the applications it runs
  3. then the IDE opens the web browser, that connects to the port 8080 using an url that includes the context of the application
  4. the application server then realizes there a new application with that name in on its “directory applications” and starts it

This first version of our application is far from finished, but it does not have any bug capable of crashing the application server, so we add som more functionality, and we ask the IDE to run our application again, and what does the IDE do?:

  1. then the application server starts
  2. since the application server already knows it has our (failed) application installed, it does not need a visit from the browser to start it, in starts it immediately
  3. the project gets copied in to the directory the application server uses to “keep” the applications it runs, since the application is already there, only the changed files are copied
  4. if the changes are of a particular kind (alterations to web.xml for example) the applications server restarts the application so that it starts working with the new configuration
  5. then the IDE opens the web browser, that connects to the port 8080 using an url that includes the context of the application

This second version of our application actually has a nasty bug, so after step 4, the application server hangs, and we are forced to kill it using the services provided by the operating system to deal with misbehaving processes, then we go back to our code, fix the problem, and we ask the IDE to run our application again, and what does the IDE do?:

  1. the IDE starts the application server
  2. since the application server already knows it has our (failed) application installed, it does not need a visit from the browser to start it, in starts it immediately
  3. The application server hangs.

And that is it, the project files are never copied in to the directory the application server uses to “keep” the applications it runs, the critical problem here is that the IDE seems to wait for the application server to start correctly before copying the new files (it should copy them any way, that of course would not prevent it from hanging, but, after we had killed the process, the next time we ran the application server, if we had fixed the bug, it would not hang any more… but even then the behavior would be anti-intuitive, why the process is not like this is a mystery to me:

  1. the project gets copied in to the directory the application server uses to “keep” the applications it runs, since the application is already there, only the changed files are copied
  2. the IDE starts the application server
  3. since the application server already knows it has our (failed) application installed, it does not need a visit from the browser to start it, in starts it immediately
  4. Since we have fixed the bug, everything runs fine

Do you know why it does not work like this? If you do, please… would you explain it to me?

Saturday, April 18, 2009

Inversion of re-render (subscription based re-rendering): Why it can not be this way?

Anyone that has used Richfaces knows that to rerender something, one needs to refer to it by id.

Now, this is (in my opinion) an useful approach but also a very limited one, specially if componentization and code reuse are important goals during development

Lets say I build a page (lets call it root page), that has a subview with a modalPanel, that includes a facelet component, that has a subview with modalPanel that includes another facelet component, and, when something is done here, I one another control, in the root page to be rerendered

Now, I could of course pass along the ids of the component I need to be re-rendered, but... what if I need another component to be re-rendered too? do I pass along its id too? and what if the other component is also inside (a different) subview with a modalPanel, that includes a different facelet component... then all this id "passing" gets really messy, and creates dependencies in components that could otherwise be decoupled... and to make things worse, using meaningful ids in JSF is not considered a good practice, because meaningful ids (specially if used in name container like the subviews) rapidly increase the size of the pages (because they concatenate to ids of all the contained controls), contributing to bandwidth waste .

Now, I have a proposal, what if re-rendering were to work in an "inversed" way: instead of "A" saying that it will re-render "B", we say that "B" will be re-rendered when something (maybe "A") says so by broadcasting event "C".

This would mean that "A" no longer needs to know the name of "B" and "B" wouldn’t need to know the name of "A" either, it would only need to know that it should re-render itself it something, somewhere broadcasted the event "C"

Am I making sense here? Is this doable? Or am I not seeing a major limitation in JSF technology that prevents this from being built? (I am no expert in JSF, so I really can not say, but I do know that an event subscription based re-rendering engine would be a really nice tool to have)

Monday, March 16, 2009

EntityManager.persist: ¿What does/should it mean?

Lets say you are presented with the following JPA @Entity:

@Entity
public class Customer {

private Long id;
private String name;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}

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

@Column(nullable=false)
public String getName() {
return name;
}

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



And then the following test



@Test
public void persistCustomerInTransaction() throws Exception {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

EntityManager em = factory.createEntityManager();

em.getTransaction().begin();

Customer customer = new Customer();

em.persist(customer);em.getTransaction().commit();

em.close();

}



And the following question: Where does it crash?:




  1. At the line em.persist(customer); because the name is configured as nullable=false, and we are trying to persist the Customer instance with a null value in the name property


  2. em.getTransaction().commit(); because the name is configured as nullable=false, and we are trying to commit the transaction with a null value in the name property



Turns out… that the answer depends on the JPA provider you are using!!!! If using Hibernate, it crashes at em.persist, but if using EclipseLink, it crashes at em.getTransaction().commit.



Now, this might seem irrelevant, but it is in fact very important, because EclipseLink behavior means that constraint validations are deferred until the point where the transaction is committed, and that means that the developer has a lot more freedom to manipulate its persistent objects: they can be in any (possibly invalid) state while they are being manipulated by the business logic of the application, and they only have to be “right” the moment one needs to commit them to the database (not before), this is specially useful, for example, when building a wizard like UI (or a plain simple CRUD UI with support for full object graphs) with EclipseLink, I can persist my objects as soon as I want, and if want to, for example, run some validation logic at the end, all I have to do is ask the EclipseLink to give a list of all the objects that are going to be written in to the database, with Hibernate, the entityManager does not help me manage new object instances, I have to manage them myself.



What I find really surprising is that AFAIK there should be some kind of test to ensure that all JPA are compatible (something called the TCK?), and I think that this kind of discrepancy should be detected by those tests... shouldn't it?


I think this support for deferred validation, and an API to get will be inserted, will be updated or will be deleted, will be very important to really integrate JPA with something like JSR 330, so that validation can really integrate with the lifecycle of a persistent POJO.

Saturday, March 14, 2009

JPA/Hibernate (subjective?) weaknesses

I have had to work with JPA/Hibernate for a few years now... and I feel it has some weaknesses I really do not like (when compared with the first ORM I ever used, NextStep EOF), I am thinking about "switching to something else" but first i would like to be sure that the ORM I switch to does not have this weaknesses too.
List of (subjective? perhaps I only perceive them because I was exposed to EOF first?) weaknesses in JPA/Hibernate:

  • No way to manage an object that "will be persisted", in JPA/Hibernate if you call entityManager.persist(object) and the database does not support sequences (like MS-Sql) an insert will be triggered, and if any of the non nullable fields of the objects is null, it will crash. If your object has a compound primary key, things get worse, because the entityManager can not deal with it until the compound primary key is set, and if your compound primary key is formed by foreign keys pointing to objects that are new too, that means you will not be able to save stuff with with a simple single call to entityManager.persist to one of the objects, cascading will not help you (I really miss something "magic" like the single shot EditingContext.saveAllChanges() in EOF)
  • No easy way to know if "an object is dirty" (if it has changed/deleted since it was read from the database, there is just no API for that), and since you can not know what objects will be persisted, and what object have changed, and what objects will be deleted from database, that means you can not easily create an unified API for centralized polymorphic validation (that is no easy way to create validateForSave, or validateForDelete methods in your persistent entity classes)
  • No real equivalent for validateForXXX, JPA lifecycle callbacks are not match for validateForXXX because you can not query the database during the lifecycle callbacks, and if you throw an exception inside a lifecycle callback, the JPA/Hibernate entityManager enters an invalid state, and after that you can not continue to use your POJOs, you have to start over with a fresh entityManager... and without you modifications to the POJOs. Note that Hibernate new validation framework does not offer a real solution for this problem... and AFAIK JSR-000303 will not help with this either.
  • No support for some kind of temporary id: In JPA/Hibernate, the id for an object is "null" until you flush it to the database, so if you need to reference a particular object instance from the user interface... there is plain no way to do it, you have to "save it first" to get a primary key.
  • No support for Nested Contexts... ( I think they would be a perfect fit for conversational frameworks like Seam or Shale). One of the goals of the ObjectContext is to provide an isolated area where local object changes can be performed without affecting other similar areas or the underlying storage. Nested Context changes can be saved to the parent Context without saving them to the database. Such child context is often called "nested". Nested contexts are useful in many situations, such as nested UI dialogs, complicated workflows, etc.

Those are my main disagreements with the way I have to work with JPA/Hibernate... will switching to JPA/EclipseLink, JPA/OpenJPA or the still not fully JPA compliant Apache Cayenne help me with those? I will be writing about my findings on this in my following posts

Wednesday, February 25, 2009

AribaWeb: The framework of my dreams?

Could AribaWeb, finally be the framework of my dreams? that for which I have longed for ever since I stopped using WebObjects? The one to finally demonstrate those Ruby guys that what makes Ruby so great is Rails, and what made Java inferior (until before AribaWeb) was its framework, but not the language itself?

So far, it seems that, while not perfect (no client side caching, some Hibernate inherited validation limitations), AribaWeb gets many basics concept right (like programmatic navigation, UI meta generation, runtime UI customization, MVC separation…)

I am simply amazed….

Now someone just needs to integrate AribaWeb with Capuccino, and total world domination would be in their hands.

Tuesday, October 21, 2008

Process Isolation: JavaScript is getting it before Java!

So, with Google Chrome, JavaScript is finally getting process isolation (even IE 8 will work in a Loosely Coupled Internet Explorer (LCIE) mode that will give the JavaScript applications running there real OS level process isolation) and Java? well, Java still does not have a anything like that.

Wednesday, July 30, 2008

Spring vs J2EE Application Servers

Lately I have been playing with Oc4j, Tomcat, Glassfish and JBoss, before that, I had only played with Spring and Tomcat (but Tomcat was irrelevant, it was there only to start Spring) and now I have realized why Spring is much more comfortable than JEE, even with all the enhancements of JEE5: Spring is “inside” your application, for example, if you want to connect to Oracle with Spring, you add the JDBC jars to your application, and then configure your datasource in the applicationContext.xml file inside your application, if you want to use log4dbc and slf4j to debug the SQL generated by Hibernate (BTW Hibernate .jars are also inside your application) you can do it, and you only have to modify, again, the applicationContext.xml file inside your application, if you want to add support for Spring transaction handling, or you want to expose some of your beans as CeltiXFire Webservices, you describe all that: exactly, you guessed correctly: inside your application. You really don’t care about the stuff outside of your application.

With JEE is the other way around, you have to worry about stuff outside of your application (for example, avoiding name conflicts in the JDBC datasources registered in JNDI), you have to worry about installing the Oracle .jars in Tomcat, Glassfish or JBoss (and worry about conflicts if the version installed as by default in Oc4j (or as shared in Tomcat) is not the one you want to use). You have to worry about compatibility with the way WebServices are handled and configured by your particular application server, etc.

And finally, when you want to test stuff, you have to start the all the huge application server, even if you just want to test if your Login page is working correctly and if after logging in, the right permissions were loaded in the the current session.

I think that is pretty much why JEE still feels uncomfortable when compared with Spring, JEE it is still about the application server, not about my application: and I really don’t care about the JEE application server, all I care about it is my application. I think that JEE6 (or perhaps JEE7) should focus in finding the way to take the attention back in to the application, perhaps by forcing the JEE application servers to offer their services the way Spring does it, from inside the application, and only if you want it, as a second, hard to configure option, make those services shared.

Saturday, October 20, 2007

It was programmed with...

Lately I have been seen people at work saying "I built that system using Php" or "We should build all our applications with Java" or "All our applications should be built with Ajax" or "We should (or should not) use Java/J2EE", but in the majority of the cases it turns out that the final product is something that is not built with a single technology but a combination of several ones... and the problems with that show up when we start to integrate applications:
  • Integrating this applications will be easy they both use WebServices (Yes, but one of them uses JSON, another SOAP, another REST and another used Hessian)
  • Lets combine this two web applications in to a single one (Yes, but one of them is built using Spring+Hibernate and the other was built with JDBC+Home Made Wannabe Framework)
  • The architecture of this applications is very similar they are both OLTP applications, integrating their code bases will be easy (or exchanging developers between them will be easy) and it turns out one of them is built using Stored Procedures in PL/SQL, another uses TopLink and the last one uses IBatis.
  • This two applications are AJAX bases it will be easy to integrate them (or exchanging developers between them will be easy) .... ups, they use to completely different and perhaps even incompatible AJAX frameworks

So... are we really saying something that somehow resembles the truth when we say "I built that application with XXXX"? I think not... but then... why do we keep saying stuff like "That was built in Java" if there are 1000 different ways to build it with Java.... 1000 ways to build with AJAX, 1000 ways to build it with PHP, 1000 ways to build it in .NET ... and millions of ways to build it, if we start combining this "base" technologies.

Saturday, October 06, 2007

Ruby is younger therefore better than Java?

I wrote this as a response to From Java to Ruby: Programmer's view, but I couldn't post it because of a bug in that site, so I decided to post it in my own blog:

Isn't this a simplified view of the advantages of Ruby over Java? For example the lack of choice in Ruby means that if the "one Ruby way" to do stuff is not good for you project... you will have to go to other technologies (Java for example). And that can happen pretty often:

  • Hibernate has many more options for integration with legacy databases than Ruby's Active Record... almost all databases now have JDBC drivers (you can not say the same about Ruby database support).
  • Spring offers integrated transaction handling that makes it possible to switch from JDBC transactions to JTA transactions without changing a single line of Java code (you just need to modify around 5 lines in an XML file) what is the equivalent for that in Ruby?
  • Calling stored procedures is not that easy with Ruby... what is the equivalent of HQL (JPAQL) for Ruby... can you honestly say that it can handle all the special cases HQL can... and with the same efficiency?
  • With java I can build a web application GWT style, JSF style or plain JSP style... and each style has advantages and disadvantages... do I have all that power with Rails? (Of course, those frameworks can be re-built in Ruby, but the question is, do I have them now?)

I think you are right when you say that it's healthy to start with a clean slate and rebuild based on a cleaner, simpler foundation, but before saying that the new foundation is actually better than the older one, you have to be sure that your new foundation is actually capable of handling all the special cases the old foundation was capable of handling... or remember that maybe if you remove all the abilities the old foundation has to handle special cases you might end up realizing that your new foundation is just a replica of the state that the old foundation had when it was younger. (And even then the older foundation has the advantage that you can use it as it was used in the past, but you can not use a new foundation as it will be used in the future)

Saturday, July 14, 2007

Unit testing Relational Queries (SQL or HQL or JQL or LINQ...)

Hi!
Most applications I have built have something to do with a database (I remember that while I was on college I used to think that was not exiting stuff, I used to dream about doing neural networks stuff, logic programming in Prolog, etc) but then I met WebObjects and its Object Relational Mapper (Enterprise Objects Framework) and I got really excited about object oriented data programming... but I always had a problem... to test my object oriented queries I had to "manually" translate them into SQL and test them against the database, and only after they give me what I thought were correct result I would write them using EOF Qualifiers...
Then I met Hibernate's HQL and I realized it is much more powerful than EOF Qualifiers, but I still had to translate it to SQL to test it, I know I can get the SQL that is generated from the HQL from the debug console, and paste it in my favorite SQL editor... but even then if I found a mistake, a lot of times it was easier to tweak it in SQL and the manually translate it HQL.
Currently, there are some extensions for Eclipse (Hibernate Tools) that make this more "direct" but, what if I don't like (or don't want, or can't) use Eclipse... it would be great if someone could, for example, make a plugin for SquirrelSQL, but until then... what options do I have?

Then I learned about unit testing... and the answer came to my mind immediately: I just had to write a unit test for each of my queries. That worked fine... in the beginning... until I started having queries that returned thousands (or millions) of objects, and it wasn't such a good idea to output them to the debug console... and I had another problem... how should I write the "asserts" of query?... and how can I do it so that it doesn't make my test so slow that it becomes unusable? (I can, of course, check the results just by viewing them, but my brain is not that good to say if those 10,000 row really match with the idea I had when I wrote that HQL)

So, I started to look "what do I do" to check if an SQL query is correct, lets say for example, that I write this:

select count(*) from Address,Employee where Address.Id= Employee.AddressId and Employee.Id = 3

(Translated to English: How many address the Employee with Id = 3 has?)

Now... how do I test that? well I could add an assert after getting the result in java (or c#) like this:

assert(count>0)

But the, what happens if someone deletes the row with Id = 3 from the table Employee? That means my test will fail... or what what if someone deletes all the addresses from employee? and what if I want to test that if there are no addresses for an employee, the answer should be zero...

That is a lot of work just to test if that simple query is right... and I think that work could be done automatically:

Take a look at the SQL, it could be decomposed into:

select count(*) from (select * from Address,Employee where Address.Id= Employee.AddressId and Employee.Id = 3) as EmployeeAddresses

And then we could say, lets automatically check for the case when the resulting set is empty, and for the case when the result is not empty, to check for a case when the result is empty, we need and Employee with Addresses, so we generate:

Select * from Employee where exists(select * from Address where Address.EmployeeId = Employee.Id)

And take the Id first employee we get... and that should give us a non empty set if used in the original sql sentence that we are trying to test... after that, we automatically generate:

Select * from Employee where not exists(select * from Address where Address.EmployeeId = Employee.Id)

And take the Id first employee we get... and that should give us an empty set if used in the original sql sentence that we are trying to test...

I call this queries "inverses" of the original one, it like when one is testing a multiplication, to see if 2 x 3 = 6, just do: 6/3 = 2 and 6/2 = 3, if 2, and 3 match the operands of the multiplication, you multiplication is right. The same thing goes for SQL, one just has to find the way to "invert" it, if I could automate this inversion, the automatically generated queries would help me by telling me things that might not be immediately obvious to me when I look at the original query, and that would help me check if my original query is right.... it would me some kind of "invariants" that would help me to better understand my querying... or maybe I could even write the invariants first, and then create a query and see if it matches my invariants...

Mmmm.... maybe using a select there is another way to "invert" a query to test if it is right, using the actual inverse operation of selecting... that is "inserting", could I derive from:

select count(*) from Address,Employee where Address.Id= Employee.AddressId and Employee.Id = 3

Something like (In pseudocode):

Insert Employee;
Store Employee.Id
Run select count(*) from Address,Employee where Address.Id= Employee.AddressId and Employee.Id = EmployeeId
Assert("The answer should be zero")
Insert Address related to Employee
Run select count(*) from Address,Employee where Address.Id= Employee.AddressId and Employee.Id = EmployeeId
Assert("The answer should be one")

This has the advantage that I don't need a database with data already on it, but it has the disadvantage that takes lot of time to write an unit test like this in java, because to insert an employee, it might be necessary to:


  • Avoid breaking validation rules no related to this particular test, for example, an Employee must be related to a Department, but if the Department table is empty, then I should create a Department or I will not be able to insert an employee.
  • Avoid conflicts with validation rules directly related to this particular test, for example, what if I have an Hibernate interceptor that won't let me insert an address without 1 or more Addresses
The main problem here, I believe, is that f I insert a row leaving a not null column empty most databases won't wait until I try to commit the transaction to say "integrity violation" and rollback my changes... therefore it is impossible to write partial data just for the test that I have in front of me, but... could I automatically generate consistent inserts using as a source just the integrity rules at the database level... and the select that I want to test?
I think it can be done... the question is..
What is the algorithm to generate the inserts needed to satisfy an SQL select statement?

Thursday, May 31, 2007

WebBrowser + Embedded WebServer + Embedded DataBase = Google Gears

Hi!

Today I found out about a new Google project, Google Gears... a new browser plugin... that adds an SQL database and a local, only for that browser on that machine "Web Server" (oh, and an external WorkerPool for threaded asynchronous proceseses)...

So... now the that WebBrowser has an SQL database... a Worker Pool ... and a WebServer... it can run disconnected applications... you can save you emails locally... or your blog entries... or your RSS (I believe that is what google reader does)... WebApplications are now... Desktop applications... (or RIAs as they are called now).

So... now... what is the real advantage of  a RIAG (a RIA with "Google Gears") vs a Desktop App? Well, lets look at its features.. the RIAG... is slower (interpreted)... needs a plugin like Flash to do  real graphical stuff... it can't access anywhere on disk  (we could say it has its own SQL based filesystem)... therefore it is still not better for graphically intensive applications (I don't see a Photoshop or 3dStudio killer in the near future) ...  but could be a nice idea for desktop like stuff (for example a disconnected mail reader, or perhaps even a disconnected wiki). But wait... we already have disconnected mail readers...  (well, but they are not multiplatform.... mmmm... wait, Thunderbird IS multiplatform... and of course we have Java to create those multiplaform mail readers if we need to do so)... okay, but we can create a multiplatform Office like system (yes, a revolutionary idea... wait... what about OpenOffice?) and of course building an Office in a technology like JavaScript will make it really fast in standard hardware (like the very successful Java Office built by Corel a few years ago... wait... never heard of it? mmm, maybe it wasn't that successful... I wonder if that was because Java was really slow on hardware back then... )

Of course... none of that is going to stop Google Gears... people are just hypnotized with building stuff in the "web way" (even if can be done easier on the Desktop)... the way I see it.. with all this stuff, as the "thin client" of the WebBrowser becomes a "rich client" it is also gaining weight, becoming fat, becoming a fat client... so... by this logic... adding a plugin to all available browsers... it is better than a Java applet... but I can't find a logical reason for that... the new RIAs are just applications that use the browsers as the platform.... the  difference with windows applications? that there are many different browsers following the HTML/JavaScript standard, and only 1 windows (of course every browser follows the standard on its own particular way)... the difference with Java? (there isn't, but RIAs are slower... and sliced in pages... that seem to be faster to download... but in fact they consume even more bandwidth than classic fat clients with their proprietary binary protocols ), perhaps the key here is the "openness" of HTML & XML and JSON as protocols for communication (but that can also be done in Java, or in .NET & Mono)

So...  I just don't get it... what it is so great about adding a database plugin to the browser? by following this path all that we are doing is reinventing the wheel (everything that can already be done outside the browser is being re-built inside it... until RIAs become as Fat as Fat-Clients... and then someone else invents the new Thin-Client... and the story repeats again).

I guess the software industry is really, really iterative... we need to go back to an re-try stuff from the previous iteration... to realize it wasn't such a bad idea... enhance that idea... and from there, realize that the idea from 2 iterations ago, was the solution for the drawbacks of our current problems...

Wednesday, May 09, 2007

Project OpenJFX

Java counterattacks? The other day I posted that Silverlight and Flash might be going to kill Java... well Java is figting back:

JavaFX is a new family of Sun products based on Java technology and targeted at the high impact, rich content market.

JavaFX Script is a highly productive scripting language that enables content developers to create rich media and content for deployment on Java environments. JavaFX Script is a declarative, statically typed programming language. It has first-class functions, declarative syntax, list-comprehensions, and incremental dependency-based evaluation. It can make direct calls to Java APIs that are on the platform. Since JavaFX Script is statically typed, it has the same code structuring, reuse, and encapsulation features (such as packages, classes, inheritance, and separate compilation and deployment units) that make it possible to create and maintain very large programs using Java technology. See the FAQ for more information.

I am very impressed with the demos in the site, and the way less verbose way to describe interfaces (when compared with traditional Java Swing code, and I am thinking it could even be a threath for XAML & XML, some people on the net believe that XML is the poor man's parser, and that it is being overutilized to create stuff that should be implemented as an specific language... well, JavaFX is not XML... is this the start of a new trend?), I was also very exited to see how easy is to add animation to Java 2D application with this new API (everything that can be done with Flash will be possible... and maybe even more...). Now... the question are:

  • Will Sun release a "UI Designers Pack" for Netbeans that will be pretty much something like Microsoft Expressions for Java?
  • Could OpenJFX be adopted by projects like OpenLaszlo?
  • Is using JavaScript like languages the new trend?
  • Will JSON stuff become the new poor man's parser?

Thursday, May 03, 2007

Eclipse... Is NOT an IDE

Okay... have been trying to use Eclipse 3.2 like an IDE all week... that failed miserably...

  • VisualStudio.NET is an IDE
  • Borland Developer Studio is an IDE
  • NetBeans is an IDE
  • IntelliJ is an IDE
  • FlexBuilder (an Eclipse plugin) is an IDE
  • JBuilder (an Eclipse plugin) is an IDE

But... Eclipse... Eclipse... is a PE... "Plug Environment", NOT an IDE: Integrated Development Environment.

After you add JDT to it can be considered an IDE... if you only build Console tools (command line applications) but, if you want to build anything more complex than that... then  JDT  is a very limited IDE.

Yes, you can add lots of plugins to Eclipse... and make it become JBuilder... (like Borland did or as Macromedia did with FlexBuilder), but the thing is, that it is JBuilder (the plugin) the thing that IS the IDE, Eclipse is just the PLATFORM for the IDE..., saying that Eclipse is an IDE it is like saying that Windows is word processor... or graphic design application... or why not, Windows is a IDE! (Of course, that is crazy... well saying that Eclipse is an IDE is crazy... comparing it to any real IDE is crazy...) Eclipse is a PLATFORM, and you can build an IDE on top of that, but, the quality (and INTEGRATION) of the free available plugins in Eclipse Callipso,  in my opinion is not enough to call it an IDE

Netbeans is a great IDE, the best OpenSource IDE for Java for Swing or Web or J2EE applications, Eclipse is NOT and IDE. Period.

(I guess this is my first rant in a blog)

Monday, April 16, 2007

Swing: Dying between Silverlight & Flash?

So... Now Microsoft has Silverlight and tools like Expressions to create really good looking animations and User Interfaces... and a really small 1Mbyte plugin that works in Windows & Mac OS X...

Adobe has Flash... and Flash CS3 & Flex to create really good looking animations and User Interfaces.... and a really small around 1 Mbyte plugin... that works... well... everywhere (Windows, Mac OS X, and yes, Linux)

And Java... well... has Swing and SWT... neither of them has a a tool too easily create really good looking animations and User Interfaces... (Mattise is not bad, but it doesn't compare with Flash CS3 or Expressions), the JRE is huge, Swing and SWT have better integration with current platform UI than ever before... (but, creating really good looking UIs, like those possible with Flash & Silverlight with just the help of a designer... well.. it is just not possible)

So...the Java vs .NET war.... is now the Silverlight vs Flash war? or now we have 3 powers?

Saturday, May 13, 2006

Object Relational Mapper vs Business Entity Manager

In my opinion the best two are Hibernate and EOF, I think a mix between them could create "the ultimate" Object Relational Mapper... or the ultimate Business Entity Manager...?

EOF (the best BEM?)

Hibernate (the best ORM?)

An interesting topic for analysis could be the limits between an Object Relational Mapper and an Business Entity Manager. Some people think that Hibernate shouldn't evolve to become more like EOF, because it should aim to do one and only one thing (be the best ORM) and other people think that it would be nice to have the services that an Business Entity Manager gives you:
  • automatic connection handling
  • automatic transactions handling
  • multiple undo levels
  • real nested transactions
  • client and server objects
  • distributed non-transactional lazy loading
  • etc,etc

There are also some people that think that a Business Entity Manager is more closer to the MDA "objective", so I think it is important to take a look at (Using Borland's ECO to develop model-powered applications for .NET) an many related articles, the specially interesting thing for me about ECO is its OCL support (that can be used, for example to configure constraints that help ensuring that only consistent data is saved into the database... it is kind of a Design by Contract for the domain model)

IMO the Active Record pattern is getting too much popularity (perhaps thanks to Ruby , but I think it leads to an anemic domain model ) and Domain Model based in Business Entity Managers is not as popular (thanks to the problems in EJB1 and EJB2) but it is important to remember that EJB is not the only way to build an Business Entity Manager, there are ways to build Business Entity Managers that are a lot more lightweight and user friendly than EJB, (just investigate more about EOF and ECO)

Requirements Analysis: Negative Space

A while ago, I was part of a team working on a crucial project. We were confident, relying heavily on our detailed plans and clear-cut requi...