Regular Expression to Validate a Comma-Separated List of Email Addresses

Recently, I needed to create a regular expression to validate the format of a comma-separated list of email addresses. Just thought I’d share the result in case it is of use to anyone. The pattern I came up with for matching a single address is as follows:


Note that I didn’t attempt to handle every possible combination of valid characters – only what I’d consider the most common ones.

The pattern is simply duplicated for the comma-separated list. Here’s an example of applying the pattern in Java:

Pattern addressListPattern = Pattern.compile(String.format("%1$s(,\\s*%1$s)*",

System.out.println(addressListPattern.matcher("xyz").matches()); // false
System.out.println(addressListPattern.matcher("").matches()); // true
System.out.println(addressListPattern.matcher(", xyz").matches()); // false
System.out.println(addressListPattern.matcher(",").matches()); // true
System.out.println(addressListPattern.matcher("fø,").matches()); // true

Note that Pattern.UNICODE_CHARACTER_CLASS is not necessary (or supported) in Android, which supports Unicode character matching by default.

Hope it helps!

Using MarkupKit with Charts

For a while now, I’ve been meaning to see if the popular open-source Charts library would work with MarkupKit. I finally got around to trying it this morning.

It actually turned out to be much easier than I expected. All of the Charts demos are built using XIB files. All I had to do was create a markup document that mimicked the contents of a XIB file, including outlets and actions, and add the code to load the view from markup instead of the XIB. I chose to try to replicate the pie chart example:

To load the view declaration, I added the following method to the demo’s PieChartViewController class. No other changes to the controller were necessary:

- (void)loadView
    [self setView:[LMViewBuilder viewWithName:@"PieChartViewController" owner:self root:nil]];

The contents of PieChartViewController.xml are shown below. Note the use of the Charts prefix in the PieChartView declaration. This is necessary because the PieChartView class is defined in the Charts module:

<?xml version="1.0" encoding="UTF-8"?>

<!-- Pie chart demo -->
<LMColumnView layoutMarginsRelativeArrangement="false" backgroundColor="#f0f0f0">
    <!-- Options button -->
    <LMRowView layoutMarginTop="6" layoutMarginLeft="18" layoutMarginRight="18">

        <UIButton style="systemButton" title="Options"
            titleLabel.font="HelveticaNeue-Light 17.0" tintColor="#4c8fbd"

    <!-- Pie chart view -->
    <Charts.PieChartView id="chartView" weight="1"/>

    <!-- Sliders -->
    <LMColumnView layoutMarginLeft="8" layoutMarginRight="8" layoutMarginBottom="24">
            <UISlider id="sliderX" minimumValue="1" maximumValue="25" value="1" weight="4"

            <UITextField id="sliderTextX" weight="1"
                font="HelveticaNeue-Light 15.0"

            <UISlider id="sliderY" minimumValue="1" maximumValue="200" value="1" weight="4"

            <UITextField id="sliderTextY" weight="1"
                font="HelveticaNeue-Light 15.0"

The results are shown below. They are virtually indistinguishable from the original (though the chart data differs slightly, since it appears to be randomly generated each time the app is run):

So, I was very happy to discover that, not only did MarkupKit work with the Charts library, I was able to use it as a drop-in replacement for the original XIB file in the demo application!

The latest version of MarkupKit can be downloaded here. See the project README for more information.

Installing MongoDB on 32-bit Ubuntu 15.10

I recently decided to install MongoDB on an old Mac Mini I use for testing. This particular device is too old to run the latest version of OS X, so I'm currently running the 32-bit version of Ubuntu 15.10 on it. Unfortunately, MongoDB no longer provides installation packages for 32-bit Linux distributions, so I had to set it up manually. Since this was a fairly cumbersome process, I thought I would share the steps I took in case they are of use to anyone:

  1. Download 32-bit MongoDB binaries:
    curl -O
    tar -zxvf mongodb-linux-i686-3.2.4.tgz
  2. Copy MongoDB binaries to /usr/bin:
    sudo cp mongodb-linux-i686-3.2.4/bin/* /usr/bin/
  3. Download startup script:
    curl > init.d
  4. Move startup script to /etc/init.d directory:
    sudo mv init.d /etc/init.d/mongod
    sudo chmod 755 /etc/init.d/mongod        
  5. Create configuration script /etc/mongod.conf:
      dbPath: /var/lib/mongo
        enabled: true
      engine: mmapv1
      destination: file
      logAppend: true
      path: /var/log/mongodb/mongod.log
      fork: true
      port: 27017
  6. Add "mongodb" user:
    sudo useradd --home-dir /var/lib/mongo --shell /bin/false mongodb
    sudo passwd mongodb
  7. Create /var/lib/mongo directory:
    sudo mkdir /var/lib/mongo
    sudo chown -R mongodb /var/lib/mongo
    sudo chgrp -R mongodb /var/lib/mongo
  8. Create /var/log/mongodb directory:
    sudo mkdir /var/log/mongodb
    sudo chown -R mongodb /var/log/mongodb
    sudo chgrp -R mongodb /var/log/mongodb
  9. Create /var/run/ file:
    sudo touch /var/run/
    sudo chown mongodb /var/run/
    sudo chgrp mongodb /var/run/
  10. Initialize service:
    sudo update-rc.d mongod defaults
  11. Restart server:
    sudo shutdown -r now

Java I/O Annoyances

While making some code updates the other day, I discovered a couple of potentially confusing features of the package that I wasn't previously aware of:

  1. The PrintStream and PrintWriter classes consume exceptions. From the PrintWriter documentation:

    Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

    Because I had incorrectly assumed that a PrintWriter would propagate any exceptions thrown by the underlying stream, I hadn't been calling checkError(). The result was that my servlet class, which was using the print writer returned by ServletResponse#getWriter(), failed to detect when a connection had been terminated by the client. The servlet simply continued writing to the output stream. Once I started calling checkError(), the response was correctly terminated:

    if (writer.checkError()) {
        throw new IOException("Error writing to output stream.");

    I couldn't find any explanation as to why these two classes were written this way, while all of the other classes in appear to simply propagate exceptions.

  2. The read(byte[], int, int) method of the InputStream class also consumes exceptions. From the Javadoc:

    The read(b, off, len) method for class InputStream simply calls the method read() repeatedly. If the first such call results in an IOException, that exception is returned from the call to the read(b, off, len) method. If any subsequent call to read() results in a IOException, the exception is caught and treated as if it were end of file.

    This is extremely misleading, since it completely obscures the fact that an error occurred and makes it appear as though the stream terminated normally.

So, even though this behavior is not what I had expected, at least it is documented, and is something I'll now be aware of when using these classes in the future.

Using Factory Methods to Simulate Map Literals in Java

Unlike many modern programming languages, Java does not support the notion of a "map literal"; that is, a map whose contents are declared using a dedicated language construct rather than being instantiated and populated via explicit API calls. For example, in Swift it is possible to create a dictionary (the Swift equivalent of a Java map) using the following syntax:

var dictionary = ["a": 1, "b": 2, "c": 3]

The result of executing this code is identical to the following, more verbose, version, which first allocates the dictionary and then populates it:

var dictionary = [String: Int]()

dictionary["a"] = 1
dictionary["b"] = 2
dictionary["c"] = 3

Similarly, an object can be constructed in JavaScript using the following literal syntax:

var object = {"a": 1, "b": 2, "c": 3};

or this more verbose equivalent:

var object = new Object();

object["a"] = 1;
object["b"] = 2;
object["c"] = 3;

Because Java does not support map literals, map instances must always be explicitly instantiated and populated. This is especially cumbersome if the map only needs to exist in the context of a single method call:

HashMap map = new HashMap();

map.put("a", 1);
map.put("b", 2);
map.put("c", 3);


Fortunately, it is possible to approximate the behavior of map literals in Java using factory methods. For example:

// Create a map from a variable length array of map entries
public static <K> Map<K, ?> mapOf(Map.Entry<K, ?>... entries) {
    HashMap<K, Object> map = new HashMap<>();

    for (Map.Entry<K, ?> entry : entries) {
        map.put(entry.getKey(), entry.getValue());

    return Collections.unmodifiableMap(map);

// Create a map entry
public static <K> Map.Entry<K, ?> entry(K key, Object value) {
    return new AbstractMap.SimpleImmutableEntry<>(key, value);

Using these methods, the previous example can be reduced to a single line of code:

process(mapOf(entry("a", 1), entry("b", 2), entry("c", 3)));

It may not be quite as elegant as the Swift or JavaScript versions, but it is a lot more convenient than creating and populating the map an element at a time.

.gitignore for Xcode 7

I end up rewriting this file for every Xcode project I create, so I thought I'd post it in case it is of use to anyone:


Comments and suggestions for improvement are welcome!

Creating a Grid Layout in iOS

As I recently mentioned over at DZone, working with auto layout in iOS has historically been somewhat difficult. Having previously built applications for other platforms with more robust layout management capabilities, I expected to find something comparable when I started doing iOS development. One of the first things I looked for was a "grid" layout that I could use to automatically arrange views in rows and columns. Such features are common on other platforms and are often used to lay out many fundamental elements of an application's user interface, from side bars and menus to feedback forms. I was disappointed to discover that nothing like this existed for iOS.

With iOS 9, Apple introduced the UIStackView class. By combining a vertical stack view with several horizontal stack views, I could much more easily create the kind of layouts I needed. And, as I mentioned in the DZone article, MarkupKit makes it even easier to work with stack views, using a declarative model similar to Android and Windows development.

For example, the following markup creates a simple form that allows a user to enter a name and address. The labels and text fields are baseline-aligned, and the entire form is hosted in a scroll view. The text fields are assigned a horizontal content hugging priority of 0 to allow them to resize:

<LMScrollView fitToWidth="true" backgroundColor="#ffffff">
    <UIStackView axis="vertical" layoutMarginsRelativeArrangement="true" layoutMargins="20" spacing="12">
        <UIStackView axis="horizontal" alignment="firstBaseline" spacing="8">
            <UILabel text="Name"/>
            <UITextField id="nameTextField" borderStyle="roundedRect"

        <UIStackView axis="horizontal" alignment="firstBaseline" spacing="8">
            <UILabel text="Address"/>

            <UIStackView id="addressStackView" axis="vertical" spacing="8">
                <UITextField borderStyle="roundedRect" placeholder="Street"

                <UIStackView axis="horizontal" alignment="firstBaseline" spacing="8">
                    <UITextField id="cityTextField" placeholder="City" borderStyle="roundedRect"
                    <UITextField id="stateTextField" placeholder="State" borderStyle="roundedRect"
                    <UITextField id="zipTextField" placeholder="Zip" borderStyle="roundedRect"

Unfortunately, stack views don't natively provide a way to vertically align controls, so the output of this markup doesn't look quite right:

What's worse, the text fields don't retain their original sizes once text has been entered into them:

To ensure that the controls are aligned and maintain a fixed size, the view controller needs to install some additional constraints in viewDidLoad():

import UIKit
import MarkupKit

class StackViewController: UIViewController {
    weak var nameTextField: UITextField!

    weak var addressStackView: UIStackView!

    weak var cityTextField: UITextField!
    weak var stateTextField: UITextField!
    weak var zipTextField: UITextField!

    override func loadView() {
        view = LMViewBuilder.view(withName: "StackViewController", owner: self, root: nil)

    override func viewDidLoad() {

        title = "Stack Views"

        // Create custom constraints
            // Equal-width
            NSLayoutConstraint(item: nameTextField, attribute: NSLayoutAttribute.width,
                relatedBy: NSLayoutRelation.equal, toItem: addressStackView, attribute: NSLayoutAttribute.width,
                multiplier: 1.0, constant: 0),

            // Weight
            NSLayoutConstraint(item: stateTextField, attribute: NSLayoutAttribute.width,
                relatedBy: NSLayoutRelation.equal, toItem: cityTextField, attribute: NSLayoutAttribute.width,
                multiplier: 2.0 / 3.0, constant: 0),
            NSLayoutConstraint(item: zipTextField, attribute: NSLayoutAttribute.width,
                relatedBy: NSLayoutRelation.equal, toItem: stateTextField, attribute: NSLayoutAttribute.width,
                multiplier: 2.0 / 2.0, constant: 0)

With the additional constraints, the form behaves as expected:

However, there is an even easier way to create this layout. MarkupKit's LMColumnView and LMRowView classes can also be used to create a table-like arrangement of UI elements. Further, LMColumnView provides an alignToGrid property that can be used to ensure that nested subviews are vertically aligned, and the form fields can be weighted to ensure that they retain their relative sizes:

<LMScrollView fitToWidth="true" backgroundColor="#ffffff">
    <LMColumnView alignToGrid="true" layoutMargins="20">
        <LMRowView alignToBaseline="true">
            <UILabel text="Name"/>
            <UITextField class="textfield" borderStyle="roundedRect" weight="1"/>

        <LMRowView alignToBaseline="true">
            <UILabel text="Address"/>

            <LMColumnView weight="1">
                <UITextField borderStyle="roundedRect" placeholder="Street"/>

                <LMRowView alignToBaseline="true">
                    <UITextField placeholder="City" borderStyle="roundedRect" weight="3"/>
                    <UITextField placeholder="State" borderStyle="roundedRect" weight="2"/>
                    <UITextField placeholder="Zip" borderStyle="roundedRect" weight="2"/>

This markup produces output identical to the final stack view example, but is much less verbose, and doesn't require the use of custom constraints or content priorities:

MarkupKit's row and column views don't offer all of the features provided by UIStackView. For example, stack views provide additional alignment and distribution options as well as the ability to animate changes to their contents. However, the weight-based distribution and column alignment options supported by LMColumnView and LMRowView make them a great alternative for creating grid layouts in iOS applications.

For more information, see the MarkupKit README or the following examples: