Archive for October, 2006

hibernate and component querying

Wednesday, October 18th, 2006

Well here is some interestingness with querying for components using the 3.2.0cr5 version of hibernate. (FYI using accessor methods is the way the code was actually written. Direct references to properties in this example used just for clarity.)

Components in hibernate are objects that are represented in the database as a subset of columns with in their container. For example:

In the Java code:

class Foo {
    public Peanuts peanut;
    public int foo1;
    public Bar bar;
}

class Bar {
    public Peanuts peanut;
    public int bar1;
}

class Peanuts{
   public Foo foo;
}

     <class name="Foo">
         <many-to-one name="peanut"/>
         <property name="foo1"/>
         <component name="bar">
             <property name="bar1"/>
         </component>
    </class>

will result in a database table ‘FOO’ that looks like:

PEANUT, FOO1, BAR1

Now the problem I have is that I wanted to retrieve Bars. Using a PostLoadEventListener looking for Foo’s, I wanted to fix up the reference Bar had to Peanuts, like this:


    public class FooPostLoadListener implements PostLoadEventListener {
        private static final long serialVersionUID = 1L;

        public void onPostLoad(PostLoadEvent event) {
            if ( event.getEntity() instanceof Foo) {
                Foo ts = (Foo)event.getEntity();
                ts.bar.peanuts = ts.peanuts;
            }
        }
    }

But of course the entity being loaded is a Bar not a Foo.

Now there is the possible use of the <parent> with in the Bar component. However, that means that a publically visible method is available that should never be used. (<parent> doesn’t have the ability to set the property using ‘field’ access).

The next step was creating a setParent(Foo) and a Foo getParent() on bar:


class Bar {
    public Peanuts peanut;
    public int bar1;
    public void setParent(Foo f) {
       peanuts = f.peanuts;
    }
    public Foo getParent() {
        return peanuts.foo;
    }
}

     <class name="Foo">
         <many-to-one name="peanut"/>
         <property name="foo1"/>
         <component name="bar">
             <parent name="parent"/>
             <property name="bar1"/>
         </component>
    </class>

Now this doesn’t work because the setParent() method is called before Foo has any of its fields instantiated. This actually makes a lot of since otherwise when you are reading in the result set, there is a lot of juggling to get the data ordered in the right way for what the code needs.

Unfortunately, inspite of all this rework at the end of it all, querying for a component returns the component without the parent Foo set. I was hoping that accessing the parent Foo via a call to getParent() would trigger a load of Foo but it doesn’t.

equity splitting

Friday, October 13th, 2006

So I read this really interesting blog by Noam Wasserman. As someone who is trying to make a go of his first company, one of the problems I face is how to give up equity in a way that makes sense. That is to say the right amount but not so much that there is “nothing” left for the original founders.

I have determined that percentage ownership is a very dangerous game .. one that I will not play. From the beginning, equity will be in terms of number of shares. The problem with percentage ownership is that at each funding event the percentage owned will drop. This creates the feeling of losing money or control. This tool is a good visualization tool.

I have decided that I am going to take my 100% ownership of nothing and convert it into two piles of stock. The smaller pile will be that which I intend to keep for myself. The other (much larger) pile will be that which I intend to distribute to investors and employees. In this way I don’t become trapped into thinking that I am “giving away my company”.

rail speed records and the effect on airplane travel

Wednesday, October 11th, 2006

September 2, 2006 Siemens used the recently-opened Nuremburg-Ingolstadt high-speed line in southern Germany to set a new world record for an electric locomotive. The Austrian Federal Railways class 1216 locomotive reached 357 km/h or 221mph

December 2, 2003 a manned Japanese maglev train set a new world speed record of 581km/h or 361mph on a test track.

In 1990, a TGV train (which does not use a locomotive) reached 515.3 kph or 320.2 mph

The Boeing 737 is the most common plane for short-distance hauls of less than 400 miles (50% of all flights in the U.S. are less than 400). The top speed of a Boeing 737-900 is 624mph.

Using the TGV speed record, over a straight-line distance of 400miles, 737 has a time advantage of (at best) (75min – 38.5minutes) of only 36.5 minutes. This is ignoring the realities of landing/take-off/taxiing on runways.

It is no wonder that according to the International Railway Journal October 2006 issue:

Air France-KLM says that the opening of the Paris-Strasbourg high-speed line next year could slash the number of flights on the route by half .

The airline expects around 500,000 passengers, equivalent to half of its current business on the route could be lost to rail. Air France will maintain its four flights per day between Strasbourg and Paris Charles de Gaulle airport but it will cut a third of its service to Paris Orly when TGV Est opens in July 2007.

what is the rail advantage in CO2 emissions over an equivalent air flight?

Tuesday, October 10th, 2006

This week there was a news release by the Eurostar company about the comparative emissions of a Eurostar trip vs. the same trip via airplane.

each passenger on a return flight between London Heathrow and Paris Charles de Gaulle generates 122 kilograms of CO2, compared with just 11 kilograms for a traveller on a London-Paris return journey by train. A round trip between London Heathrow and Brussels airport generates 160 kg of CO2 per passenger, against only 18 kg of CO2 for a return journey by rail.

The distance between London and Paris is 495km or 298 miles via car (and probably close to what the train distance is). But the plane trip is shorter since the Chunnel is to the north of the straight-line route. The straight-line distance is 214 miles between Heathrow and Charles de Gaulle Airport. Google map of car route here. So the train pays a route penalty but still manages to easily beat the airplane.

Airplane: 0.57 CO2kg/mile. Train is between 0.037-0.05 CO2kgs/mile.

For the London to Brussels route, the car route is 418km or 251 miles. The Chunnel looks to be inline with the most direct route. The straight-line distance is 219 miles. Google map of car route here.

Airplane: 0.73 CO2kg/mile. Train is between 0.07-0.08 CO2kgs/mile.

Original new release reported:

Passengers who fly between London, Paris and Brussels generate ten times more emissions of the greenhouse gas carbon dioxide (CO2) than travellers who go by rail, according to a study commissioned by train operator Eurostar.

The research shows that each passenger on a return flight between London Heathrow and Paris Charles de Gaulle generates 122 kilograms of CO2, compared with just 11 kilograms for a traveller on a London-Paris return journey by train. A round trip between London Heathrow and Brussels airport generates 160 kg of CO2 per passenger, against only 18 kg of CO2 for a return journey by rail.

Eurostar claim the figures are the most detailed ever produced and are based on actual passenger numbers, exact distances of rail and air routes, actual aircraft types in use on different routes, and the mix of electricity sources used by the company’s high speed trains.

Eurostar chief executive, Richard Brown, said: “Travellers are increasingly demanding factual information about the environmental impact of their travel plans, and what they can do to reduce emissions of gases which are causing climate change.”

With journey times between London and the Continent set to be cut by 20 minutes with the opening of the line into St Pancras in autumn 2007, Eurostar say the environmental advantages of using their service will be further increased. The research also shows that travelling by high-speed rail will generate even less CO2 per passenger in future years, due to increased supplies of renewable energy and UK policies to reduce CO2 emissions.

notes on building a “Super Railroad”

Friday, October 6th, 2006

I got this information from a Sierra Club email list I am on that has some useful technical information about how to build a really first class railroad. This comment was posted by Clyde L. Anderson, Treasurer, Nebraska Chapter – Sierra Club [email address: remove spaces: Clyde L Anderson (near somewhere around) Cox.net ] in response to a discussion about the secretly proposed NAFTA “super-highway”, discussed here. I thought others would be interested in the technical details.

Some key technical data that I found interesting is highlighted.

Using a combination of the best rail routes between Laredo and Kansas City, we could build a Super Railroad with a capacity exceeding the capacity of the proposed NAFTA Super Highway while occupying only a 125-ft right-of-way. (Modern railway lines are built on 25-ft centers, but most of our existing multiple-track routes were built decades ago on 15-ft or smaller centers. If track centers are at least 25 ft, the FRA allows trains to pass track maintenance operations without shutting down the maintenance work.)

What’s need is a well-engineered double-track railroad with modern signaling system, universal crossovers every 10-15 miles, 10,000-ft sidings every 15 miles (for slower trains to pull off the main lines to allow faster trains to overtake them), and 4 main tracks through major terminals like San Antonio and Ft. Worth. Grade separations would also be needed where the NAFTA Railroad crosses other major rail routes, such as the Sunset Route in San Antonio.

Think of the energy savings of using trains instead of trucks. If the NAFTA Railroad was electrified, look at all of the energy options available to propel the trains — solar, wind, biofuels, etc. ) [China has a goal of electrifying 2,000 km per year of its rail routes as a means to reduce its dependence on oil.]

The closest thing the U.S. has to a super freight railroad is Union Pacific’s busy route across Nebraska which handles more tonnage than any other rail route in the world. The huge terminal at North Platte is also the world’s largest. Unfortunately, the route is not electrified, so North Platte has the world’s biggest railroad fueling facility because all of the trains are powered by diesel-electric locomotives.

How to do redirects in tapestry

Friday, October 6th, 2006

How to do client-side redirects-after-post (taken from someone else’s sample code):

public abstract class somePage extends ATapestryPage {
   @InjectObject("engine-service:page")
   public abstract IEngineService getPageService();
   public ILink theListenerMethod() {

/*
Redirect to next page. SECURITY NOTE – do not use simple page activation Instead, we return an ILink because that instructs Tapestry to do a redirect-after-post. Redirect-after-post protects against a security vulnerability in which a user may log in without a password simply by using a browser that has been logged out, then using the Back button to go back to the first screen after the login screen and pressing refresh. Without redirect-after-post this would re-post the login info and they’d be logged in!
*/

      ILink redirectTo = getPageService().getLink(false, WelcomePage.PAGE_NAME);
      return redirectTo;
   }
}

To do a server-side redirect, throw a org.apache.tapestry.PageRedirectException that was created with the desired page to redirect to.

Hibernate nastiness using the one-to-one mapping.

Tuesday, October 3rd, 2006

Hibernate nastiness filed as bug HHH-2128. When reading this please notice that this situation arose from the most minimal definition. Using the ‘defaults’ is what caused this issue!

Steps:

  1. define two classes (Primary, Secondary) that have a one-to-one relationship.
  2. use the native generator to generate a primary key for each.
  3. save a primary with no assigned secondary object.
  4. save another primary with a secondary object.
  5. retrieve the first primary and it will have the secondary object saved in previous step.
  6. retrieve the second primary and it will have no secondary object.

Talk about ouch!

Hibernate’s event system

Sunday, October 1st, 2006

So I just had an interesting realization, Hibernate uses various default listeners in it’s poorly documented event system to do all of its persistence work.

For example, saving an object through a Hibernate Session object quickly goes to the Session.fireSaveOrUpdate, which by default calls DefaultSaveOrUpdateEventListener. DefaultSaveOrUpdateEventListener does all the heavy lifting of checking to see if the object legal to save prior to actually saving the object.

These default listeners also invoke interceptors as briefly described in section 12.1 of the 3.2.0.cr4 manual.

This means that if someone starts adding event listeners of their own, they better make damn sure that they add in Hibernate’s as well. Otherwise Hibernate will very quietly do nothing!

I filed this bug in the hopes that the documentation would get changed:

Please add this (or equivalent) to the bottom of section 12.1. (Interceptors):

===========================================
Interceptors are invoked by Hibernate’s default event listeners. For example, interceptors’ onSave() method is invoked by Hibernate’s DefaultSaveOrUpdateEventListener
===========================================

Please add this (or equivalent) to the bottom of section 12.2 (Event System):

===========================================
When changing the event listeners be sure to keep the various Hibernate default listeners. These listeners actually perform much of Hibernate’s persistence work, including invocation of the interceptors. Without those default listeners, Hibernate will quietly do nothing.
===========================================

Event Default Hibernate EventListener Interceptor method called by default listener
PreLoadEvent DefaultPreLoadEventListener onLoad
PreInsertEvent
(return true to veto the insertion)
DefaultSaveOrUpdateEventListener
(on HSQL EntityIdentityInsertAction – which gets the generated id after the insertion)
?
SaveOrUpdateEvent DefaultSaveOrUpdateEventListener onSave
PostInsertEvent
(called even if the PreInsertEvent vetoed the insertion)
DefaultSaveOrUpdateEventListener ?