XPages PhoneNumber Control – Part 2 Upgrades to the Converter
In part 1 of this series, we created a basic Phone Number Converter, which takes the user input and converts it to a standard International format for phone numbers.
In this part (Part 2) we will add 2 extra pieces of functionality to this converter.
- Implement some ‘tooling’ for our converter, by defining our custom tag and include in the ‘drop down’ list of converters in Domino Designer.
- Add a property to the converter to it to allow the defaultCountryCode to be set on the XPage (and not hardcoded anymore)
This post will introduce some concepts that will help us throughout any XPages component development
- Introduction to the Xsp Configuration file format (xsp-config) which tells Domino Designer ‘tooling’ information about components
- Introduction to some basic concepts to do with control development:
- Adding a property to a Component
- Saving the component’s state between requests
- Allowing a property to use a run-time Value Binding
- The special component ‘getter’ pattern for properties that can have value binding
The source code is available on github at camac/XPagesPhoneNumberControl, and I have tagged the code as it stands after this post as ‘part2‘
Telling Domino Designer about our control with xsp-config
So in this next step, we will not change anything in our actual PhoneNumberConverter java class, it will behave at ‘runtime’ (when the application runs) exactly as it did before.
The difference will be seen at ‘design’ time, when the developer is creating the XPage.
After this step Domino Designer will know specifically about our control and can include it in the XPage via it’s own custom tag, whereas previously we were using the generic <xp:converter
converterId=””/> tag.
Xsp-config vs Faces Config
We define this Domino Designer ‘tooling’ information by using an xsp-config file.
The format of the xsp-config files is based on the faces-config file format, however they both serve two different purposes and it is important to know the difference. It can be confusing because both file formats have the root xml element <faces-config>.
You can tell the difference between the two files by looking at the file extension whether it is an xsp-config file or a faces config file, the xsp-config files end with ‘.xsp-config‘ and the faces config ends with ‘.xml‘.
Faces Config files are used to configure the application at ‘runtime’.
xsp-config files are used at ‘design’ time by Domino Designer to show the developer extra information about available controls and how to configure them. The xsp-config information is also they are used when ‘building’ the XPages from xpage source xml into the underlying secret java versions of the xpages that you don’t usually see unless you peek around in package explorer.
If you want to know everything about the xsp-config file, then I suggest you have a good look at the Domino Developer Wiki’s ‘XPages configuration file format’ section, which has 5 pages at time of writing. It has a lot of good information about the format.
Also I suggest having a look in the source code of the Extension Library, pick an extension library control you know well (maybe the tooltip?) and go looking in the ‘com.ibm.xsp.extlib.controls’ plugin, and within that in the ‘com.ibm.xsp.extlib.config’ package, you should find lots of examples of xsp-config files.
Creating our xsp-config file for our PhoneNumberConverter
Here are the Questions we are going to answer within our xsp config file
- What is the Human Readable name of our Converter? (<display-name>)
- What is a good description of what it does (<description>)
- What is the java class of this converter (<converter-class>)
- What Id should be used for this converter? (<converter-id>)
- What is the xml tag name (e.g. <xp:converter>) of our converter? (<converter-extension><tag-name>)
So our first step is to create an xsp-config file for the converter, and place it in the WebContentWEB-INF directory (using the package explorer view).
You can include more than one component in the same xsp-config file and later on we will add some components to the same xsp-config file, so instead of calling it phoneNumberConverter.xsp-config, I will call it phoneNumber.xsp-config
Note that the file name does not matter, the important part is that the extension is .xsp-config
The first thing I will do for this new xsp-config file is to define the namespace and default prefix for the contents of this xsp-config file.
This is done using the faces-config-extension tag.
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="UTF-8"?> <faces-config> <faces-config-extension> <namespace-uri>http://www.gregorbyte.com/xsp/ </namespace-uri> <default-prefix>gb</default-prefix> </faces-config-extension> </faces-config> |
I am using the namespace http://www.gregorbyte.com/xsp/ , but you could use anything you like, it does not have to be a URL it just is by convention, and the URL does not need to point anywhere. More info on xml namespaces and prefixs can be found here.
Next we will included the xsp-config definition for our converter.
Here is the contents of our completed xsp-config file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?xml version="1.0" encoding="UTF-8"?> <faces-config> <faces-config-extension> <namespace-uri>http://www.gregorbyte.com/xsp/ </namespace-uri> <default-prefix>gb</default-prefix> </faces-config-extension> <converter> <description>Converts a String into an Phone Number in International Format</description> <display-name>Phone Number Converter</display-name> <converter-id>gregorbyte.PhoneNumberConverter </converter-id> <converter-class>com.gregorbyte.xsp.converter.PhoneNumberConverter </converter-class> <converter-extension> <tag-name>convertPhoneNumber</tag-name> </converter-extension> </converter> </faces-config> |
So with our new xsp-config, we should be able to select our converter from the converters drop down list!
And we can! Now we will update our XPage to use our custom tag instead of the old <xp:converter converterId=”foo”> tag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:gb="http://www.gregorbyte.com/xsp/"> <xp:label value="Phone Number" id="label1" for="inputText1"></xp:label> <xp:inputText id="inputText1" value="#{viewScope.phoneNumber}"> <xp:this.converter> <gb:convertPhoneNumber></gb:convertPhoneNumber> </xp:this.converter> </xp:inputText> <xp:message id="message1" for="inputText1"></xp:message> <xp:button value="Submit" id="button1"> <xp:eventHandler event="onclick" submit="true" refreshMode="complete"> </xp:eventHandler> </xp:button> </xp:view> |
And now lets test out our page again to make sure our converter is still attached properly. It should operate exactly as before, we will enter something that cannot be converted and expect an error message again.
Ok this step is complete, we have added the tooling and can select our converter from the converters drop down, on to the next step.
Add a ‘Default Country Code’ property to the converter
Currently our converter is hard-coded to have Australia as the default country code. This is great for me, but not great for those users who don’t live in Australia, so our next upgrade to the converter is to allow the XPage designer to choose the default Country Code.
We will do this by adding a property to our converter, and here are the steps we will follow
- Add the defaultCountryCode Property to our Converter (no runtime Value binding yet!)
- Update the xsp-config so that Domino Designer knows about the new property
- Discover a problem regarding state saving
- Fix the problem by implement State Saving
- Allow the property to use a run-time Value Binding as well
Add the default Property to our Converter
We will update our PhoneNumberConverter class to:
- include new property defaultCountryCode with it’s own getter and setter
- update the xsp-config file to include the definition of the property, which includes:
- A description of the property (<description>)
- The Human Readable name (<display-name>)
- The property name for xml use (<property-name>)
- The value type of the property e.g. String, Integer etc. (<property-class>)
- Whether or not the property can be set using a runtime value binding (<property-extension><allow-run-time-binding>)
Ok so here is the updated Java class with the new private field and getter and setter, note that in the getter, we check if the defaultCountryCode is null, and if so we still return “AU” as a default in the case it has not been set.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
package com.gregorbyte.xsp.converter; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import com.ibm.commons.util.StringUtil; public class PhoneNumberConverter implements Converter { private String defaultCountryCode = null; public Object getAsObject(FacesContext context, UIComponent component, String value) { if (StringUtil.isEmpty(value)) return value; PhoneNumberUtil util = PhoneNumberUtil.getInstance(); String defCountryCode = getDefaultCountryCode(); try { PhoneNumber number = util.parse(value, defCountryCode); if (!util.isValidNumber(number)) { FacesMessage fm = new FacesMessage(); fm.setSummary("Phone Number is not valid for country code " + defCountryCode); fm.setDetail("The supplied Phone Number is not valid to the country code " + defCountryCode); fm.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ConverterException(fm); } else { return util.format(number, PhoneNumberFormat.INTERNATIONAL); } } catch (NumberParseException e) { FacesMessage fm = new FacesMessage(); fm.setSummary("The Phone Number entered is not in a valid format for " + defCountryCode); fm.setDetail(e.getMessage()); fm.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ConverterException(fm); } } public String getAsString(FacesContext context, UIComponent component, Object value) { if (value == null) return null; return value.toString(); } public String getDefaultCountryCode() { if (this.defaultCountryCode != null) { return this.defaultCountryCode; } return "AU"; } public void setDefaultCountryCode(String defaultCountryCode) { this.defaultCountryCode = defaultCountryCode; } } |
Ok great we have the property! lets see if we can set it on the XPage:
No we can’t! it only shows the ‘loaded’ property, we need to update the converter definition in our xsp-config to include the definition for the new property:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?xml version="1.0" encoding="UTF-8"?> <faces-config> <faces-config-extension> <namespace-uri>http://www.gregorbyte.com/xsp/ </namespace-uri> <default-prefix>gb</default-prefix> </faces-config-extension> <converter> <description>Converts a String into an Phone Number in International Format</description> <display-name>Phone Number Converter</display-name> <converter-id>gregorbyte.PhoneNumberConverter </converter-id> <converter-class>com.gregorbyte.xsp.converter.PhoneNumberConverter </converter-class> <property> <description>The default Country code to be used if the user does not specify one</description> <display-name>Default Country Code</display-name> <property-name>defaultCountryCode</property-name> <property-class>java.lang.String</property-class> <property-extension> <allow-run-time-binding>false</allow-run-time-binding> </property-extension> </property> <converter-extension> <tag-name>convertPhoneNumber</tag-name> </converter-extension> </converter> </faces-config> |
Now lets go back to the our converter on our XPage and see if we can set the property
We can! So I will set it to US, here is what it looks like when you look at it in the XPages source
So lets see, can we use it now? A quick test, lets try entering google’s California US number, but we will enter it without the US country code (national number only)
and on Submit
Uh oh, somethings wrong! It seems to be using the default ‘AU’ and ignoring the ‘US’ that we set on the XPage, what’s happening?
For a clue, lets look at our persistence settings for this database,
Our database is set to ‘keep pages on disk’, which means that, between requests to our xpage, the XPage control tree needs to be able to save itself to the disk to wait for the next request.
- Our converter currently does not know how to save its ‘state’.
Previously it had nothing that it need to save, but now that the converter has a property, we need to save the property to disk between requests.
If this setting was ‘keep pages in memory’ we would not have this problem, however we should design this converter so that it can be used for any persistence setting.
Implementing State Saving for our converter
So what do we need to do to implement state saving? Our converter needs to implement the javax.faces.component.StateHolder interface.
So lets do that now. The StateHolder interface has 4 methods.
2 of the methods are getters and setters for a transient property ‘isTransient’ and ‘setTransient’. Basically if ‘isTransient’ returns true, State Saving / Restoring will not be done. We aren’t interested in this setting right now, I will leave it as false so that it will always do state saving.
What we are really interested in are the saveState and restoreState functions, which do what they say.
Lets start with save state. Save state should return the object to saved as state. Usually this as an Object[]. So we will do an object array with one element, the defaultCountryCode. Note that we are not using the getter to retrieve the property, but directly referencing the private field which holds the property.
1 2 3 4 5 6 7 8 |
public Object saveState(FacesContext arg0) { Object[] state = new Object[1]; state[0] = this.defaultCountryCode; return state; } |
Now for Restore State, which is given back the same Object that was saved using saveState, and then uses the object to re-initialise the properties. So we will take the defaultCountryCode out of the Object[] and place it back in the private field.
1 2 3 4 5 6 7 |
public void restoreState(FacesContext context, Object object) { Object[] state = (Object[])object; this.defaultCountryCode = (String)state[0]; } |
So lets try it out now and see if it works!
We will do the same as before, and enter the Google California number again in National format (no international code), this time we expect it work with no error.
And after submit
Excellent, the defaultCountryCode must have been saved properly as ‘US’ between requests, as the phone number has been converted to the international format for US.
No lets double check that it will fail for a national number that is not US, by entering the google Sydney (Australia) office number in National Format (no International code) this should fail as it is not a US number
and after submit
And it does fail, and we can see that it is now telling us that it is not a ‘US’ number.
Allowing the defaultCountryCode to be set using a runtime Value Binding
So we are in a good position now, we can change the defaultCountryCode when I design an XPage, but what about runtime value bindings?
You know value bindings don’t you? they look like this
#{viewScope.someVar}
or like this
${viewScope.someVar}
And you know the difference between the two?
The ${viewScope.someVar} is a valueBinding that is computed just once, when the page is loaded.
The #{} is a runtime value binding, which is re-calculated every time it is needed.
At the moment, we can only use the ${} value bindings to set our defaultCountryCode, but what if we wanted it to be dependent on something that may not be available at page load?
We need to upgrade our converter to use run-time Value Bindings.
How does that work? at the moment we have a private field ‘defaultCountryCode’ on our converter. When the country code is entered directly on the XPage, that explicit value is saved to the private field. Also if a ‘page load’ value binding is used ‘${…}’, that page-load value binding is computed into a value once only, and then that value is save in the private field.
For runtime value binding, things are a little different. Instead of any value being saved into the private field defaultCountryCode, it is left as NULL, and instead, the ‘formula’ for computing the value (e.g. the actual text “#{viewScope.someVar}”) is saved in a list of ‘valueBindings’ to be re-used again and again when needed by the component.
So to help us do that, we are not going to re-invent the wheel, and instead we will do something that we should have done at the very start!
We are going to extend a class the IBM XPages developers have made available to extend ‘com.ibm.xsp.converter.AbstractConverter’
The AbstractConverter class takes care of storing the ‘valueBindings’ for us, and also does some other ‘StateHolder’ stuff.
I didn’t extend this class at the start because I wanted to demonstrate some of the principles before we cheated and used the ready made class.
So after extending AbstractConverter, I have to do 2 things
- Modify our StateHolder functions so that it will also save and restore the state of the extended ‘AbstractConverter’ class
- Modify the getter of our defaultCountryCode getter to compute the valueBinding when needed
So for step one, our saveState and restoreState will now save and restore the state of the ‘AbstractConverter’ super class using the index 0 in our object array, and we will use from index 1 onwards for our own PhoneNumberConverter class. You will find this is a common pattern for StateHolder classes that extend another class.
Here is the new Save state and restore state functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public Object saveState(FacesContext arg0) { Object[] state = new Object[2]; state[0] = super.saveState(arg0); state[1] = this.defaultCountryCode; return state; } public void restoreState(FacesContext context, Object object) { Object[] state = (Object[])object; super.restoreState(context, state[0]); this.defaultCountryCode = (String)state[1]; } |
For step 2, we modify our getter for defaultCountryCode to check for a runtime valueBinding.
We still check the private field defaultCountryCode first. If that is not null we return it, otherwise we move on to check for a valueBinding that was stored for “defaultCountryCode”.
The function getValueBinding() is one of the functions that is provided by the ‘AbstractConverter’ superclass. If we do have a valueBinding stored for defaultCountryCode, we compute it (using it’s getValue function), cast it as String and return it.
If there was no valueBinding, then we return the default “AU”
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public String getDefaultCountryCode() { if (this.defaultCountryCode != null) { return this.defaultCountryCode; } ValueBinding vb = getValueBinding("defaultCountryCode"); if (vb != null) { return (String)vb.getValue(getFacesContext()); } return "AU"; } |
Now there is one more thing to do before we try it out. Domino Designer does not yet know that the defaultCountryCode can be a runtime value binding, if we try to compute it now, we don’t get the option to ‘compute dynamically’ (which means runtime value binding)
and as such we need to update the property in our xsp-config file to tell Designer that runtime bindings are allowed.
1 2 3 4 5 6 7 8 9 10 |
<property> <description>The default Country code to be used if the user does not specify one</description> <display-name>Default Country Code</display-name> <property-name>defaultCountryCode</property-name> <property-class>java.lang.String</property-class> <property-extension> <allow-run-time-binding>true</allow-run-time-binding> </property-extension> </property> |
And then we should be able to see the ‘compute dynamically’ option
Ok Lets try it out, I will update my XPage to include a combo box of Countries which allows us to select the defaultCountrycode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:gb="http://www.gregorbyte.com/xsp/"> <xp:comboBox id="comboBox1" value="#{viewScope.countryCode}" defaultValue="AU"> <xp:selectItem itemLabel="Australia (AU)" itemValue="AU"></xp:selectItem> <xp:selectItem itemLabel="France (FR)" itemValue="FR"></xp:selectItem> <xp:selectItem itemLabel="Singapore (SG)" itemValue="SG"></xp:selectItem> <xp:selectItem itemLabel="United States (US)" itemValue="US"></xp:selectItem> <xp:eventHandler event="onchange" submit="true" refreshMode="partial" refreshId="comboBox1" execMode="partial"> </xp:eventHandler> </xp:comboBox> <xp:label value="Phone Number" id="label1" for="inputText1"></xp:label> <xp:inputText id="inputText1" value="#{viewScope.phoneNumber}"> <xp:this.converter> <gb:convertPhoneNumber defaultCountryCode="#{viewScope.countryCode}"> </gb:convertPhoneNumber> </xp:this.converter> </xp:inputText> <xp:message id="message1" for="inputText1"></xp:message> <xp:button value="Submit" id="button1"> <xp:eventHandler event="onclick" submit="true" refreshMode="complete"> </xp:eventHandler> </xp:button> </xp:view> |
Lets enter the Google California National number and try it out with Australia selected as the Country
Which should fail…
And it does so lets change the country to US
And it should pass
And it does! Now, just for fun, lets enter Google French office number, and change country to france
and it should pass..
and it does!
Conclusion for Part 2
So in this part we have upgraded our converter so it now
- Has it’s own xpages tag <gb:convertPhoneNumber>
- Can be selected from the converters drop down
- Can have the defaultCountryCode set explicitly, at page-load or at run time
And in this article we explored a few more concepts like
- The xsp-config file format
- Component state saving
- Basic component properties
- Component properties that using a runtime valuebinding
- Extending a ready to use AbstractSomething class
I hope you enjoyed this part, please let me know via the comments or twitter if you do!
If you have any questions or corrections please also leave a comment!
Next in the series we will make our Phone Number Validator which will allow us to restrict the entered phone number to a certain country or list of countries!
Greg,
Thanks for the two part detailed series. Exceptionally well written and greatly appreciated.
Cheers Damien
Thanks a lot Damien, I really appreciate the feedback!
Great post! Your validation solution working great for me so far. I do have a little annoyance. Every time I open the database in developer that is housing the validator I receive error – The unknown tag gb:convertPhoneNumber cannot be used as a complex type. However if I re-save the custom control the error goes away, until I close and re-open developer. Have you run into this issue? I am using 9.0.1 FP4.
Thanks for the feedback, I’m glad it is working for you!
Unfortunately you have discovered one of the annoyances of doing XPages Control development directly within an NSF. ‘The unknown tag…’ error will constantly reappear as you have experienced.
The only way to avoid it is to package the control in a plugin (an XPages Extension Library) and install to your designer + any servers that your solution is deployed to.
So, the benefit of doing Control development within an NSF is that you don’t require plugin installation, but the negatives are that you see this error all the time, and also you don’t get true re-use across all your applications (you have to copy and paste the controls to each application)
The Benefit of doing controls within a plugin/library, is that you get consistent use of a component across all your applications and you don’t see this ‘the unknown tag error’ all the time!
The negative of doing controls within a plugin is that you require installation to you designer client and production servers, and some people don’t have authority to decide what plugins get deployed to the server environment – even though the same code can be written in the NSF 🙂
I am happy to package this up in a plugin/libary for you so you don’t see this error anymore, but first can you let me know if you will be able to use it? that is, will your solution allow for installation of plugins to the production environment?