Author Archives: Arsenalist

About Arsenalist

Gunner fan

What files changed in WordPress 2.8.4? The proper way to upgrade patches

I run raptorsrepublic.com which uses WordPress with some pretty heavy customizations here and there so every time WordPress releases an upgrade I’m very wary of doing it because I just don’t know how it’ll effect the platform. Partial file copying with FTP can really throw you a curveball and if one file gets corrupted it’ll take you hours to find out which one.

I think the best way of upgrading WordPress installations is by only copying files that changed over patch releases (e.g.: 2.8.2, 2.8.3 and 2.8.4). If there’s a database change things get a little more complicated but in most patch releases that’s not the case.

The way you find out what files were changed is by accessing the WordPress SVN repository and running the svn diff command. Here is the commands one need to run and the output that follows it. I’m running this on a Linux box with SVN installed. You could also do it in windows if you download the binaries.

svn diff --summarize http://core.svn.wordpress.org/tags/2.8.3/ http://core.svn.wordpress.org/tags/2.8.4/
M      http://core.svn.wordpress.org/tags/2.8.4/wp-login.php
M      http://core.svn.wordpress.org/tags/2.8.4/wp-includes/version.php
M      http://core.svn.wordpress.org/tags/2.8.4/readme.html

This means three files changed between the two versions as M stands for modified. That value could also be A for added and D for deleted. If you’d like to see what the actual changes were just get rid of the --summarize part. I copied these three files over to my WordPress installation and I’m done!

Advertisement

Integrating vBulletin with a WordPress theme

OK, so you have a WordPress blog and are thinking about adding a vBulletin message board to it and want it to appear seamlessly within your WP theme. This post will show you how to do it.

The way you go about accomplishing this is by creating two Plugins under vBulletin. Before we do anything we have to make sure that the Plugin/Hook system is enabled. For this select vBulletin Options under the vBulletin Options from the control panel. Select the Plugin/Hook System option in the select list and make sure its enabled. Once you’ve done that, you’ll need to create a couple plugins. Click on the Add New Plugin option under the Plugins & Products on the left hand side of the control panel. Create a plugin with the Hook Location specified as global_start and the default execution order. Give it the title of WP Header and in the Plugin PHP Code field, write the following:

ob_start();
   include('../path/to/wp-load.php');
   include('../blog/wp-content/themes/sandbox/header.php');
   $wp_header = ob_get_contents();
ob_end_clean();

Now let’s examine what I did here. Bascially, I’m invoking two WordPress PHP files, wp-load.php from the main installation and header.php from my theme’s directory. I capture the content of it in the $wp_header variable which we’ll use later.

Make sure you change the plugin to be active by clicking on the Yes radio button and save the plugin.

Now we’ll create another plugin for the footer. Once again, specify the Hook Location as global_start, give it the title of WP Footer and select the default execution order. In the Plugin PHP Code field write the following:

ob_start();
   include('../blog/wp-content/themes/sandbox/footer.php');
   $wp_footer = ob_get_contents();
ob_end_clean();

In this plugin we’re capturing the theme’s footer.php in the $wp_footer variable.

Now we need to insert the two pieces of data we captured into the vBulletin theme. For that let’s go to Style Manager under the Styles & Templates group in the left control panel. Once there, select Edit Templates from the drop down list which should give you a listing of all the editable files in your theme. Double-click on header from the list and simply add the following line of code as the first line in the file:

$wp_header

Save it and go back to the list of editable files and edit footer. Make sure the following line of code is the last line in the file:

$wp_footer

Save it and you’re done.

Well, almost. Depending on the version of vBulletin you have you might get a PHP error which says something like “sanitize_url function has already been defined”. Check the vBulletin file its happening in, download it and rename both occurrences of the function to something like vb_sanitize_url and now you’re done.

Conditionally printing HTML tags in JSF Facelets

This took me a bit to figure out so I thought I’d post it.

Say you’re using JSF and want to conditionally print some HTML tags in your Facelet that could, technically speaking, result in non well-formed markup. You can’t really do it. Printing something like is illegal as it’ll complain about the < and > characters being in there. Using the tag doesn’t work either, even if you wrap the content in a CDATA element. Problem is that it’s preventing you from writing non well-formed markup in any which way.

One of the solutions is to force the rendering kit to not analyze the output for “well-formedness” by passing the HTML markup in a variable.

In your facelet.xhtml

<h:outputText escape="false" 
              rendered="#{someCondition}" 
              value="#{messages&#91;'lessThan'&#93;.concat('ul').concat(messages&#91;'greaterThan'&#93;)}"/>

In messages.properties

lessThan=<
greaterThan=>

IntelliJ Hilarity

Note that this is a very lame post. IntelliJ IDEA is the greatest Java IDE in the world, his post does not “diss” it in any way, just pointing out something that was funny to me and only so because I’ve been at it for quite some time now.

I often have IntelliJ generate the equals() and hashCode() methods for me when programming @Entity beans. Here’s what it did for me:

equals

Makes sense, but notice how the last if statement is highlighted? That’s IntelliJ’s way of telling me that it can make things better which is a little weird because IntelliJ’s the guy that generated the code for me. Anyway, I see what the hint has to say:

hint

It’s saying that it can make some of these ifs redundant and sure enough once I take the hint the return clause is joined with last if like so:

first-hint

It’s all good but notice now that it now highlighted the previous if statement and if I accept it, it’ll continue doing the same thing over and over again. I’ll accept all the improvements it wants to make and I’ll finally end up with this method which is logically equivalent to what I showed you in the first picture:

final

The difference isn’t that great in an entity with three properties but you get the point about tertiary statements and IntelliJ”s love for them.

Writing Custom Facelet JSF Components

Writing Facelet JSF Components is NOT the same thing as writing custom JSP-based JSF Components. Once you get past that it turns out they’re not hard to write at all. There’s no mucking around with JSP tag libraries, TLD files and other such archaic nonsense.

You need to edit create/edit three files in total. Here’s an example of a Facelet JSF component that prints out a table row when it is nested around another UI component. For example, the component if used the following way:

<arse:tableRow>
    <h:inputText id="myId" label="My Label"/>
</arse:tableRow>

would print

<tr>
  <td>My Label</td>
  <td><input type="text" ..../></td>
</tr>

Simple, right? Here’s the three files you have to create/edit:

faces-config.xml

Make sure the following is present in your faces-config.xml:

    
    <component>
        <component-type>tableRow</component-type>
        <component-class>com.arsenalist.UITableRow</component-class>
    </component>

META-INF/mytag-taglib.xml

Create a file withe following contents under your META-INF folder:

<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
  "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">

<facelet-taglib>
    <namespace>http://www.arsenalist.com/jsf/util</namespace>
    <tag>
        <tag-name>tableRow</tag-name>
        <component>
            <component-type>tableRow</component-type>
            <renderer-type>tableRow.renderer</renderer-type>
        </component>
    </tag>
</facelet-taglib>

Note the namespace, that’s what you’ll need to refer in the Facelet before using the tag, e.g:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:arse="http://www.arsenalist.com/jsf/util"
      . . . 
&#91;/sourcecode&#93;

<h2><code>UITableRow.java</code></h2>

Finally, create the actual component.  Here's an example of a component that wraps the child elements around a tr and a couple tds.  We must override <code>getRendersChildren()</code> to return true because it is the component's duty to render its children (since we're wrapping it around stuff).


package com.arsenalist;


import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;

/**
 * This class renders a table row.  It must contain two controls, the label and control to render.
 * @author Zarar Siddiqi
 */
public class UITableRow extends UIOutput {

    public UITableRow() {
        setRendererType(null);
    }

    public boolean getRendersChildren() {
        return true;
    }

    public void encodeBegin(FacesContext facesContext) throws IOException {
        // We're rendering a table row
        facesContext.getResponseWriter().startElement("tr", null);
    }

    @Override
    public void encodeChildren(FacesContext facesContext) throws IOException {
        ResponseWriter writer = facesContext.getResponseWriter();

        UIComponent control = getChildren().get(0);

        writer.startElement("td", label);
        // Label goes inside td
        writer.startElement("label", label);
        writer.writeAttribute("for", control.getClientId(facesContext), null);

        writer.write((String) control.getAttributes().get("label"));
        writer.endElement("label");
        writer.endElement("td");

        // Div element goes in the second along with the control
        writer.startElement("td", control);
        control.encodeEnd(facesContext);
        writer.endElement("td");
    }


    @Override
    public void encodeEnd(FacesContext facesContext) throws IOException {
        ResponseWriter writer = facesContext.getResponseWriter();
        writer.endElement("tr");
    }

    @Override
    public String getFamily() {
        return COMPONENT_TYPE;
    }
}

And that’s that.

JSF Seam Validation + Custom Messages + Annotations + Internationalization

Validation is one of the first things you test out when evaluating a web framework and its often one of the most time consuming to wrap your head around. In this post I’ll talk about three types of validation mechanisms present in JBoss’ Seam which will get you on your way towards validating web forms without too much pain:

I’m going to cover three cases:

  1. Validating required fields without using annotations
  2. Validating manually and displaying custom messages
  3. Validating fields using Hibernate annotations in Seam beans

We’ll also display messages using a simple resource bundle (java.util.ResourceBundle) which will allow us to internationalize our forms and messages. Let’s dive into the examples:

Validating required fields without using annotations

This is the most general case, you want to force the user to input something in your text fields and if they don’t, you want to display a message telling them just that.

Here’s a JSF form which asks for a username and password:

<h:messages/>
<h:form id="LoginForm">
    <table>
	<tr>
	    <td><h:outputText value="#{messages&#91;'login.username'&#93;}"/></td>
	    <td>
		<h:inputText required="true" value="#{user.username}" label="#{messages&#91;'login.username'&#93;}"/>
	    </td>
	</tr>
	<tr>
	    <td><h:outputText value="#{messages&#91;'login.password'&#93;}"/></td>
	    <td>
		<h:inputSecret required="true" value="#{user.password}" label="#{messages&#91;'login.password'&#93;}"/>
	    </td>
	</tr>
	<tr>
	    <td></td>
	    <td>
		<h:commandButton action="#{loginAction.login}"
				 value="#{messages&#91;'button.login'&#93;}"/>
	    </td>
	</tr>
    </table>
</h:form>

Specifying required=”true” is all you need to validate required fields. The matter of displaying messages is left to the <h:messages/> tag which iterates through the list of messages generated by the validation phase and displays them sequentially.

By default validation messages are displayed in a format that is not very intuitive, in order to change the format you must override a property in your messages.properties file located at the root of your classpath:

javax.faces.component.UIInput.REQUIRED={0} is a required field.

The placeholder is {0} is automatically filled by the label attribute of the <h:inputText> tag. So in the above case if login.username is defined to be “Username” in the resource bundle, the messages that will be printed will be: Username is a required field.

If validation passes, then the login() method on the bean referenced by loginAction will be called (as specified by the <h:commandButton> tag.

Validating manually and displaying custom messages

This is probably the most powerful way of validating user input – programmatically. Let’s face it, the built-in validators can only do so much, at some point you end up writing java code to validate input by checking it against a database or queue etc. Going back to the login example, say we need to check the values supplied by the user against a database and if they match, let them into the system and if they don’t, kick them back to the login page with a message. The login page does not change, let’s get to the LoginAction class:

@Name( "loginAction" )
public class LoginAction {

    @In
    private User user;

    @In(create=true)
    private FacesMessages facesMessages;

    public String login() {
        if (user.getUsername().equals( "Arsenalist" ) && user.getPassword().equals( "Raptors" )) {
            return "success";
        } else {
            facesMessages.addFromResourceBundle("login.failed");
            return "failure";
        }
    }
}

It’s very obvious what’s happening here. The injected instance of FacesMessages allows you to use its addFromResourceBundle() method to specify a message that will be displayed in the view resulting from returning “failure”. Just for completeness sakes, here’s the faces-config.xml navigation rule:

    
    <navigation-rule>
        <from-view-id>/pages/login.xhtml</from-view-id>
        <navigation-case>
            <from-action>#{loginAction.login}</from-action>
            <from-outcome>success</from-outcome>
            <to-view-id>/pages/home.xhtml</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{loginAction.login}</from-action>
            <from-outcome>failure</from-outcome>
            <to-view-id>/pages/login.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

Validating fields using Hibernate annotations in Seam beans

The next step is to apply more complex validation without resorting to writing Java code and for that Seam relies on Hibernate’s validation framework. As an aside, this dependency is probably the most annoying thing about Seam at this point but it works well enough to look past.

Let’s say we need to force the value of username to be atleast 5 characters. In order to do this we need to annotate two things:

  1. The injected user variable in LoginAction so Seam knows to validate it
  2. The User objects properties to specify what to validate.
    1. Here’s the relevant piece in LoginAction.java:

      @Name( "loginAction" )
      public class LoginAction {
          @In @Valid
          private User user;
          public String login() {
              . . . .
          }
      
      

      Here’s the relevant piece in User.java:

      @Name( "user" )
      public class User {
      
          private String username;
          private String password;
      
          @Length(min=5, message= "#{messages['login.username.length']}" )
          public String getUsername() {
              return username;
          }
          . . . .
      

      Notice how we’re using a resource key inside an annotation to print the message. This will look for a resource bundle called messages and inside it for the login.username.length property to retrieve the message. You could alternately just write the message in plain old English inside the annotation but why would you want to when you can internationalize.

      The last thing we need to do is tell the JSF page that it will need validation (I think this is a somewhat redundant step since the bean is already annotated but nonetheless it is required). You must wrap the fields of the login form around the <s:validateAll> tag like so:

      <h:messages/>
      <h:form id="LoginForm">
          <s:validateAll>
                  . . . .
      	    <h:outputText value="#{messages&#91;'login.username'&#93;}"/></td>
                  . . . .
          </s:validateAll>
      </h:form>
      

      Note: Be sure to specify required=”true” for the fields you want to apply annotation validations to. Otherwise, you’ll see some very weird results such as only non-blank fields getting the annotation validations applied to while the blank fields get considered valid.

      Here’s a list of annotations that you can use to validate java beans:

      • @Length(min=, max=) Checks whether the string length matches the range
      • @Max(value=) Checks that the value is less than or equal to the max
      • @Min(value=) Checks that the value is greater than or equal to the min
      • @NotNull Checks that the value is not null
      • @Past For a date object, checks that the date is in the past
      • @Future For a date object, checks that the date is in the future
      • @Pattern(regex=”regexp”, flag=) For a string, checks that the string matches this pattern
      • @Range(min=, max=) Checks whether the value is between the min and the max
      • @Size(min=, max=) For collections, checks that the size is between the two
      • @AssertFalse Asserts that the evaluation of the method is false
      • @AssertTrue Asserts that the evaluation of the method is true
      • @Valid For a collection or a map, checks that all the objects they contain are valid
      • @Email Checks whether the string conforms to the email address specification

      That’s all there is to it.

Free Euro 2008 Pool Script

OK, I don’t contribute much to the software community but I’m feeling generous today.

Since I run this pool at my office and for some unknown and weird reasons the link is #1 on Google for Euro 2008 Office Pool, I figured I’d share the piece of code that runs that “system” with the public.

Its basically a PHP/MySQL app with a few tables that are self-explanatory (I hope). You just enter who picked what teams and players and then just update the results as they happen – watch the entrants rise and fall as each team wins, loses or ties. Its quite fun really, much better than doing cocaine. The PDF form that entrants fill out is part of the zip along with everything else you need, but here it is anyway if you want to take a look.

Download the ZIP file here. All you really need to do is dump the schema in a MySQL 5 database (maybe even 4 might work), change the database info in ez_sql.php file (just replace INSERT_HOST tags etc.) and you’re good to go.

If you do feel like joining the pool, send me your entry form and $16 through PayPal to zarars at gmail

Update: I’ve updated this post with an improved version of this software which includes sample data. Here’s the older version.

Worst Captcha Ever

I’m trying to download a file from the evil Rapidshare (who make you wait about 2 painful minutes before giving you the file) and just after the wait time is over, I get a Captcha looking like this:

WTF man? I mean, does it really need to be this hard? Are you telling me that it has come down to us hiding domestic animals in our captcha characters in order to hold off bots? Plus, there are only 3 “letters” in that image but its asking for four.

This is a sad day for the HCI crowd.

On an unrelated note, here’s my cat.