Thursday, October 11, 2007

Java data validation trick with bit-twiddling

I have a specialized value object with the property that fields can be null but only in a particular order:

class Data {
    private final String field1;
    private final String field2;
    private final String field3;

    public Data(String field1, String field2,
            String field3) {
        if (!valid(field1, field2, field3))
            throw new IllegalArgumentException();

        this.field1 = field1;
        this.field2 = field2;
        this.field3 = field3;
    }

    // ...
}

The rule is simple: Given the order of the fields 1-4, any later field may be null provided that no earlier field is null. That is, "abc", "def", null is ok but "abc", null, "ghi" is invalid.

So the question becomes, How to code up valid?.

The straight-forward approach of nested if-else blocks becomes particularly unwieldy as more fields are added. But it turns out there is a clever solution using bit-twiddling:

private static boolean valid(String... fields) {
    byte flag = 0; // Fails after 8 fields

    // Sets the i-th bit for each non-null field
    for (int i = 0; i < fields.length; ++i)
        if (null != fields[i])
            flag |= (1 << i);

    // Math trick: 2n ∧ 2n-1 = 0
    return 0 == (flag & flag + 1);
}

In words: the flag has a 1-bit for each non-null field in argument order. The validation condition only holds when the 1 bits are in sequence starting at the 0-th position with no gaps, e.g., 00000111. That particular bit pattern is the same as one less than some power of two. Use the math fact that in bit arithmetic, 2n ∧ 2n-1 = 0 to check the condition.

Thanks to this powers-of-two problem for pointing the way.

Wednesday, October 10, 2007

Dethreading a chicken

Anyone who has tried knows what messy task deboning a chicken is (unless you are Morou Ouattara.) Likewise I face the messy task of protecting multi-threaded legacy code from itself.

I face a complex graph with an elaborate API. It is thread-safe in that individual nodes are locked, but it is not thread-consistent: changes traversing the graph are not isolated from each other.

What to do?

One approach which is of general application is to dethread the data structure. That is, turn it from multi-threaded access to single-threaded.

The task is made much simpler by the JDK5 concurrency library. First, create a facade for the original API:

interface Complexity {
    void methodOne(int argOne);
    int methodTwo();
    // ... ad nauseum
}

Next create command classes for each method call in the API:

class MethodOne
        extends Runnable {
    private final Complexity realGraph;
    private final int argOne;

    MethodOne(Complexity realGraph, int argOne) {
        this.realGraph = realGraph;
        this.argOne = argOne;
    }

    void run() {
        realGraph.methodOne(argOne);
    }
}

class MethodTwo
        extends Callable<Integer> {
    private final Complexity realGraphy;

    MethodTwo(final Complexity realGraph) {
        this.realGraph = realGraph;
    }

    Integer call() {
        return realGraph.methodTwo();
    }
}

// ... ad nauseum

Finally, wire the facade to forward calls to a queue for replay into the real graph with a dedicated single thread:

class SingleThreadComplexity implements Complexity {
    private final ExecutorService commands
            = Executors.newSingleThreadExecutor();
    private final Complexity realGraph
            = new OriginalMultiThreadComplexity();

    public void methodOne(int argOne) {
        commands.submit(new MethodOne(realGraph, argOne);
    }

    public int methodTwo() {
        try {
            return commands.submit(new MethodTwo(realGraph)).get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    // ... ad nauseum
}

Finishing up

Unless the caller has special latency needs violated by the queueing of commands, the facade is a drop-in replacement for the original complex graph but with the new property that the original is always accessed sequentially from the same thread. Goetz calls this property thread confinement.

The complex, messy graph—a fowl thing indeed—is now dethreaded.

Friday, September 14, 2007

Running "N" foreground tasks in Java

A handy helper method for running "N" foreground tasks in Java with a timeout. A more sophisticated technique would permit examination of job status:

/**
 * Invokes <var>n</var> copies of the given <var>runnable</var>, timing out
 * after <strong>10 unit</strong> with {@code InterruptedException}.
 *
 * @param n the number of threads to run
 * @param runnable the thread body to execute
 * @param timeout the timeout
 * @param unit the timeout unit
 *
 * @throws InterruptedException if timed out
 */
public static void invokeNCopiesWithTimeout(final int n,
        final Runnable runnable, final long timeout, final TimeUnit unit)
        throws InterruptedException {
    final ExecutorService pool = newFixedThreadPool(n);

    pool.invokeAll(
            Collections.<Callable<Void>>nCopies(n, new Callable<Void>() {
                public Void call() {
                    runnable.run();
                    return null;
                }
            }));

    pool.awaitTermination(timeout, unit);
}

I find this particularly useful for blackbox concurrency testing. I run, say, 100 threads which both read and write to a common data structure, and accept the lack of exceptions as empirical evidence of safeness. (In truth, it only provides a comfort zone, not a proof. Reasoning about threads is difficult when maintaining disparate interacting components.)

Monday, September 10, 2007

Performing fixed amounts of work with blocking queues

A colleague of mine showed me a nice idiom with BlockingQueue for performing a fixed amount of work:

final List<T> work = new ArrayList<T>(N);

for (;;) {
    // Wait until there is some work
    work.add(queue.take());
    // Get more work, if available
    queue.drainTo(work, N - 1);

    for (final T item : work)
        process(item);

    work.clear();
}

This idiom works on 1 to N chunks at a time efficiently and succinctly.

An example use is batching SQL updates. At the top of the loop begin the batch transaction after take() and finish the batch after the processing loop.

UPDATE: This idiom is also more efficient when unbounded amounts of work:

queue.drainTo(work);

Every call to take() is blocking and checks a lock — essentially giving up any remaining thread time slice. Using drainTo(work) avoids this lost thread work, cutting down on lock checks.

Tuesday, August 21, 2007

Cygwin BASH wrapper for Maven deploy:deploy-file

I frequently use Maven's deploy:deploy-file mojo for building project-local repositories.

Many interesting 3rd-party Java libraries are not (yet) available from public Maven repositories (the otherwise excellent dev.java.net projects are particularly weak in this respect), but I want to use them in my project POM. What to do?

I store them with my project. This is not an ideal solution, but it is practical.

To help me deploying jars, sources and javadocs I wrote a simple BASH wrapper script for Cygwin (to run under Linux/UNIX requires a trivial change). Here is typical use:

$ mvn-file-deploy ~/IdeaProjects/Scratch/lib cool-library-1.0.4.jar org.cool.library:cool-library:1.0.4
$ mvn-file-deploy -S ~/IdeaProjects/Scratch/lib cool-library-1.0.4-sources.jar org.cool.library:cool-library:1.0.4
$ mvn-file-deploy -J ~/IdeaProjects/Scratch/lib cool-library-1.0.4-javadocs.jar org.cool.library:cool-library:1.0.4

And the script itself:

#!/bin/bash

function help()
{
    cat <<'EOH' | fmt
Usage: mvn-file-deploy [options] REPO_PATH FILE_PATH DESCRIPTOR [CLASSIFIER]

Use mvn-file-deploy as a helper for 'mvn deploy:deploy-file' when using Cygwin.

EOH
    cat <<'EOH'
Options:
  -h, --help          Print this help message
      --version       Print program version
  -S, --sources       Deploy sources
  -J, --javadocs      Deploy javadocs
  -q, --quiet         Do not print maven command
EOH
    cat <<'EOH' | fmt

Other options are passed to Maven.  (BROKEN)

Examples:

The most common use is to run it like this:

    $ mvn-file-deploy C:/my/project/lib C:/some/interesting.jar groupId:artifactId:version

Or if you use a classifier (e.g., jdk5):

But sometimes like this.

    $ mvn-file-deploy C:/my/project/lib C:/some/interesting.jar groupId:artifactId:version classifier

Report bugs to <binkley@alumni.rice.edu>.
EOH
}

function version()
{
    cat <<'EOV' | fmt
mvn-file-deploy 1.0
Copyright (C) 2007 JPMorganChase, Inc.  All rights reserved.
EOV
}

function fatal()
{
    echo "$0: $*" >&2
    exit 2
}

function usage() 
{
    cat <<'EOU' | fmt >&2
usage: mvn-file-deploy [options] REPO_PATH FILE_PATH DESCRIPTOR [CLASSIFIER]
EOU
}

eval set -- "$(getopt -o hJSq --long help,javadocs,sources,quiet,version -n "$0" -- "$@")"

declare -a maven_opts
declare -a args

for opt
do
    shift
    case "$opt" in
        -h|--help ) help ; exit 0 ;;
        -J|--javadocs ) classifier=-Dclassifier=javadocs ;;
        -S|--sources ) classifier=-Dclassifier=sources ;;
        --version ) version ; exit 0 ;;
        -q|--quiet ) quiet=t ; maven_opts=("${maven_opts[@]}" "$opt") ;;
        -- ) break ;;
        -* ) maven_opts=("${maven_opts[@]}" "$opt") ;;
    esac
done

case $# in
    3 ) repo_path="$1"
        file_path="$2"
        descriptor="$3" ;;
    4 ) repo_path="$1"
        file_path="$2"
        descriptor="$3"
        classifier=-Dclassifier="$4" ;;
    * ) usage ; exit 2 ;;
esac

(cd "$repo_path" 2>/dev/null) || \
    fatal "No such repository path: $repo_path"

repo_url="file://$(cygpath -am "$repo_path")"
file_path="$(cygpath -am "$file_path")"

[[ -r "$file_path" ]] || \
    fatal "No such artifact: $file_path"

triplet=($(echo $descriptor | tr : ' '))

(( 3 == ${#triplet[*]} )) || \
    fatal "Descriptor not groupId:artifactId:version format: $descriptor"

packaging=-Dpackaging="${file_path##*.}"

[[ -n "$quiet" ]] ||
    echo mvn "${maven_opts[@]}" deploy:deploy-file -Durl="$repo_url" \
        -DrepositoryId=project -Dfile="$file_path" -DgroupId=${triplet[0]} \
        -DartifactId=${triplet[1]} -Dversion=${triplet[2]} \
        $packaging $classifier
exec mvn "${maven_opts[@]}" deploy:deploy-file -Durl="$repo_url" \
    -DrepositoryId=project -Dfile="$file_path" -DgroupId=${triplet[0]} \
    -DartifactId=${triplet[1]} -Dversion=${triplet[2]} \
    $packaging $classifier

Sunday, August 19, 2007

Recursive "toString"

Sometimes for debugging I want to dump an object recursively. That is, I'd like to see not just an Apache Commons Lang-style toString, but a recursive version which descends fields to display their inner bits as well.

Rather than complain, I coded my own. Enjoy!

public static String recursiveToString(final Object o) {
    final StringBuilder buffer = new StringBuilder();

    recursiveToString(new StringBuilder(), o, buffer,
            new HashSet<Object>());

    return buffer.toString();
}

private static void recursiveToString(final StringBuilder prefix,
        final Object o, final StringBuilder buffer,
        final Set<Object> seen) {
    if (null == o) {
        buffer.append("null\n");
        return;
    }

    // Mark back references with angle brackets
    if (seen.contains(o)) {
        buffer.append('<');
        objectToString(o, buffer);
        buffer.append(">\n");
        return;
    }

    seen.add(o);

    objectToString(o, buffer);

    // TODO: More clever to see if protection domain is in the JDK
    if (shouldNotRecurse(o, o.getClass().getPackage().getName())) {
        buffer.append('=');
        buffer.append(o);
        buffer.append('\n');
        return;
    }

    buffer.append("={");
    buffer.append('\n');

    final StringBuilder fieldPrefix = new StringBuilder(prefix);
    fieldPrefix.append("  ");

    for (final Field field : o.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        buffer.append(fieldPrefix);
        buffer.append(field.getName());
        buffer.append('(');
        buffer.append(Modifier.toString(field.getModifiers()));
        buffer.append(")=");

        try {
            recursiveToString(fieldPrefix, field.get(o), buffer, seen);
        } catch (final IllegalAccessException e) {
            buffer.append("? (");
            buffer.append(e.getMessage());
            buffer.append(')');
        }
    }

    buffer.append(prefix);
    buffer.append("}\n");
}

private static boolean shouldNotRecurse(final Object o,
        final String packageName) {
    try {
        return (packageName.startsWith("java.") || packageName
                .startsWith("javax.")) && !Object.class
                .getMethod("toString")
                .equals(o.getClass().getMethod("toString"));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}

private static void objectToString(final Object o,
        final StringBuilder buffer) {
    buffer.append(o.getClass().getName());
    buffer.append('@');
    buffer.append(Integer.toHexString(System.identityHashCode(o)));
}

Luboš Motl answers some physics questions

Wow! I miss physics sometimes.

Wednesday, July 25, 2007

Monday, July 09, 2007

More with Java enums: simulating inheritance

One drawback to the Java enum is the lack of inheritance. Java uses inheritance for many reasons, one of which is implementation inheritance. (In C++ you would use private inheritance for the same reason.)

To recapture implementation inheritance with enums, use the visitor pattern:

class Convert {
    public interface Vivid {
        char character();
    }

    public static <E extends Enum<E> & Vivid> E from(
            E[] values, char character) {
        for (E e : values)
            if (e.character() == character)
                return e;

        throw new IllegalArgumentException("Boring: " + character);
    }
}

enum Men implements Convert.Vivid {
    OLIVIER('L'), WAYNE('J');

    private final char character;

    Men(char character) {
        this.character = character;
    }

    public char character() {
        return character;
    }

    public static Men valueOf(char character) {
        return Convert.from(values(), character);
    }
}

The implementation of valueOf(char):Men is handled in Convert and can be reused in other enum classes.

Thursday, June 14, 2007

Download web pages in BASH

BASH is quite amazing. From Bhaskar V. Karambelkar comes Bash shell tricks and this gem (with some small corrections):

function headers()
{
    server=$1
    port=${2:-80}
    exec 5<>/dev/tcp/$server/$port
    echo -ne "HEAD / HTTP/1.0\r\nHost: $server:$port\r\n\r\n" >&5
    cat <&5
    exec 5<&-;
}

I work behind a corporate firewall, so I need web proxy settings. No problem, BASH is still amazing:

function webget()
{
    declare -a parts
    parts=($(echo $1 | tr / ' '))
    protocol=${parts[0]}
    server=${parts[1]}
    path=$(echo $1 | sed "s,$protocol//$server,,")

    exec 5<>/dev/tcp/$http_proxy_server/$http_proxy_port
    echo -ne "GET $path HTTP/1.0\r\nHost: $server\r\n\r\n" >&5
    cat <&5
    exec 5<&-;
}

Usage is obvious:

$ webget http://www.ccil.org/jargon/
# Out pops the top page for Jargon File Resources

UPDATE: Also useful for talking to SMTP (email) servers:

$ exec 5<>/dev/tcp/localhost/smtp
$ read -u 5 line
$ echo $line
220 my.full.host.name ESMTP ...
$ echo QUIT >&5
$ read -u 5 line
$ echo $line
221 2.0.0 my.full.host.name closing connection

This also shows that BASH knows to map the SMTP service to port 25.

Monday, June 11, 2007

Excellent advice on Java exceptions

Excellent advice on avoiding exception anti-patterns in Java from Tim McCune, Exception-Handling Antipatterns. Particularly noxious are the anti-patterns which swallow exceptions.

Quick trivial quiz.

  1. Does this code compile?
  2. If it compiles, what happens at runtime?
try {
    throw null;
} catch (final Throwable t) {
    System.out.println("t = " + t);
}

Before you chuckle too hard, recall that this is a perfectly valid C++ program, if contrived, and prints Something integral: 0:

#include <iostream>

int
main(const int argc, const char *argv[])
{
  try {
    throw 0;
  } catch (const int i) {
    std::cout << "Something integral: " << i << std::endl;
  } catch (...) {
    std::cout << "Something exceptional." << std::endl;
  }
}

UPDATE: I fixed the title.

Friday, June 08, 2007

Style, taste, sensibilities in coding

Chris Aston has an eminently sensible post on programming in the small (not his words[*]), Coding Against the Grain, on some coding style and taste points that have been part of my habits nearly as long as I have programmed.

He emphasizes balance and clarity and cautions against turning objects into stand-ins for global variables: the function is given its due.

To elaborate on his points, I often treat objects as small bundles of encapsulated state with public methods that tie private fields to private functions. A simple example illustrates:

class UsefulExample {
    private int count;

    public String repeatMessage(String message) {
        return repeatMessage(message, count);
    }

    static String repeatMessage(String message,
            int count) {
        StringBuilder builder = new StringBuilder(message);

        for (int i = 1; i < count; ++i)
            builder.append(' ').append(message);

        return builder.toString();
    }
}

This example is not very interseting, but it makes it easy to list benefits:

  • Testing the functions independent of the encapsulated state is easy.
  • Changing the algorithm of functions does not affect public methods.
  • If the functions are common across classes, refactoring them out to a common utility class is simple.
  • Design changes in the encapsulated state do not impact functions.

In effect, the I have decoupled encapsulated state within the object from implementation algorithms within the functions, and use public methods to connect them together.

This is carrying a common design pattern from "programming in the large" into "programming in the small", with the same advantages. The decoupling of state from algorithm is an old idea [PDF].

More on programming in the small

Ivan Moore has a delightful series of posts on Programming in the Small well worth reading.

The all-dancing, all-singing LockSmith plugin for IntelliJ

I've never been willing to pay for IntelliJ plugins, but LockSmith from the very clever Sixth & Red River may change my mind.

This is a list of features which made me look twice:

  • Split Lock
  • Merge Locks
  • Make Class Thread-Safe
  • Convert Field to Atomic
  • Convert Field to ThreadLocal
  • Lock Call-Sites of Method
  • Convert Simple Lock to Read-Write Lock
  • Convert Read-Write Lock to Simple Lock
  • Convert Synchronization Field to Lock
  • Split Critical Section
  • Shrink Critical Section
  • Merge Critical Sections

Fortunately, I work for an excellent employer, and may be able to wrangle a group bulk license for my team for LockSmith and other wonderful plugins.

Friday, May 04, 2007

Getting more from streams in Bash

A handy trick in Bash is to split a stream to process it in more than one way without saving a temporary copy:

# Make 3 a copy of 1 (stdout)
exec 3>&1
result="$(command to generate stream \
    | tee /dev/fd/3 \
    | command to process stream)"
# Now work with $result
# The original stream also went to the console

The actual case I worked with this morning was a very simple demonstration:

#!/bin/bash

exec 3>&1

echo -e "Bob is my friend.\nFred is my friend, too." \
    | tee /dev/fd/3 \
    | cut -f1 -d' ' >&2

Which simply prints:

Bob is my friend.
Fred is my friend.

to stdout and to stderr it prints:

Bob
Fred

That most excellent Erlang short

There is a short making the rounds, Erlang: The Movie. It is witty, indirect and informative. And subtly hilarious.

As programming language propaganda goes, this is highly effective: I really want to go out and try Erlang after watching. Nicely done.

Wednesday, May 02, 2007

Increasing log4j verbosity

To programmatically increase log4j verbosity, a simple code snippet does the trick:

final Logger rootLogger = Logger.getRootLogger();

rootLogger.setLevel(Level.toLevel(
        rootLogger.getLevel().toInt() + 1,
        Level.ALL));

I use this to handle the -verbose command-line switch. Repeating the switch keeps increasing my program's verbosity.

Naturally there are wrinkles with a complex log4j configuration, but the idiom remains.

Tuesday, May 01, 2007

Subversion best practices, branching

A useful link on Subversion, Subversion Best Practices. Really nice are the links into the Red Bean book filling out each point.

What I am looking for at the moment is a good discussion on using Subversion to fork a project. I have internal libraries at work which are not ameniable to multiple teams working on them. My best option is to fork the code and merge back in fixes from the original.

This looks like a good start on this kind of branching. I like the example shell scripts for automating portions of the process.

Thursday, April 12, 2007

Good temporary files in Ant

I was reading this nice post on unsigning jars with Ant when this line caught my eye:

<tempfile destdir="${java.io.tmpdir}"
          prefix="unsign-"
          property="temp.file"/>

I was struck by an Aha! moment—using ${java.io.tmpdir} is clearly the Right Thing for creating temporary files in Java. Why not also in Ant?

Wednesday, April 11, 2007

The fallacy of soft coding

Today's Worse Than Failure has a brilliant post on soft coding.

It begins with a strong exposition answering "what is soft coding?" — the example business method is just about ideal for what a business method should be. I wish I could hire him!

The moral is simple: don't be a soft coder; in some respects it is worse than hard coding.

Most used tool

What is the most used tool in my daily work life? The Java compiler? IntelliJ IDEA? Perl?

Actually it is Mark Edgar's PuTTYcyg, a PuTTY patch for Cygwin terminal. This runs BASH from Cygwin inside a PuTTY xterm-ish window, making my daily work on Windows rather more productive.

You see, I'm a command-line sort of guy. And BASH is indispensable to my habits; hence Cygwin. And the default DOS box terminal is lame.

Using PuTTYcyg is a cinch. Download, unpack and add a shortcut to your desktop for C:\puttycyg-20070320\putty.exe - (or wherever you unpack to; the important part is the trailing solo hyphen). I usually change the icon to the Cygwin one (%SystemDrive%\cygwin\cygwin.ico, YMMV).

Tuesday, April 03, 2007

Google's excellent code coloring

This looks like fun:

<html>
<head>
<title>Example</title>
<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>
</head>
<body onload="prettyPrint()">
<h1>C</h1>
<pre class="prettyprint">void
main(char* argv[])
{
    printf("Hello, Bob.\n");
}</pre>
<h1>Java</h1>
<pre class="prettyprint">public class Main {
    public static void main(final String[] args) {
        System.out.println("Hello, Bob.");
    }
}</pre>
<h1>Shell</h1>
<pre class="prettyprint">echo "Hello, Bob."</pre>
</body>
</html>

Friday, March 23, 2007

Writing JUnit 4 parameterized tests with varargs data

One of the many excellent new features of JUnit 4 is parameterized tests. These are data-driven tests where a test case runs repeatedly against a collection of test data, as if each run were its own test case.

A standard example:

@RunWith(Parameterized.class)
public class ExampleDataDrivenTest {
    public static final class Data {
        private final String name;

        public Data(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    private final List<Data> data;

    public ExampleDataDrivenTest(final Data datum1, final Data datum2) {
        System.out.println("ExampleDataDrivenTest");

        this.data = asList(datum1, datum2);
    }

    @Test
    public void dumpData() {
        for (final Data datum : data)
            System.out.println("datum = " + datum);
    }

    @Parameters
    public static Collection<Data[]> data() {
        final Data[][] data = new Data[][]{
                {new Data("apple"), new Data("core")}};

        return asList(data);
    }
}

This produces:

ExampleDataDrivenTest
datum = apple
datum = core

This works great for a fixed number of test data, but I want to test a variable number of data. The change is straight-forward once you recall that the varargs Java language feature is implemented as an array:

@RunWith(Parameterized.class)
public class ExampleDataDrivenTest {
    public static final class Data {
        private final String name;

        public Data(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    private final List<Data> data;

    public ExampleDataDrivenTest(final Data... data) {
        System.out.println("ExampleDataDrivenTest");

        this.data = asList(data);
    }

    @Test
    public void dumpData() {
        for (final Data datum : data)
            System.out.println("datum = " + datum);
    }

    @Parameters
    public static Collection<Data[][]> data() {
        final Data[][][] data = new Data[][][]{
                {{new Data("apple"), new Data("core")}}};

        return asList(data);
    }
}

Reflect on the constructor and you see:

public ExampleDataDrivenTest(ExampleDataDrivenTest$Data[])

This makes the change more obvious.

I can now write my annotated parameters as:

    @Parameters
    public static Collection<Data[][]> data() {
        final Data[][][] data = new Data[][][]{{{ /* no data */ }},
                {{new Data("apple"), new Data("core")}},
                {{new Data("baltimore")}}};

        return asList(data);
    }

To produce:

ExampleDataDrivenTest
ExampleDataDrivenTest
datum = apple
datum = core
ExampleDataDrivenTest
datum = baltimore

Saturday, March 10, 2007

Storing jars in a Maven project

One of the sweetest things about Maven is that depedencies are stored external to your sources: if you depend on Apache Commons Lang 2.3, for example, then you can stick this in the dependencies section of your pom.xml and stop worrying:

<depedency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.3</version>
</dependency>

But what do you do when your dependency is not available in a public Maven repository? For example, the library is too new to be widely available, or is proprietary like the Oracle JDBC driver?

One tack is to establish an internal repository and refer to that in your pom.xml. But sometimes that is not practical, perhaps because of corporate network use restrictions, or for very small projects.

Before Maven, common practice was to stash dependencies into a directory named lib/ or similar underneath the root of your project sources. When no other solution presents itself, you can follow that practice but keep using Maven.

In your pom.xml, add this top-level section:

<repositories>
    <repository>
        <id>project</id>
        <name>Project Maven Repository</name>
        <layout>default</layout>
        <url>file:///./lib</url>
    </repository>
</repositories>

This establishes the lib/ directory underneath your project as a Maven repository relative to your project root. Now you can stash dependencies there, store them with the rest of your project resources, but keep using Maven.

A little bit more

Often I have to re-lookup the documentation on deploy:deploy-file so that I can put a dependency in an internal repository or in the project repository as described above. Here is a magic incantation example:

$ cd /PATH-TO-guice-1.0-DOWNLOAD
# Checkout the SVN 1.0 tag sources to src/
# Note -- need to use the -Dversion=1.0 switch
# because pom says 1.0-RC2 in spite of tag.  Then:
$ mvn deploy:deploy-file \
    -Durl=file://C:/FULL-PROJECT-PATH/lib \
    -DrepositoryId=project -Dfile=guice-1.0.jar \
    -DpomFile=src/pom.xml -Dversion=1.0
# Pack up the javadocs and sources into jars, then:
$ mvn deploy:deploy-file \
    -Durl=file://C:/FULL-PROJECT-PATH/lib \
    -DrepositoryId=project \
    -Dfile=guice-1.0-javadocs.jar \
    -DpomFile=src/pom.xml -Dversion=1.0 \
    -Dclassifier=javadocs
$ mvn deploy:deploy-file \
    -Durl=file://C:/FULL-PROJECT-PATH/lib \
    -DrepositoryId=project \
    -Dfile=guice-1.0-sources.jar \
    -DpomFile=src/pom.xml -Dversion=1.0 \
    -Dclassifier=sources

I now have the splediferous Guice 1.0 dependency in my project repository, and can use it in my pom.xml with:

<depedency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>1.0</version>
</dependency>