Dave Harris

General ramlings about Java

How to access the Spring WebFlow from Spring MVC September 1, 2009

Filed under: How-to, Spring — daveharris @ 5:09 pm

I recently came across a problem in a Spring Webflow based application where I needed to have one page as a standard Spring MVC page.  I needed to write a PDF file to the actual http response and I’m not allowed to do that in WebFlow.

So I defined a standard Spring MVC Controller and URL Mapper to complement my existing Flow Controller:

<bean id="PDFPageController" class="controller.mvc.PDFPageController" />

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
    <props>
      <prop key="/index.htm">/index.htm</prop>
      <prop key="/pdf.htm">PDFPageController</prop>
    </props>
  </property>
</bean>

<bean name="/index.htm" class="org.springframework.webflow.executor.mvc.FlowController">
  <property name="flowExecutor" ref="flowExecutor" />
  <property name="defaultFlowId" value="main" />
</bean>

Then inside the MVC Controller (which extends AbstractController), define a method called accessFlowScope like below:

private void accessFlowScope(HttpServletRequest request, HttpServletResponse response) {
  // Gain access to the Spring Web Flow context
  FlowController controller = (FlowController)getApplicationContext().getBean("/index.htm");
  FlowExecutionRepository repository = ((FlowExecutorImpl)controller.getFlowExecutor()).getExecutionRepository();
  FlowExecutorArgumentHandler handler = controller.getArgumentHandler();
  ExternalContext externalContext = new ServletExternalContext(getServletContext(), request, response);

  // Make sure we have a flow execution key.
  if (handler.isFlowExecutionKeyPresent(externalContext)) {
    try {
      // Get access to the variable stored in the context.
      ExternalContextHolder.setExternalContext(externalContext);
      FlowExecutionKey flowExecutionKey = repository.parseFlowExecutionKey(handler.extractFlowExecutionKey(externalContext));
      FlowExecution flowExecution = repository.getFlowExecution(flowExecutionKey);
      Object variableInFlowScopeObject = flowExecution.getActiveSession().getScope().get("variableInFlowScope");
    }
    catch(Exception ex) {
      logger.error("Error when accessing flow scope from MVC", ex);
    }
    finally {
      ExternalContextHolder.setExternalContext(null);
    }

  }
  else {
    logger.error("Handler did not have flow execution key present");
  }
}

This can then be called from your handleRequestInternal method of the MVC controller:

public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)

All that is required now is to call from the Webflow view jsp into the MVC controller.  I had to do a horrible iframe like so:

<iframe id="pdf-view" src="pdf.htm?_flowExecutionKey=${flowExecutionKey}" height="100%" width="50%">
  I'm sorry, iframes are not supported by your browser, upgrade to <a href="http://getfirefox.com">Firefox</a>
</iframe>

Now you can pull out whatever values you require from the many scopes (request, flash, flow, conversation) and use them in your MVC controller to do stuff.

NB: All the code is used pretty much verbatim from http://www.ervacon.com/products/swf/tips/tip1.html, but it doesn’t say to add the flowExecutionKey onto the URL, which is the part I was missing and thiking that it wasn’t working correctly.

 

SVN Dump Parts of a Repository August 5, 2008

Filed under: How-to — daveharris @ 5:02 pm

Today at work at Fronde I needed to create a dump of a ‘project’ inside a repository.  Our SVN setup is to have one repo per team and then within there have a folder for each client/project.  In this case I was providing the backup to a client so it was vital that I gave them just their code and not the whole repo.

So my SVN repo was like this:

/
  teamA
    clientA
    clientB
  teamB
    clientC

To dump the clientA history into a portable, re-creatable format, I used svnadmin dump, like this:

svnadmin dump [path to repo] > C:\Repo.svn-dump

Which creates a dump of the entire repository at C:\Repo.svn-dump.  This took about 10 mins with 1000 versions and used 100% so it would be best to perform this outside of normal work hours.  You have been warned!

I then used svndumpfilter (tutorial) to filter just for the ClientA folder (see folder tree above):

svndumpfilter include ClientA < Repo.bak > ClientA.bak

This didn’t take very long and at the end I had a full svn repository that could be re-created anywhere.  To prove the point I installed SVN on my mac and created the repository.  I then loaded the dump file into it and it worked beautifully ;)

svnadmin create /Users/Dave/ClientA
svnadmin load /Users/Dave/ClientA < ClientA.bak
mkdir /Users/Dave/ClientA-checkout
svn co file:///Users/Dave/ClientA clientA-checkout/

Now that you have checked it, you can delete the whole repo backup file (mine was massive) Repo.svn-dump in my case.

Easy as pie once you know how.  The fact that you can’t specify the filter at dump-time is non-intutative, clunky and frankly a waste of space.  However if you only need to do it once it works and produces a very nice result.  Open Source and Open Standards FTW ;)

 

MySQL Backup Script May 29, 2008

Filed under: *nix, How-to — daveharris @ 12:53 pm

This is a convienct place for me to put stuff that I (or you!) may need in the future. While working at Fronde I wrote this little backup script for the wiki we were using. It is meant to be run on a cron job daily. It makes daily backups and every Friday copies that backup to elsewhere (preferably off disk or off site) and deletes that past week’s daily backups. Before I get flamed in the comments I know that there is AutoMySQLBackup but that is huge and very complicated and I wanted to write it myself! :P

#!/bin/bash
# Wiki Database backup script

# Set up the variables
DB_USERNAME="username"
DB_PASSWORD="password"
DB_HOST="localhost"
DB_NAME="wikidb"
BACKUP_DIR="~/wiki_backups"
ARCHIVE_DIR="~/wiki_backups/archive"
DATE=$(date '+%Y-%m-%d')
OUTPUT_FILENAME="${BACKUP_DIR}/wiki_${DATE}.sql"
ERROR_FILENAME="${BACKUP_DIR}/error_log_${DATE}.txt"
ARCHIVE_FILENAME="${ARCHIVE_DIR}/wiki_${DATE}.sql"
MYSQLDUMP="/usr/local/mysql/bin/mysqldump"

# Dump the wiki db to a file
${MYSQLDUMP} -ac --add-drop-table -u ${DB_USERNAME} --password=${DB_PASSWORD} \
    -h ${DB_HOST} -r ${OUTPUT_FILENAME} ${DB_NAME} &> ${ERROR_FILENAME} 

# If there are errors, then do stuff here...
STATUS_CODE="$?"
if [ ${STATUS_CODE} = 2 ]; then

fi

# If the error log is empty, delete it
numLines=$(cat ${ERROR_FILENAME} | wc -l | sed 's/\ //g')
if [ ${numLines} = 0 ]; then
  rm ${ERROR_FILENAME}
fi

# If today is Friday, put a weekly backup in archives and delete daily backups
if [ $(date +%A) = "Friday" ]; then
  cp -f ${OUTPUT_FILENAME} ${ARCHIVE_FILENAME}
  rm ${BACKUP_DIR}/*.sql
  #echo $(cat ${BACKUP_DIR}/wiki_${DATE}.sql)
fi
 

Home Sweet Home May 18, 2008

Filed under: San Francisco — daveharris @ 12:44 pm

Well I arrived safe and sound in Wellington this morning.  It was nice to hear kiwi accents again!  It was also nice to go through NZ customs without having to take my shoes off!!!

I had a fantastic time but it is always nice to get home.  Unfortunately I left in 30 degree heat and arrived in Auckland at 5am at 7 degrees, ouch!

Unfortunately I couldn’t get an iPhone as they were all sold out from the Market St Apple Store and the online store.  The 3G iPhone must be just around the corner…  The consensus is that it will be announced that the keynote of WWDC which starts early June (at the Moscone Centre!).

I’m not really looking forward to going to work tomorrow… Speaking of which I should pimp Fronde.  If you want application development, visit http://www.fronde.com

I have added more photos to the Yosemite and Cycling albums also

Thanks for all your comments and I will see most of you soon…

 

Two hot days May 18, 2008

Filed under: San Francisco — daveharris @ 12:35 pm

The last two days in San Fran were unbearably hot, upwards of 36 degrees!!  On Thursday I took a nice ride on a catamaran.  The photos are here.  That made the heat bearable, but typically there wasn’t really enough wind!!  No one knew what to do with themselves so most were lying under trees in the park…

On Friday I took the tram on the steepest line, California Street.  I then had a look around Chinatown.  SF has the biggest Chinatown outside of China itself.  There were heaps of little stores selling all sorts of things, I could even buy a Samurai sword, I was kinda tempted.  Everything was really cheap, about half price of the other stores on Fisherman’s Wharf!  I then went up to the famous Castro district which is famous for being the gay and lesbian capital of the world.  The day before, California made it legal for same sex couples to marry (to much opposition) and so the streets were decorated and people were still celebrating.  But it was again about 35 degrees so it was too hot to do anything.  It seemed that most people were sitting under the trees in Union Square, or shopping in the air conditioned boutiques!  The photos are here.

I flew out Friday night SF time…

 

Yosemite May 16, 2008

Filed under: San Francisco — daveharris @ 5:34 am

So after yesterday’s exploits on the bike, I really didn’t feel like getting up at 6am to go to Yosemite, but I knew that I would be thankful later!

We left at about 7.30am and arrived at Yosemite at 1.30pm, a long trip. We parked pretty much right under the falls and stepping out of the a/c couch, the heat hit like it does getting off the plane in Singapore or something. It hit 32 degrees there because it is more inland, it would’ve got much higher but we were at 5000 feet above sea level! I can’t describe in words how awe inspiring this place is, my photos definately can’t do it justice but here they are. I took about 200 photos, so these are just a sample.

Nothing can do this place justice. The height of El Capitan is just astonishing, and people actually climb up there (the shortest time is 4 days!). We stopped and looked at some smaller waterfalls up close on the way and then a good viewing spot for El Capitan and Bridalveil Falls. We had 3 hours on our own after we arrived and I spent most of that at the largest Yosemite Falls. There was a track to the top that took 3 hours that I wanted to do but didn’t have enough time or energy after yesterday! They have a free shuttle service to take you around the park and the visitor centre had a good video. I couldn’t resist some professional photography so got a large postcard of the falls.

They are going a lot of work on the road and so we were stuck in traffic for about an hour or so. Thankfully we had air conditioning. The driver could tell we weren’t getting anywhere fast se he took us up to Inspiration Point where you can see all the major attractions. He said that it was probably the most photographed spot in the US if not the world.

As it happened there was a kiwi couple on the tour also (yes, its a very small world) so we took each others photos so there are more of me this time ;)

I got back to the hotel at about 10.30pm so it was a very very long and hot day. As we crossed the Oakland bridge at about 10pm, it was still 28 degrees!!!!

So it is now Thursday morning and I finally have internet access so I can post this and the photos. It is meant to reach about 35 degrees here today. It is very hot already so I am doing to find a tree at Fisherman’s Park and get some reading done and then go on the yacht this afternoon. I need a break, its been a very busy few days!

Well last full day in SF, and its a hot one! ;)

 

Biking to Sausilito (and beyond) May 16, 2008

Filed under: San Francisco — daveharris @ 5:11 am

This morning the weather forecast said that a heat wave was coming so I had to shuffle my plans around. I was planning to go to Yosemite on Wednesday and then do the biking on Thursday but it is meant to be 30+ degrees on Thursday so I went today instead.

As I said before, there are many people that ride to Sausiltio and catch the ferry back to San Fran. I thought that was winmping out a little to be honest, and I was going for a ride not to see Sausilito. I managed to find a place that hired out road racing bikes so there I was riding down Fisherman’s Wharf (on the (my) wrong side of the road) headed for the GG bridge. Photos are here. I looked at the map and found that Sausilito was only 13km but Tiburon was another 13km round the coast. There was a ferry headed back from there if I felt tired, but I wanted to ride there and back. Even though the heat wave hadn’t officially started yet, the temperatures were easily hitting 28 as I rode into Tiburon, completely wasted. I wasn’t sure exaclty where I was going and was following the cycle way hoping I would make it.

Speaking of cycleways, they are everywhere here and really well used. They are nice and smooth too which is a change from the roads which are even worse than ours. And I was riding this awesome racing bike so I felt every single bump!

Anyway, I eventually arrived at Tiburon and found a sleepy Italian town just waking up at 1pm. I found this awesome Italian panini place and after cooling down I decided that catching the ferry back was wimping out and I had like 6 hours to make it back. The temperature got even hotter though, one side said it was 33 (of course everything is in Farenheit so 101 degrees doesnt really mean anything to me, but 90 is 30 and HOT!). I did contemplate getting the ferry from Sausilito, but I only needed to cross the bridge and I was basically there. Being the stubourn rider (thanks Dad!) I rode on and up the massive hill to the bridge. I was about ready to collapse when the freezing (and I mean freezing) wind off the sea arrived at the entrance to the bridge. So that is why I look so wasted here. I got back in plenty of time and bought a tshirt saying I had ridden across the GG bridge! I had a speedo too (but it was all in miles was was kinda useless) and my total was 42 miles (68km) .. so thats why I was so tired. Not sure where the 13 + 13km came from (yes that was km’s not miles)

I got a pizza from this awesome little places up the road called Uncle Vito’s and ate it all in one sitting and was almost too tired to sleep. I think I overdid it … ooops! ;)

Photos are here

 

Alcatraz May 13, 2008

Filed under: San Francisco — daveharris @ 5:39 pm

Well today was Alcatraz day and what a stunning day I had to see it. From the photos it may look warm and sunny, but that wind is cutting, especially in the middle of the harbour! I definitely feel at home here, it is very like Wellington with steep hills, windy and thriving, forward looking city.

Everything is very expensive here though, well almost everything. It’s expensive even when I forget to convert it to $NZ. Like a bag of chips is $4 and a Ben ‘n’ Jerry’s icecream is $4. But other things like Alcatraz were remarkably goof value. It was only $24 for a 20 min boat ride each way, a free audio tour (more on that later), a documentary explaining the history and a guided tour around a certain section if you were lucky (which I was). Food seems very expensive here I guess, but the hostel puts of great evening meals for $5 (tonight was a roast!) and a free breakfast of the typical American bagel so I can’t complain.

Anyway, onto Alcatraz. I caught the boat out after lunch and arrived at the perfect time, one of the wardens was about to give a guided tour explaining the 3 major escape attempts … the best bit!!! He was really good and had a massive crowd. He showed us some bits that were off limits without a guide so that was sweet. I have like 200 shots so there are plenty more than went up on the website. Jeff, I am loving your camera ;) . So he talked about the buildings on the way to the location of the escape attempts which was god because of its varied history, it’s hard to make out what is from what era. First was the establishment of a military fort during the 1850’s gold rush. Then it became the prison from 1930-60’s and it was then taken over by native American Indians, who seem to be in a very similar state as our Maori in terms of land being taken and slowly being granted back. The American Indians occupied it for over a year before being captured by the Government.

But the prison is the really interesting bit. After explaining how some escapee’s planned to get out we walked up to the top where the main cell block is. We were issued with little audio players and headphones that we could control. The thing that got under my skin was the language options were American, Chinese, Gernan……. American??????? There is no such language!!! Anyway, these players were really awesome. There was a narrator telling you what you were looking at and then former inmates spoke about what life was like. So much better than reading about it, and you could go your own pace, which meant plenty of stopping and starting for photos! We were introduced to the cells and then taken around and told what went on in each section or highlighting events such as escape attempts etc. One really good bit that I would’ve totally missed was speckled marks on the concrete floor. These were caused by grenades thrown into the prison by the guards during a time when the prisoners overran the guards inside. The cells are tiny, 5 feet but 8 feet by 7 feet tall. I could touch the walls on either side! Its an impressive and spooky place, especially hearing about that a murder happened in the cell you are looking into and the bullet mark can be seen in the wall! There are night tours you can do, noooo thanks!!! The solitary confinement cells were even worse. They had nothing in them al all apart from a grate in the floor for you-know-what, the cells were even smaller than normal, the windows were left permanently open so the freezing air from the bay comes straight into the room and you are locked behind two doors with no light. By law, they had to provide them light, but they turned them off for more punishment. As the saying goes “Break the rules and go to jail, break prison rules and go to Alcatraz”!!!

We then were showed the cells of the escapee’s that made dummy heads and made the inflatable raft out of rain coats. They managed to get the grate off the wall and dig through the concrete at night FOR A YEAR. They made it into the utility shaft between the cells and up onto the roof. The alarm was raised in the morning and all that was found was the raft floating in the bay. Some people think that they made it to South American (they did learn Spanish while inside) and they got away but the official Government line was that they drowned and their bodies went out to sea. Who knows!? Yet another mystery of Alcatraz. Mythbusters did a show on it, but I can’t remember if they said it was possible to do or not. their plan was ingenious though. The best bit is that they learnt how to make the raft from a Popular Mechanics magazine that was in the prison library …. ooooops!

We did a tour of the guards quarters and then I walked around the outside to get to the playing field. As you can see in the photo, you can see the Golden Gate clearly from there, I can see why they thought they could swim across the bay. And it’s such a short distance too, only 1.25 miles. But the water is freezing with strong currents. Speaking of which, the ranger guide who took us around actually swam across to the mainland last year without a wetsuit and did it in 45 mins. So it was possible to do it. But he had been training in the freezing water for weeks before hand!

The whole place is falling apart though. They have the same problem that we do where the salt water gets into the steel reinforcing and blasts the concrete apart as it rusts from the inside out. They are spending a lot of money to get it back in shape, but there is a lot to do with many layers of history. Whihc one do you restore it to?

So Alcatraz was a blast, exactly what I thought it would be. Spooky but exciting at the same time. It was packed though (even on a Monday) and everyone was at the same stage in the audio tour. It meant for some crushes at times.

I have having a hard time uploading these photos, the internet seems to be better sometimes than others. When they are done they will be at http://picasaweb.google.com/compnewbie/Alcatraz

I have booked the Yosemite tour for Wednesday and then biking to Sausilito on Thursday before flying back Friday night. Tomorrow I am going to go sailing on the yacht and go on the steepest cablecar line on California Street. Not sure what I’ll do Friday at this stage.

Hope you are all well and don’t spend all day reading my too long and detailled accounts!

 

To Buy or Not To Buy… May 12, 2008

Filed under: Mac — daveharris @ 5:29 pm

Of course I am talking about the iPhone.  I went into the awesome Apple Store (I’ll take some photos next time) and was about to buy one but they had sold out of the 16GB.

But then Dad said that it will be the same price in NZ.  So it’s $USD 499 + 2.5% foreign exchange credit card fee = $671.  Stuff was saying that it was going to be $700 in NZ.  So it’s not really any cheaper, if $700 is to be believed.  Has any more news come out or have Vodafone been tight-lipped?  I assume that the $499 includes the 8.65% sales tax…

So do you think its worth buying it here and haking it, or should I wait and get the official one and get too expensive 3G and GPS????  I’m sure there will be some awesome app that uses GPS and I’ll be annoyed it didn’t wait.

What should I do??? Sound off in the comments please ;)

 

Exploring San Fran May 12, 2008

Filed under: San Francisco — daveharris @ 5:18 pm

Well as I said this morning (my time anyway) I had a nice sleep in (finally).  I got a weekly pass to all transport and then walked down the pretty much deserted Market Street down to the Ferry Building through the Financial District.  From there I walked about half an hour down the road (under the Oakland bridge) to the baseball game between the Phillies and the Giants.  The number of people was really quite impressive, but the pitch seems really small.  I had almost no idea what was going on, who was winning and why people suddenly broke into cheers (and jeers) for no reason, but I had a good time nonetheless.  I then caught the train (a restored 1930’s streetcar) back to Fisherman’s Wharf and had an a chance to explore the little shops trying to sell everything for cheaper than the guy next door.  I’m def going to buy a San Fran hoodie, seems they are all the rage here!  Maybe something from the Giants too.  The amount of food they eat though is amazing.  It seems like most people go there to sit in the sun and eat (not that there’s anything wrong with that!).  I thought I had better try it and got a hotdog and coke, I was less than impressed….lol.

I booked my trip to Alcatraz for tomorow afternoon so I will have a nice lazy morning again.  I need to sort out the trip to Yosemite tomorrow too.  I then came back on a packed cablecar and because I was young and thin was allowed on hang on the side, true SF style.  Which meant that I got some great shots.  You can see them here.  The steepness of these streets is amazing!!

A nice relaxing day doing just what I wanted to, but lots of walking around.

Remember that I said that everything in America is bigger, it seems that it is also full of Starbucks.  The bus driver said yesterday that there are almost 2 per square mile.  walking around there seems to be one on every block, and they are always full of people… they must be making a killing!

Hard to believe I have been here for a week already, and only have 5 full days left :( .  I am going to book a trip on a sailing catermaran that goes around Alcatraz and under the Golden Gate later in the week.  Given the wind here it should be quite exciting.

The photos are uploaded http://picasaweb.google.com/compnewbie/ExploringSanFran, BTW I have put captions on all previous and current photos.

For those who saw it, yes Moscone was hit by the Norovirus, but thankfully I dodged that bullet again.  Maybe I am carrying it as it hit the scout jamboree too … hmmmmm!!

For those who care, Survivor is on TV and they just announced the winner, not sure where NZ tv is up to.

Tomorrow at Alcatraz should be good fun ;)