Sending HTML Email with Wicket part II: Converting links

In my previous post, I showed how you can use Wicket‘s HTML rendering engine to render HTML emails by faking a request/response cycle.

In this post, I’ll show you how to use an IVisitor to change image and anchor URLs to be absolute instead of relative. This is absolutely essential in order to make your HTML email work – otherwise all your images can’t be found, and your links point to your own mail server.

The trick is to use Wicket’s IVisitor to add a TransformerBehaviour to all the Images and Links that uses a regex to transform the URL after render but before the page is returned.

The code for the IVisitor is below:

private final class RelativeToAbsoluteUrlVisitor implements IVisitor {
        private final String requestPath;
        private Pattern urlPattern;
        private Class<? extends Component> componentClass;

        private RelativeToAbsoluteUrlVisitor(String requestPath, Class<? extends Component> componentClass, String attributeName) {
            this.requestPath = requestPath;
            this.componentClass = componentClass;
            urlPattern = Pattern.compile(attributeName+"="(.*?)"");
        }

        public Object component(Component component) {
            //if this component is of the specified class, update the URL attribute to be absolute instead of relative
            if(componentClass.isInstance(component)) {
                component.add(new AbstractTransformerBehavior() {

                    @Override
                    public CharSequence transform(Component component,
                            CharSequence output) throws Exception {
                        log.warn("Transforming component output: "+output);

                        Matcher m = urlPattern.matcher(output);

                        if(m.find()){
                            String attributeValue = m.group(1);
                            int start = m.start(1);
                            int end = m.end(1);

                            //convert relative to absolute URL
                            String absolutePath = RequestUtils.toAbsolutePath(requestPath, attributeValue);

                            log.warn("Got absolute path '"+absolutePath+"' from relative path '"+attributeValue+"'");

                            //construct a new string with the absolute URL
                            String strOutput = String.valueOf(output);
                            String finalOutput = strOutput.substring(0, start)+absolutePath+strOutput.substring(end);

                            log.warn("Returning updated component: '"+finalOutput+"'");

                            return finalOutput;
                        }

                        return output;
                    }});
            }
            return IVisitor.CONTINUE_TRAVERSAL;
        }
    }

Then we override the onBeforeRender() routine to traverse the component hierarchy and add this behaviour to the appropriate elements. Note that I haven’t shown how you get the current absolute request URL, as in my system this is proprietary. There’s plenty of example code floating around on how to do that, anyway.

    protected void onBeforeRender() {
        super.onBeforeRender();

        final String requestPath = MyCustomWebRequestCycle.get().getCurrentUrlAsString();

        IVisitor imageVisitor = new RelativeToAbsoluteUrlVisitor(requestPath, Image.class, "src");
        IVisitor anchorVisitor = new RelativeToAbsoluteUrlVisitor(requestPath, Link.class, "href");

        visitChildren(Image.class, imageVisitor);
        visitChildren(Link.class, anchorVisitor);
    }

So there you have it! All the bits and pieces to create HTML email with Wicket. There’s one more catch though: You have to generate these emails in the same process as the Wicket Application. Calling Application.get() outside of the main process results in an error. In my system, I get around this by generating the HTML email source every time the user saves my Newsletter bean, which means that when it’s finally sent (in the background), it just sends the pre-generated HTML. Easy!



			
					

Render a Wicket page to a string for HTML email

Something that’s very desirable to do in Apache Wicket is create HTML emails using Wicket’s brilliant component-oriented markup.

I’ve been working on this problem on and off for ages — it’s tricky because of teh way that markup rendering is so deeply tied to the requestcycle, which in turn is deeply dependent on the httpservletrequest — with good reason, too. That’s where Wicket gets its autoconfiguring magic from!

So in order to use Wicket to create HTML emails, we need to fake the request/response cycle. I wrote this convenient method that renders a bookmarkable page (pageclass + pageparameters) to a string:

protected String renderPage(Class<? extends Page> pageClass, PageParameters pageParameters) {

        //get the servlet context
        WebApplication application = (WebApplication) WebApplication.get();

        ServletContext context = application.getServletContext();

        //fake a request/response cycle
        MockHttpSession servletSession = new MockHttpSession(context);
        servletSession.setTemporary(true);

        MockHttpServletRequest servletRequest = new MockHttpServletRequest(
                application, servletSession, context);
        MockHttpServletResponse servletResponse = new MockHttpServletResponse(
                servletRequest);

        //initialize request and response
        servletRequest.initialize();
        servletResponse.initialize();

        WebRequest webRequest = new WebRequest(servletRequest);

        BufferedWebResponse webResponse = new BufferedWebResponse(servletResponse);
        webResponse.setAjax(true);

        WebRequestCycle requestCycle = new WebRequestCycle(
                application, webRequest, webResponse);

        requestCycle.setRequestTarget(new BookmarkablePageRequestTarget(pageClass, pageParameters));

        try {
            requestCycle.request();

            log.warn("Response after request: "+webResponse.toString());

            if (requestCycle.wasHandled() == false) {
                requestCycle.setRequestTarget(new WebErrorCodeResponseTarget(
                        HttpServletResponse.SC_NOT_FOUND));
            }
            requestCycle.detach();

        } finally {
            requestCycle.getResponse().close();
        }

        return webResponse.toString();
    }

One other thing that’s desirable to do is change all relative links in the email to absolute URLs — something that Wicket makes super-easy, if you know how. That will be the subject of my next post.

Australia adopts Chinese Internet policy

I was stunned and baffled today to read that not only is Australia implementing a national porn filter, but that there is no way to completely opt-out of the system.

Even if you switch off the “inappropriate for children” part, there remains in place an “inappropriate for anyone in Australia” part, the rules for which will presumably remain secret and under the control of someone who “knows better”.

Score -5 Kevin Rudd for clamping down on the open use of the nation’s critical information infrastructure. The greatest single benefit of the Internet is that it allows the completely free and uncensored flow of information. Sure it’s both a blessing and a curse, but the possibility of governments controlling what we’re allowed to read frightens me much more than the occasional person getting scammed.

George Saunders has perfected Sarah Palin’s speech patterns

Is it a bird? Is it a plane? No, it’s Super Satire!

So, when Barack Obama says he will put some lipstick on my pig, I am, like, Are you calling me a pig? If so, thanks! Pigs are the most non-Élite of all barnyard animals. And also, if you put lipstick on my pig, do you know what the difference will be between that pig and a pit bull? I’ll tell you: a pit bull can easily kill a pig. And, as the pig dies, guess what the Hockey Mom is doing? Going to her car, putting on more lipstick, so that, upon returning, finding that pig dead, she once again looks identical to that pit bull, which, staying on mission, the two of them step over the dead pig, looking exactly like twins, except the pit bull is scratching his lower ass with one frantic leg, whereas the Hockey Mom is carrying an extra hockey stick in case Todd breaks his again. But both are going, like, Ha ha, where’s that dumb pig now? Dead, that’s who, and also: not a smidge of lipstick.

A lose-lose for the pig.