Saturday, June 05, 2010

Jersey JAX-RS and Freemarker

UPDATE

The example below uses sun specific packages. See here http://blogs.citytechinc.com/sjohnson/?p=32 for how to do it using jax-rs stuff only.


--------------------------------------------------------------------------------


I've been scratching around with various REST frameworks and I think I like Jersey. However, there's no native support out of the box for my fave templating superstar Freemarker.

So here's my first scratch at a ViewProcessor that supports Freemarker.

@Provider
@Singleton
public class FreemarkerViewProcessor implements ViewProcessor<Template> {

private final Logger l = Logger.getLogger(FreemarkerViewProcessor.class);
private final Configuration cfg = new Configuration();

@Context
public void setServletContext(final ServletContext context) {
// TODO - all of these should be in freemarker.properties.
cfg.setLocalizedLookup(false);
cfg.setTemplateUpdateDelay(0);
cfg.setTemplateLoader(new WebappTemplateLoader(context, "/WEB-INF/templates"));
}

public Template resolve(final String path) {
try {
return cfg.getTemplate(path);
} catch (final IOException e) {
return null;
}
}

@SuppressWarnings("unchecked")
public void writeTo(final Template template, final Viewable viewable, final OutputStream out) throws IOException {
try {
template.process((Map<String, Object>) viewable.getModel(), new OutputStreamWriter(out));
} catch (final TemplateException e) {
throw new IOException(e);
}
}
}


And here's how you use it...


@Path("/")
public class BananaResource {

@GET
@Produces(MediaType.TEXT_HTML)
public Viewable getBanana() {
final Map<String, Object> vars = new HashMap<String, Object>();
vars.put("name", "banana");
return new Viewable("/banana.ftl", vars);
}
}

Sunday, October 05, 2008

Grub error 22

Next time you turn on your computer and you get grub error 22, make sure you don't have a usb flash drive inserted. I'm guessing grub looks for it's files on flash drive if there's one inserted.

So it's a case of user error but software which presents a shitbox error code with no explanatory text should be incinerated.

Sunday, July 06, 2008

GridBagLayout help

I have to admit I quite like GridBagLayout. Not a lot of people admit to that I guess. However, I was recently impressed with MigLayout and wondered if I could hack up something similar for grid bag and make it a little more tidy. You may or may not agree; opinions as always are welcome.

Here's how you use it.

setLayout(new GridBagLayoutEx());
add(component1, "insets:2.2.2.2 fill:BOTH weightx:1.0 weighty:1.0 gridwidth:1 gridx:0 gridy:0");
add(component2, "insets:2.2.2.2 fill:BOTH weightx:1.0 weighty:1.0 gridwidth:1 gridx:1 gridy:0");
add(component3, "insets:2.2.2.2 fill:BOTH weightx:1.0 weighty:1.0 gridwidth:2 gridx:0 gridy:1");
add(component4, "insets:2.2.2.2 fill:VERTICAL weightx:0.0 weighty:1.0 gridwidth:1 gridheight:2 gridx:2 gridy:0");


The basic premise is that any property that GridBagConstraints supports can be set using property:value.

Here's the class......off you go...

// Copyright (c) 2008 Luke Biddell
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package uk.co.biddell;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.lang.reflect.Field;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class GridBagLayoutEx extends GridBagLayout {

private static final Logger log = Logger.getLogger(GridBagLayoutEx.class.getName());
private static final long serialVersionUID = 5303976710331305433L;
private static final Pattern[] patterns = new Pattern[] {
Pattern.compile("(fill):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(anchor):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(gridx):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(gridy):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(gridwidth):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(gridheight):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(weightx):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(weighty):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(ipadx):([^\\s]+)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(ipady):([^\\s]+)", Pattern.CASE_INSENSITIVE)
};
private static final Pattern insetsPattern = Pattern.compile("insets:(\\d+).(\\d+).(\\d+).(\\d+)",
Pattern.CASE_INSENSITIVE);

@Override
public final void addLayoutComponent(final Component comp, final Object constraints) {
try {
final GridBagConstraints gbc = new GridBagConstraints();
for (final Pattern pattern : patterns) {
final Matcher m = pattern.matcher((String) constraints);
if (m.find()) {
// First have a look and see if the value is a static constant ie there's a field representing it.
// This would be something like gbc.gridx = GridBagConstraints.REMAINDER
final Field f = gbc.getClass().getField(m.group(1).toLowerCase());
try {
final Field value = gbc.getClass().getField(m.group(2).toUpperCase());
if (f.getType() == int.class) {
f.setInt(gbc, value.getInt(gbc));
} else if (f.getType() == double.class) {
f.setDouble(gbc, value.getDouble(gbc));
}
} catch (final NoSuchFieldException nsfe) {
// There's no field for this value so we will attempt to set it ourselves.
if (f.getType() == int.class) {
f.setInt(gbc, Integer.valueOf(m.group(2)).intValue());
} else if (f.getType() == double.class) {
f.setDouble(gbc, Double.valueOf(m.group(2)).doubleValue());
}
}
}
}
final Matcher m = insetsPattern.matcher((String) constraints);
if (m.find()) {
gbc.insets = new Insets(Integer.valueOf(m.group(1)).intValue(), Integer.valueOf(m.group(2)).intValue(),
Integer.valueOf(m.group(3)).intValue(), Integer.valueOf(m.group(4)).intValue());
}
super.addLayoutComponent(comp, gbc);
} catch (final Exception e) {
log.severe("Exception adding component [" + comp + "] with constraints [" + constraints + "]");
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

Friday, February 22, 2008

Cocking Oil

During today's visit to Tower 5 we spotted this.....

Glad I didn't have the fish....

Tuesday, April 03, 2007

A cat called custard

Last Saturday night the doorbell rang at about 10pm, there's a young lad at the door.

"Do you know the owner of a ginger cat? I've just run him over and he's crawled into a hedge down the road."

I grabbed my torch and raced down the road; the cat was there in a hedge shaking and bleeding from the mouth. Still fairly lively though given what had happened to him. It was pretty obvious I had to get him out as if he went any further into the hedge it would be really difficult to get him out. Luckily I managed to get hold of him at the first attempt and dragged him out. He was squirming a lot which felt like a good sign. I sat him on the floor and calmed him down before taking him back to my house. I got him inside and took him into the kitchen. He coughed and blood spurted all over the kitched floor. His lower jaw was clearly broken, hanging down and one of his back legs was dislocated judging by his limp.

We grabbed one of our cat boxes and as I'd been drinking the young lad that ran him over and his girlfriend agreed to take him to the vets. He was pretty quiet in the car, I could hear him breathing and his airway sounded good, breathing hard but not laboured.

We got to the vets and they took him away. About 15 mins later the vet returned. The cat's lower jaw is completely split in half and the roof of his mouth is badly fractured too. They have him on oxygen and painkillers. The surgery will cost a significant amount of money. If we can't find the owners within 24 hours then he will be put down. If his condition worsens then he will be put down. We all felt pretty dejected - he was alive but if we didn't find out who owned him he was dead. We figured that at the very least he would spend his last hours in comfort rather than freezing and bleeding to death in a hedge. I told the vet to call me straight away if anything changed.

We went back to my house and photocopied a bunch of fliers to put through people's doors asking if they know of the cat and to call the vets immediately. I delivered them all sometime after midnight and eventually went to bed.

After lunch on Sunday I decided to ring the vets as I hadn't heard anything. Still no word from the owners but at least his condition was stable.

I decided to go further afield and try more fliers. He was just too well groomed to be stray, he had to be owned by someone. So I started to flier the rest of the estate and asked around the residents to see if they knew him. He was known in the area and had been seen in the gardens so that was a good start.

By now I had one flier left and was giving up and going home when I walked past a couple of kids playing in the alley. I decided to go back and ask them if the knew the cat. The little girl I talked to said she hadn't seen her ginger cat for a day or so. We went and got her mom and from the description it was surely their cat - especially as they confirmed that he hadn't be spayed. The vet had told me that he hadn't been spayed and that pretty much any cat that gets run over is a male who hasn't been spayed.

I gave them the last flier and went home - fingers crossed.

5 hours or so later I had a call from the vets saying the owners had come forward and he was going to get the operation he needed. His condition had improved and he was doing really well.

His name? Custard.

Just goes to show you should never ever give up.

Hopefully I will hear later this week how the operation went....

Monday, March 12, 2007

People of Fleet...

...are possibly the most polite drivers on Earth. Courteous beyond belief. Calm and generous to a fault. I've yet to see a middle finger or victory wave.

However, when the fucking traffic lights go green don't let 26 cars from a side road go in front of you. You might not be in a rush but by that point in my journey to work I've had enough.

And when you do eventually get through the lights, how about not leaving 7 car lengths between you and the bloke in front so more that two cars get through on green?

Here endeth le rant...

Tuesday, January 02, 2007

If you only knew what I've forgotten

I was thinking the other day about the things I can't remember anymore.

That may sound like a crazy statement but it's not as mad as it sounds. I was trying to do some mathematics the other day and was stuggling. At university my math was good, and the particular problem I was attempting to solve, I knew I used to know how to do it and couldn't remember anymore.

So what's worse, not knowing how to do something. Or knowing that you used to know how do something and have since forgotten?

I think the latter is worse and my current plan is to drink more wine so I forget I ever knew how to do anything.

Lady marmalade again

Isn't it strange the way search engines work sometimes....My old post on Lady Marmalade is on the third page when you search google for lady marmalade ...

Surely there are more deserving pages? I was just saying how much i like marmalade on toast.


see my results

Tuesday, December 26, 2006

The Boxing Day Cigar

The most anticipated and enjoyable cigar of the year, richly deserved after the over-indulgence of Christmas Day.

Monday, November 06, 2006

BT are shit

I'll rant more when I feel I can be coherent. Needless to say they are a shower of shite and I'm not the only one who thinks this...


http://www.btsuck.org/

The camera never lies

I've updated a bunch of photos in the gallery, mostly of Livi.

Sleeping beauty....

Saturday, September 16, 2006

Good luck Big Juice

My friend...my hero...see you on Broadway

Burton mail news article

Adventures in babyland

Livi is cool and smiles lots now.

Friday, July 21, 2006

How we used to live

The seventies were great, not least because I was born then...




Thanks Uncle Mike, is the Ostrich dead?

Monday, July 17, 2006

Fly Icarus Airlines

http://news.bbc.co.uk/1/hi/england/5185910.stm

According to Junket, the sky really is the limit...

Friday, July 14, 2006

Are birds scared of heights?

Do you think that any bird has been scared of heights? If so, would it evolve into something flightless, like New Zealand’s Kakapo?

If that’s the case, did we evolve from an aquaphobic fish? Sounds mad, BUT, it could happen!

Evolution is a strange thing, and I don't pretend to understand it, but is it the creation of solutions to problems that exist, or is it creating problems by solutions that don't?

What prompted the evolution of an eyeball? What decided that being able to see (and therefore interpret) gives an advantage over blind genetic peers? Is it only based upon how efficiently the thing could grow and reproduce... What decided reproduction was a good idea? Is it because death is built in?

Saturday, July 08, 2006

Safe hands

As I stumble along the path of parenthood I realised that I should be extremely grateful for my time at school. Especially playing cricket. I was a reasonable wicket keeper which is coming in handy catching Livia's sick.

Two slips and a gully please.

Wednesday, May 24, 2006

Professor Bubbleworks unifies dark matter and alternate realities

The end of the Professor Bubbleworks ride at Chessington (don't ask me why I was there - I am a kid at heart) has streams of water arcs that pass above your head. Those arcs are periodically lit by strobe lighting, effectively freezing and focussing your attention on a particular water drop's trajectory.

This got me thinking about time and alternative realities. There is a common thought that all possibilities are playing out all of the time (let's conveniently ignore what that might mean for conservation of energy and the bounded/unbounded universe); but why do we only experience a single reality (i.e. why haven't I won the lottery yet?). Could it be that each reality is like one of those water droplets, but the collapsing of the wave function (I can't remember what that actually means ;-) ) is like the strobe or a filter on our reality? If that was the case, could we alter the filter or frequency of the "reality strobe" to "light up" alternate realities?

What's this got to do with dark matter? Well, there's an awful lot of it... and we don't know what it is and we can't "light it up" to look at it... but could the dark matter actually be our alternate realities playing out?!

Tuesday, May 16, 2006

Lady Marmalade

Isn't it strange how you rediscover things throughout your life?

Marmalade....where have you been for the last 10 years?

Monday, May 08, 2006

The law of proportions

Bidd's law No.1 states that the amount of work you are required to undertake as part of your employment is directly proportional to the summation of complication in your personal life.

work == sum(life)


Friday, April 21, 2006

German excursion

Even discounting the girl on the plane on the way back...we had a good time in Cologne...friendly natives and good beer....

Being British...this made us laugh...

Wednesday, April 19, 2006

Pringles

I'm always getting busted for scoffing all the pringles . I always rip the foil seal and then there's no hinding the fact that they have been opened.

Skills to learn this year No.1 - How to open pringles slowly so the foil seal looks undisturbed.

Tuesday, April 18, 2006

Papa bought a Saab




Ding ding ding..."Time for service"...crap...I'll always be poor....

Windy miller

Testing, testing one two three testing...Ich bin ein blogger...