<?xml version="1.0"?>
<rss version="2.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007" xmlns:atom="http://www.w3.org/2005/Atom">
   <channel>
      <title>hjug-blogs</title>
      <description>This is the aggregation of the blogs of the HJUG members</description>
      <link>http://pipes.yahoo.com/pipes/pipe.info?_id=npUcRlYc3BGKs9yy1fC6Jw</link>
      <atom:link rel="next" href="http://pipes.yahoo.com/pipes/pipe.run?_id=npUcRlYc3BGKs9yy1fC6Jw&amp;_render=rss&amp;page=2"/>
      <pubDate>Thu, 01 Oct 2015 15:52:02 +0000</pubDate>
      <generator>http://pipes.yahoo.com/pipes/</generator>
      <item>
         <title>JUnit @Rule for a SQL transaction</title>
         <link>http://binkley.blogspot.com/2015/09/junit-rule-for-sql-transaction.html</link>
         <description>&lt;p&gt;I needed to run some Java test code in a SQL transaction.  It modifies the database, changes that should be 1) invisible to other tests, and 2) thrown away after tests finish.&lt;/p&gt; &lt;p&gt;I am using JUnit (of course) so I wrote a &lt;code&gt;@Rule&lt;/code&gt; to provide a transaction to my test methods (note I'm using Lombok for convenience):&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@RequiredArgsConstructor
public final class SQLTransactionRule
        extends ExternalResource {
    private final DataSource original;
    private final String user;
    private final String password;
    private final Consumer testDataSource;

    private Connection conn;

    public SQLTransactionRule(final DataSource original,
            final Consumer testDataSource) {
        this(original, null, null, testDataSource);
    }

    @Override
    protected void before()
            throws Throwable {
        super.before();
        beginTransaction();
        testDataSource.accept(testDataSource(conn));
    }

    @Override
    protected void after() {
        testDataSource.accept(null);
        rollbackTransaction();
        super.after();
    }

    private void beginTransaction() {
        try {
            final Connection conn = original.getConnection(user, password);
            conn.setAutoCommit(false);
            this.conn = conn;
        } catch (final SQLException e) {
            throw new RuntimeException(
                    format(&quot;Cannot create transaction from %s: %s&quot;, original,
                            getRootCause(e)), e);
        }
    }

    private void rollbackTransaction() {
        try {
            conn.rollback();
        } catch (final SQLException e) {
            throw new RuntimeException(
                    format(&quot;Cannot rollback transaction to %s: %s&quot;, original,
                            getRootCause(e)), e);
        }
    }

    private DataSource testDataSource(final Connection conn) {
        return (DataSource) newProxyInstance(getClass().getClassLoader(),
                new Class[]{DataSource.class}, (proxy, method, args) -&amp;gt; {
                    System.out.println(&quot;SQLTransactionRule.testDataSource&quot;);
                    if (Object.class.equals(method.getDeclaringClass()))
                        return method.invoke(proxy, args);
                    else if (&quot;getConnection&quot;.equals(method.getName()))
                        return conn;
                    else
                        return method.invoke(original, args);
                });
    }
}&lt;/pre&gt; &lt;p&gt;The motivation for the &lt;code&gt;Consumer&lt;/code&gt; of &quot;testDataSource&quot; and for the proxied data source was avoidance of dependencies.  Original code has this convenience method, but I decided that was a concern of the test code not the &lt;code&gt;@Rule&lt;/code&gt;:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public JdbcTemplate newJdbcTemplate() {
    return new JdbcTemplate(testDataSource);
}&lt;/pre&gt; &lt;p&gt;Of course there are tests for the &lt;code&gt;@Rule&lt;/code&gt; as well!  And &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://tedvinke.wordpress.com/2013/12/17/mixing-junit-hamcrest-and-mockito-explaining-nosuchmethoderror/&quot; title=&quot;Mixing JUnit, Hamcrest and Mockito: Explaining java.lang.NoSuchMethodError: org/hamcrest/Matcher.describeMismatch&quot;&gt;this post on Mockito&lt;/a&gt; was handy.&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@RunWith(MockitoJUnitRunner.class)
public final class SQLTransactionRuleTest {
    @Mock
    private DataSource original;
    @Mock
    private Connection conn;

    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    private SQLTransactionRule rule;
    private DataSource testDataSource;

    @Before
    public void setUp()
            throws SQLException {
        when(original.getConnection(anyString(), anyString())).
                thenReturn(conn);
        rule = new SQLTransactionRule(original,
                testDataSource -&amp;gt; this.testDataSource = testDataSource);
    }

    @Test
    public void shouldExecuteStatement()
            throws Throwable {
        final boolean[] called = {false};
        executeStatement(() -&amp;gt; called[0] = true);
        assertThat(called[0], is(true));
    }

    @Test
    public void shouldPublishTestDataSource()
            throws Throwable {
        executeStatement(
                () -&amp;gt; assertThat(testDataSource, is(notNullValue())));
    }

    @Test
    public void shouldReuseOriginalConnection()
            throws Throwable {
        executeStatement(() -&amp;gt; assertThat(testDataSource.getConnection(),
                is(sameInstance(conn))));
    }

    @Test
    public void shouldTransact()
            throws Throwable {
        executeStatement(() -&amp;gt; verify(conn).setAutoCommit(eq(false)));
        verify(conn).rollback();
    }

    @Test
    public void shouldDescribe()
            throws Throwable {
        thrown.expect(AssertionError.class);
        thrown.expectMessage(containsString(&quot;alpha&quot;));
        thrown.expectMessage(containsString(&quot;beta&quot;));

        executeStatement(() -&amp;gt; assertThat(&quot;alpha&quot;, is(equalTo(&quot;beta&quot;))));
    }

    @FunctionalInterface
    private interface RunMe {
        void execute()
                throws Throwable;
    }

    private void executeStatement(final RunMe statement)
            throws Throwable {
        rule.apply(new Statement() {
            @Override
            public void evaluate()
                    throws Throwable {
                statement.execute();
            }
        }, EMPTY).evaluate();
    }
}
&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-8484910744418409958</guid>
         <pubDate>Thu, 10 Sep 2015 19:43:00 +0000</pubDate>
      </item>
      <item>
         <title>REST API best practices</title>
         <link>http://binkley.blogspot.com/2015/06/rest-api-best-practices.html</link>
         <description>&lt;p&gt;Vinay Sahni of &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://enchant.com/&quot;&gt;Enchant&lt;/a&gt; writes &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api&quot; title=&quot;Best Practices for Designing a Pragmatic RESTful API&quot;&gt;&lt;cite&gt;Best Practices for Designing a Pragmatic RESTful API&lt;/cite&gt;&lt;/a&gt;, a complete, current best practices article on REST APIs, chock full of explanation, examples and real APIs from top web sites.  Enchant itself is a good example &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://dev.enchant.com/api/v1&quot;&gt;how to document a REST API&lt;/a&gt;.  Vinay has been writing a long series of articles on REST APIs, plenty of chewy links for further reading.  Main points:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;Key requirements for the API&lt;/li&gt;&lt;li&gt;Use RESTful URLs and actions&lt;/li&gt; &lt;li&gt;SSL everywhere - all the time&lt;/li&gt; &lt;li&gt;Documentation&lt;/li&gt; &lt;li&gt;Versioning&lt;/li&gt; &lt;li&gt;Result filtering, sorting &amp;amp; searching&lt;/li&gt;&lt;li&gt;Limiting which fields are returned by the API&lt;/li&gt; &lt;li&gt;Updates &amp;amp; creation should return a resource representation&lt;/li&gt;&lt;li&gt;Should you HATEOAS?&lt;/li&gt; &lt;li&gt;JSON only responses&lt;/li&gt; &lt;li&gt;snake_case vs camelCase for field names&lt;/li&gt; &lt;li&gt;Pretty print by default &amp;amp; ensure gzip is supported&lt;/li&gt; &lt;li&gt;Don't use an envelope by default, but make it possible when needed&lt;/li&gt; &lt;li&gt;JSON encoded POST, PUT &amp;amp; PATCH bodies&lt;/li&gt; &lt;li&gt;Pagination&lt;/li&gt; &lt;li&gt;Auto loading related resource representations&lt;/li&gt; &lt;li&gt;Overriding the HTTP method&lt;/li&gt; &lt;li&gt;Rate limiting&lt;/li&gt; &lt;li&gt;Authentication&lt;/li&gt; &lt;li&gt;Caching&lt;/li&gt; &lt;li&gt;Errors&lt;/li&gt; &lt;li&gt;HTTP status codes&lt;/li&gt; &lt;li&gt;In Summary&lt;/li&gt; &lt;/ul&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-7699351084333524216</guid>
         <pubDate>Sat, 27 Jun 2015 21:50:00 +0000</pubDate>
      </item>
      <item>
         <title>Pattern matching for Java</title>
         <link>http://binkley.blogspot.com/2015/06/pattern-matching-for-java.html</link>
         <description>&lt;p&gt;Java does not (yet) have &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://c2.com/cgi/wiki?PatternMatching&quot;&gt;pattern matching&lt;/a&gt; although writing a legible DSL for it is not too hard.  I'm certainly not the first &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://kerflyn.wordpress.com/2012/05/09/towards-pattern-matching-in-java/&quot; title=&quot;Towards Pattern Matching in Java&quot;&gt;to take&lt;/a&gt; a &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://eng.wealthfront.com/2015/02/pattern-matching-in-java-with-visitor.html&quot; title=&quot;Pattern matching in Java with the Visitor pattern&quot;&gt;hand at it&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;An example DSL in action.  Lambdas and method references sure help a lot:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public static void main(final String... args) {
    asList(0, 1, 2, 3, 13, 14, null, -1).stream().
            peek(n -&amp;gt; out.print(format(&quot;%d -&amp;gt; &quot;, n))).
            map(matching(Integer.class, Object.class).
                    when(Objects::isNull).then(n -&amp;gt; &quot;!&quot;).
                    when(is(0)).then(nil()).
                    when(is(1)).then(&quot;one&quot;).
                    when(is(13)).then(() -&amp;gt; &quot;unlucky&quot;).
                    when(is(14)).then(printIt()).
                    when(even()).then(scaleBy(3)).
                    when(gt(2)).then(dec()).
                    none().then(&quot;no match&quot;)).
            map(MatchingTest::toString).
            forEach(out::println);
    out.flush(); // Avoid mixing sout and serr

    matching(Integer.class, Void.class).
            none().thenThrow(RuntimeException::new).
            apply(0);
}&lt;/pre&gt; &lt;p&gt;Implementation:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;/**
 * {@code Matching} represents &amp;lt;a href=&quot;https://en.wikipedia.org/wiki/Pattern_matching&quot;&amp;gt;Pattern
 * Matching&amp;lt;/a&amp;gt; in Java as a function production an optional.  Example: &amp;lt;pre&amp;gt;
 * asList(0, 1, 2, 3, 13, 14, null, -1).stream().
 *         peek(n -&amp;gt; out.print(format(&quot;%d -&amp;gt; &quot;, n))).
 *         map(matching(Integer.class, Object.class).
 *             when(Objects::isNull).then(n -&amp;amp;gt; &quot;!&quot;).
 *             when(is(0)).then(nil()).
 *             when(is(1)).then(&quot;one&quot;).
 *             when(is(13)).then(() -&amp;amp;gt; &quot;unlucky&quot;).
 *             when(is(14)).then(printIt()).
 *             when(even()).then(scaleBy(3)).
 *             when(gt(2)).then(dec()).
 *             none().then(&quot;no match&quot;)).
 *         map(MatchingTest::toString).
 *         forEach(out::println);&amp;lt;/pre&amp;gt;
 * &amp;lt;p&amp;gt;
 * &amp;lt;i&amp;gt;NB&amp;lt;/i&amp;gt; &amp;amp;mdash; There is no way to distinguish from an empty optional if
 * there was no match, or if a match mapped the input to {@code null}, without
 * use of a {@link When#then(Object) sentinel value} or {@link
 * When#thenThrow(Supplier) thrown exception}.
 * &amp;lt;p&amp;gt;
 * &amp;lt;strong&amp;gt;NB&amp;lt;/strong&amp;gt; &amp;amp;mdash; There is no formal destructuring, but this can
 * be simulated in the {@code Predicate} to {@link #when(Predicate) when}.
 *
 * @param &amp;lt;T&amp;gt; the input type to match against
 * @param &amp;lt;U&amp;gt; the output type of a matched pattern
 *
 * @author &amp;lt;a href=&quot;mailto:binkley@alumni.rice.edu&quot;&amp;gt;B. K. Oxley (binkley)&amp;lt;/a&amp;gt;
 */
@NoArgsConstructor(access = PRIVATE)
public final class Matching&amp;lt;T, U&amp;gt;
        implements Function&amp;lt;T, Optional&amp;lt;U&amp;gt;&amp;gt; {
    private final Collection&amp;lt;Case&amp;gt; cases = new ArrayList&amp;lt;&amp;gt;();

    /**
     * Begins pattern matching with a new pattern matcher.
     *
     * @param inType the input type token, never {@code null}
     * @param outType the output type token, never {@code null}
     * @param &amp;lt;T&amp;gt; the input type to match against
     * @param &amp;lt;U&amp;gt; the output type of a matched pattern
     *
     * @return the pattern matcher, never {@code null}
     *
     * @todo Avoid the type tokens
     */
    public static &amp;lt;T, U&amp;gt; Matching&amp;lt;T, U&amp;gt; matching(final Class&amp;lt;T&amp;gt; inType,
            final Class&amp;lt;U&amp;gt; outType) {
        return new Matching&amp;lt;&amp;gt;();
    }

    /**
     * Begins a when/then pair.
     *
     * @param when the pattern matching test, never {@code null}
     *
     * @return the pattern continuance, never {@code null}
     */
    public When when(final Predicate&amp;lt;? super T&amp;gt; when) {
        return new When(when);
    }

    /**
     * Begins a default when/then pair, always placed &amp;lt;strong&amp;gt;last&amp;lt;/strong&amp;gt; in
     * the list of cases (evaluates no cases after this one).
     *
     * @return then pattern continuance, never {@code null}
     */
    public When none() {
        return when(o -&amp;gt; true);
    }

    /**
     * Evaluates the pattern matching.
     *
     * @param in the input to match against, possibly {@code null}
     *
     * @return the match result (empty if no match), never {@code null}
     */
    @Override
    public Optional&amp;lt;U&amp;gt; apply(final T in) {
        return cases.stream().
                filter(c -&amp;gt; c.p.test(in)).
                findFirst().
                map(c -&amp;gt; c.q.apply(in));
    }

    @RequiredArgsConstructor(access = PRIVATE)
    public final class When {
        /**
         * Number of frames to discard when creating an exception for a match.
         * Very sensitive to implementation.  This aids in understanding stack
         * traces from matching, discarding internal machinery and leaving the
         * actual throwing call at the top of the stack.
         */
        private static final int N = 7;
        private final Predicate&amp;lt;? super T&amp;gt; when;

        /**
         * Ends a when/then pair, evaluating &amp;lt;var&amp;gt;then&amp;lt;/var&amp;gt; against the input
         * if matched.
         *
         * @param then the pattern matching function, never {@code null}
         *
         * @return the pattern matcher, never {@code null}
         */
        public Matching&amp;lt;T, U&amp;gt; then(
                final Function&amp;lt;? super T, ? extends U&amp;gt; then) {
            cases.add(new Case(when, then));
            return Matching.this;
        }

        /**
         * Ends a when/then pair, returning &amp;lt;var&amp;gt;then&amp;lt;/var&amp;gt; if matched.
         *
         * @param then the pattern matching value, possibly {@code null}
         *
         * @return the pattern matcher, never {@code null}
         */
        public Matching&amp;lt;T, U&amp;gt; then(final U then) {
            cases.add(new Case(when, x -&amp;gt; then));
            return Matching.this;
        }

        /**
         * Ends a when/then pair, evaluating &amp;lt;var&amp;gt;then&amp;lt;/var&amp;gt; independent of
         * supplier if matched.
         *
         * @param then the pattern matching supplier, never {@code null}
         *
         * @return the pattern matcher, never {@code null}
         */
        public Matching&amp;lt;T, U&amp;gt; then(final Supplier&amp;lt;? extends U&amp;gt; then) {
            cases.add(new Case(when, x -&amp;gt; then.get()));
            return Matching.this;
        }

        /**
         * Ends a when/then pair, evaluating &amp;lt;var&amp;gt;then&amp;lt;/var&amp;gt; to {@code null}
         * if matched.
         *
         * @param then the input consumer, never {@code null}
         *
         * @return the pattern matcher, never {@code null}
         */
        public Matching&amp;lt;T, U&amp;gt; then(final Consumer&amp;lt;? super T&amp;gt; then) {
            cases.add(new Case(when, o -&amp;gt; {
                then.accept(o);
                return null;
            }));
            return Matching.this;
        }

        /**
         * Ends a when/then pair, evaluating &amp;lt;var&amp;gt;then&amp;lt;/var&amp;gt; independent of
         * supplier and throwing the new exception if matched.
         *
         * @param then the pattern matching exception supplier, never {@code
         * null}
         *
         * @return the pattern matcher, never {@code null}
         */
        public Matching&amp;lt;T, U&amp;gt; thenThrow(
                final Supplier&amp;lt;RuntimeException&amp;gt; then) {
            cases.add(new Case(when, x -&amp;gt; {
                final RuntimeException e = then.get();
                final List&amp;lt;StackTraceElement&amp;gt; stack = asList(
                        e.getStackTrace());
                e.setStackTrace(stack.subList(N, stack.size()).
                        toArray(new StackTraceElement[stack.size() - N]));
                throw e;
            }));
            return Matching.this;
        }
    }

    @RequiredArgsConstructor(access = PRIVATE)
    private final class Case {
        private final Predicate&amp;lt;? super T&amp;gt; p;
        private final Function&amp;lt;? super T, ? extends U&amp;gt; q;
    }
}&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-6540179687443427434</guid>
         <pubDate>Sat, 27 Jun 2015 04:42:00 +0000</pubDate>
      </item>
      <item>
         <title>RESTful errors, Simple Boot</title>
         <link>http://binkley.blogspot.com/2015/05/restful-errors-simple-boot.html</link>
         <description>&lt;h3&gt;Handling Errors&lt;/h3&gt; &lt;p&gt;Reading Travis McChesney's &lt;cite&gt;&lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://cloud-elements.com/restful-api-design-part-iii-error-handling/&quot;&gt;RESTful API Design Part III: Error Handling&lt;/a&gt;&lt;/cite&gt;, there are more ways to represent errors in REST APIs than the returned body.  &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/simple-boot&quot;&gt;A toy API I am writing as a playground&lt;/a&gt; for these idea is named &lt;cite&gt;Simple Boot&lt;/cite&gt;, a jest on &quot;Spring Boot&quot;.  There I have an &quot;X-Correlation-ID&quot; header for tracking calls through services.&lt;/p&gt; &lt;ul&gt;&lt;li&gt;Should &quot;X-Correlation-ID&quot; be required?&lt;/li&gt;  &lt;li&gt;Should it be supplied automatically?&lt;/li&gt; &lt;li&gt;When required and missing, what should the caller receive?&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Answering the third the caller sees:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Warning: 250 localhost:8080 &quot;Missing X-Correlation-ID header&quot;
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 28 May 2015 12:46:40 GMT
Connection: close

{
  &quot;timestamp&quot;: 1432817125588,
  &quot;status&quot;: 400,
  &quot;error&quot;: &quot;Bad Request&quot;,
  &quot;message&quot;: &quot;Missing X-Correlation-ID header&quot;,
  &quot;path&quot;: &quot;/hello/Bob&quot;
}&lt;/pre&gt; &lt;p&gt;Here rather than choosing among options, I take them all:&lt;/p&gt; &lt;ol&gt;&lt;li&gt;Return a 400 for a bad request&lt;/li&gt; &lt;li&gt;Describe the error in the response body&lt;/li&gt; &lt;li&gt;Add a header describing the error&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;As McChesney points out, there is not general agreement on reporting errors.  For example, Facebook returns 200 for errors, requiring parsing of the response body.&lt;/p&gt; &lt;p&gt;Using the &quot;Warning&quot; header for this purpose is uncommon but &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46&quot;&gt;supported in the specification&lt;/a&gt; albeit obliquely.  However &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://stackoverflow.com/questions/6676976/putting-detailed-rest-error-message-in-http-warning-header-good-bad-idea&quot;&gt;not everyone agrees&lt;/a&gt;.  I use warning code 250, one I made up.  The 1xx codes are transient errors; the 2xx codes permanent.  In another example I use a 1xx code for an upstream service currently unavailable, and return cached data, which is closer to the described uses of &quot;Warning&quot;.&lt;/p&gt; &lt;p&gt;Other header options:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;Using a custom code outside 1xx or 2xx with &quot;Warning&quot;.  This makes sense for in-house services, may cause issues with caching devices but unclear&lt;/li&gt; &lt;li&gt;Use a custom HTTP header, &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://www.safaribooksonline.com/library/view/restful-web-services/9780596809140/ch01s13.html&quot;&gt;a common solution&lt;/a&gt;, again may have issues with intermediate devices&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;Some Spring Bonus&lt;/h3&gt; &lt;p&gt;Simple Boot has been fun and instructive.  One Spring Boot feature I stumbled on is automated binding of configuration properties.  For services requiring &quot;X-Correlation-ID&quot; I configure with &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/simple-boot/blob/13/common/src/main/java/hello/CorrelationIdFilter.java#L34&quot;&gt;&lt;code&gt;@ConfigurationProperties(prefix = &quot;headers.correlation-id.server&quot;)&lt;/code&gt;&lt;/a&gt;.  To automate clients I use &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/simple-boot/blob/13/common/src/main/java/hello/CorrelationIdInterceptor.java#L28&quot;&gt;&lt;code&gt;@ConfigurationProperties(prefix = &quot;headers.correlation-id.client&quot;)&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;As an example of solving one issue with headers, I write &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/simple-boot/blob/13/common/src/main/java/hello/FeignHeadersInterceptor.java&quot;&gt;Feign pass-through&lt;/a&gt; support.&lt;/p&gt; &lt;p&gt;Of course &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/simple-boot/tree/13/common/src/test/java/hello&quot;&gt;there are tests&lt;/a&gt;.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-4481403881470913556</guid>
         <pubDate>Thu, 28 May 2015 21:32:00 +0000</pubDate>
      </item>
      <item>
         <title>Dynamic properties in Java</title>
         <link>http://binkley.blogspot.com/2015/03/dynamic-properties-in-java.html</link>
         <description>&lt;h3&gt;Motivation&lt;/h3&gt; &lt;p&gt;I've been looking at the problem of dynamic properties in Java.  Typically properties are injected into a program at start and never change.  Common examples include timeouts, host names, etc.  Changing these requires and edit and restart (edit can also mean an update to a remote data source).&lt;/p&gt; &lt;p&gt;What I want is runtime updates to properties, and the program uses the new values.  Hence &quot;dynamic properties&quot;.&lt;/p&gt; &lt;p&gt;There are several schemes for this built around frameworks or external data sources.  I want something using only the JDK.&lt;/p&gt; &lt;h3&gt;Interfaces&lt;/h3&gt; &lt;p&gt;My interfaces became one for tracking key-value pairs, one for updating them (javadoc munged to display in post):&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;/**
 * &lt;code&gt;Tracking&lt;/code&gt; tracks string key-value pairs, tracking external updates
 * to the boxed values.  Optionally tracks them as a type converted from
 * string.  Example use: &lt;pre&gt;
 * Tracking dynafig = ...;
 * Optional&amp;lt;AtomicReference&amp;lt;String&amp;gt;&amp;gt; prop = dynafig.track(&quot;prop&quot;);
 * boolean propDefined = prop.isPresent();
 * AtomicReference&amp;lt;String&amp;gt; propRef = prop.get();
 * String propValue = propRef.get();
 * // External source updates key-value pair for &quot;prop&quot;
 * String newPropValue = propRef.get();&lt;/pre&gt;
 *
 * In an injection context: &lt;pre&gt;
 * class Wheel {
 *     private final AtomicInteger rapidity;
 *
 *     &amp;#64;Inject
 *     public Wheel(final Tracking dynafig) {
 *         rapidity = dynafig.track(&quot;rapidity&quot;).
 *                 orElseThrow(() -&amp;gt; new IllegalStateException(
 *                         &quot;Missing 'rapidity' property));
 *     }
 *
 *     public void spin() {
 *         spinAtRate(rapidity.get());
 *     }
 * }&lt;/pre&gt;
 *
 * @author &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;mailto:boxley@thoughtworks.com&quot;&gt;Brian Oxley&lt;/a&gt;
 * @see Updating Updating key-value pairs
 * @see Default Reference implementation
 */
public interface Tracking {
    /**
     * Tracks the given &lt;var&gt;key&lt;/var&gt; value as a string.  Returns empty if
     * &lt;var&gt;key&lt;/var&gt; is undefined.  If &lt;var&gt;key&lt;/var&gt; is defined, may stil
     * return a &lt;code&gt;null&lt;/code&gt; boxed value.
     *
     * @param key the key, never missing
     *
     * @return the optional atomic value string, never missing
     *
     * @todo Some way to work out &lt;var&gt;type&lt;/var&gt; from &lt;var&gt;convert&lt;/var&gt;
     */
    @Nonnull
    Optional&amp;lt;AtomicReference&amp;lt;String&amp;gt;&amp;gt; track(@Nonnull final String key);

    /**
     * Tracks the given &lt;var&gt;key&lt;/var&gt; value as a boolean.  Returns empty if
     * &lt;var&gt;key&lt;/var&gt; is undefined.
     *
     * @param key the key, never missing
     *
     * @return the optional atomic value boolean, never missing
     */
    @Nonnull
    Optional&amp;lt;AtomicBoolean&amp;gt; trackBool(@Nonnull final String key);

    /**
     * Tracks the given &lt;var&gt;key&lt;/var&gt; value as an integer.  Returns empty if
     * &lt;var&gt;key&lt;/var&gt; is undefined.
     *
     * @param key the key, never missing
     *
     * @return the optional atomic value integer, never missing
     */
    @Nonnull
    Optional&amp;lt;AtomicInteger&amp;gt; trackInt(@Nonnull final String key);

    /**
     * Tracks the given &lt;var&gt;key&lt;/var&gt; value as &lt;var&gt;type&lt;/var&gt;.  Returns
     * empty if &lt;var&gt;key&lt;/var&gt; is undefined.  If &lt;var&gt;key&lt;/var&gt; is defined,
     * may stil return a &lt;code&gt;null&lt;/code&gt; boxed value.
     *
     * @param key the key, never missing
     * @param type the value type token, never missing
     * @param convert the value converter, never missing
     * @param &amp;lt;T&amp;gt; the value type
     *
     * @return the optional atomic value reference, never missing
     *
     * @todo Some way to work out &lt;var&gt;type&lt;/var&gt; from &lt;var&gt;convert&lt;/var&gt;
     */
    @Nonnull
    &amp;lt;T&amp;gt; Optional&amp;lt;AtomicReference&amp;lt;T&amp;gt;&amp;gt; trackAs(@Nonnull final String key,
            @Nonnull final Class&amp;lt;T&amp;gt; type, // TODO: Can this be worked out?
            @Nonnull final Function&amp;lt;String, T&amp;gt; convert);
}&lt;/pre&gt; &lt;pre class=&quot;code&quot;&gt;/**
 * {@code Updating} updates key-value pairs.
 *
 * @author &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;mailto:boxley@thoughtworks.com&quot;&gt;Brian Oxley&lt;/a&gt;
 * @see Tracking Tracking key-value pairs
 * @see Default Reference implementation
 */
public interface Updating {
    /**
     * Updates a key-value pair with a new value.
     *
     * @param key the key, never missing
     * @param value the value, possibly &lt;code&gt;null&lt;/code&gt;
     *
     * @return &lt;code&gt;true&lt;/code&gt; if updated else &lt;code&gt;false&lt;/code&gt; if created
     */
    boolean update(@Nonnull final String key, @Nullable final String value);

    /**
     * Updates a key-value pair as a map entry for convenience.
     *
     * @param entry the entry, never missing
     *
     * @return &lt;code&gt;true&lt;/code&gt; if updated else &lt;code&gt;false&lt;/code&gt; if created
     * @see #update(String, String)
     */
    default boolean update(@Nonnull final Map.Entry&amp;lt;String, String&amp;gt; entry) {
        return update(entry.getKey(), entry.getValue());
    }

    /**
     * Updates a set of key-value pairs for convenience.  Each key is
     * invidually updated in entry-set order.
     *
     * @param values the key-value set, never missing
     *
     * @see #update(String, String)
     */
    default void updateAll(@Nonnull final Map&amp;lt;String, String&amp;gt; values) {
        values.entrySet().stream().
                forEach(this::update);
    }
}&lt;/pre&gt; &lt;h3&gt;Team lead&lt;/h3&gt; &lt;p&gt;I built a reference implementation to demonstrate these were plausible.  To my team I explained like this: &lt;ul&gt;&lt;li&gt;Coded very much in Java 8 functional style&lt;/li&gt; &lt;li&gt;Trivial API - 4 tracking calls (variants on return type), 1 updating call (plus 2 convenience)&lt;/li&gt;
&lt;li&gt;Minimal dependencies - JDK + javax.annotations (@Nonnull)&lt;/li&gt; &lt;li&gt;Thread-safe, not concurrency-safe (lost updates, etc).  Fine if properties are not updated on top of each other (i.e., several in the same microsecond)&lt;/li&gt; &lt;li&gt;I expect it to be straight-forward to integrate into JSR107, Cassandra, etc, but I've not tried this from home&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;And offered some advice to my juniors:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;Be functional where sensible, the benefits are almost beyond enumeration&lt;/li&gt;
&lt;li&gt;Corollary: Avoid state - in Java that means fields.  Temp variables (locals) are debatable and come down to individual taste.  I lean to avoiding them, but there's nothing wrong with creating locals that clarify the code for others (including yourself 6 mos. later)&lt;/li&gt;
&lt;li&gt;Corollary: Push fields down as low as possible, avoid globals and &quot;local globals&quot; (static fields)&lt;/li&gt;
&lt;li&gt;Complicate your data structure, not your calls.  People reason about complex data structures much better than they do about complex logic&lt;/li&gt;
&lt;li&gt;Avoid null.  Really.  Treat all uses of null as code smell - think of it as &quot;machine level&quot; programming.  You should do high-level programming&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;Implementation&lt;/h3&gt; &lt;p&gt;All tests pass.  The reference implementation:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public final class Default
        implements Tracking, Updating {
    private final Map&amp;lt;String, Value&amp;gt; keys = new ConcurrentHashMap&amp;lt;&amp;gt;();
    private final Map&amp;lt;String, Value&amp;gt; values = new ConcurrentHashMap&amp;lt;&amp;gt;();

    public Default() {
    }

    public Default(@Nonnull final Map&amp;lt;String, String&amp;gt; keys) {
        updateAll(keys);
    }

    @Nonnull
    @Override
    public Optional&amp;lt;AtomicReference&amp;lt;String&amp;gt;&amp;gt; track(
            @Nonnull final String key) {
        return Optional.ofNullable(keys.get(key)).
                map(Value::get);
    }

    @Nonnull
    @Override
    public Optional&amp;lt;AtomicBoolean&amp;gt; trackBool(@Nonnull final String key) {
        return Optional.ofNullable(keys.get(key)).
                map(Value::getBool);
    }

    @Nonnull
    @Override
    public Optional&amp;lt;AtomicInteger&amp;gt; trackInt(@Nonnull final String key) {
        return Optional.ofNullable(keys.get(key)).
                map(Value::getInt);
    }

    @Nonnull
    @Override
    public &amp;lt;T&amp;gt; Optional&amp;lt;AtomicReference&amp;lt;T&amp;gt;&amp;gt; trackAs(@Nonnull final String key,
            @Nonnull final Class&amp;lt;T&amp;gt; type,
            @Nonnull final Function&amp;lt;String, T&amp;gt; convert) {
        return Optional.ofNullable(keys.get(key)).
                map(v -&amp;gt; v.getAs(type, convert));
    }

    @Override
    public boolean update(@Nonnull final String key,
            @Nullable final String value) {
        return null != keys.put(key, values.compute(key,
                (k, v) -&amp;gt; null == v ? new Value(value) : v.update(value)));
    }

    private static final class Atomic&amp;lt;T&amp;gt; {
        private final T atomic;
        private final Consumer&amp;lt;String&amp;gt; update;

        private static Atomic&amp;lt;AtomicReference&amp;lt;String&amp;gt;&amp;gt; of(
                final String value) {
            final AtomicReference&amp;lt;String&amp;gt; atomic = new AtomicReference&amp;lt;&amp;gt;(
                    value);
            return new Atomic&amp;lt;&amp;gt;(atomic, atomic::set);
        }

        private static Atomic&amp;lt;AtomicBoolean&amp;gt; boolOf(final String value) {
            final AtomicBoolean atomic = new AtomicBoolean(
                    null == value ? false : Boolean.valueOf(value));
            return new Atomic&amp;lt;&amp;gt;(atomic,
                    v -&amp;gt; atomic.set(null == v ? false : Boolean.valueOf(v)));
        }

        private static Atomic&amp;lt;AtomicInteger&amp;gt; intOf(final String value) {
            final AtomicInteger atomic = new AtomicInteger(
                    null == value ? 0 : Integer.valueOf(value));
            return new Atomic&amp;lt;&amp;gt;(atomic,
                    v -&amp;gt; atomic.set(null == v ? 0 : Integer.valueOf(v)));
        }

        private static &amp;lt;T&amp;gt; Atomic&amp;lt;AtomicReference&amp;lt;T&amp;gt;&amp;gt; asOf(final String value,
                final Function&amp;lt;String, T&amp;gt; convert) {
            final AtomicReference&amp;lt;T&amp;gt; atomic = new AtomicReference&amp;lt;&amp;gt;(
                    convert.apply(value));
            return new Atomic&amp;lt;&amp;gt;(atomic, v -&amp;gt; atomic.set(convert.apply(v)));
        }

        private Atomic(final T atomic, final Consumer&amp;lt;String&amp;gt; update) {
            this.atomic = atomic;
            this.update = update;
        }

        private void update(final String value) {
            update.accept(value);
        }
    }

    private final class Value {
        @Nullable
        private final String value;
        private final Map&amp;lt;Class&amp;lt;?&amp;gt;, Atomic&amp;lt;?&amp;gt;&amp;gt; values;

        private Value(final String value) {
            this(value, new ConcurrentHashMap&amp;lt;&amp;gt;(3));
        }

        private Value(@Nullable final String value,
                final Map&amp;lt;Class&amp;lt;?&amp;gt;, Atomic&amp;lt;?&amp;gt;&amp;gt; values) {
            this.value = value;
            this.values = values;
        }

        private Value update(final String value) {
            final Value newValue = new Value(value, values);
            newValue.values.values().stream().
                    forEach(a -&amp;gt; a.update(value));
            return newValue;
        }

        @SuppressWarnings(&quot;unchecked&quot;)
        private AtomicReference&amp;lt;String&amp;gt; get() {
            return (AtomicReference&amp;lt;String&amp;gt;) values.
                    computeIfAbsent(String.class,
                            k -&amp;gt; Atomic.of(value)).atomic;
        }

        private AtomicBoolean getBool() {
            return (AtomicBoolean) values.
                    computeIfAbsent(Boolean.class,
                            k -&amp;gt; Atomic.boolOf(value)).atomic;
        }

        private AtomicInteger getInt() {
            return (AtomicInteger) values.
                    computeIfAbsent(Integer.class,
                            k -&amp;gt; Atomic.intOf(value)).atomic;
        }

        @SuppressWarnings(&quot;unchecked&quot;)
        private &amp;lt;T&amp;gt; AtomicReference&amp;lt;T&amp;gt; getAs(final Class&amp;lt;T&amp;gt; type,
                final Function&amp;lt;String, T&amp;gt; convert) {
            return (AtomicReference&amp;lt;T&amp;gt;) values.
                    computeIfAbsent(type,
                            k -&amp;gt; Atomic.asOf(value, convert)).atomic;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;
            final Value that = (Value) o;
            return Objects.equals(value, that.value);
        }

        @Override
        public int hashCode() {
            return Objects.hash(value);
        }
    }
}&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-7759304460688235020</guid>
         <pubDate>Sun, 15 Mar 2015 20:40:00 +0000</pubDate>
      </item>
      <item>
         <title>Does refactoring worsen code?</title>
         <link>http://binkley.blogspot.com/2015/03/does-refactoring-worsen-code.html</link>
         <description>&lt;p&gt;Thought provoking: &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.itworld.com/article/2891140/study-finds-that-refactoring-doesn-t-improve-code-quality.html&quot;&gt;&lt;cite&gt;Study finds that refactoring doesn’t improve code quality&lt;/cite&gt;&lt;/a&gt;. The opening:&lt;/p&gt; &lt;blockquote&gt;&lt;p&gt;Refactoring software, that is, restructuring existing source code to make it more readable, efficient, and maintainable, is something all developers do every now and again. Of course, the implicit assumption behind refactoring is that the benefits (time and headaches saved in the future) outweigh the costs (time and effort spent now). However, new experimental research suggests that this may not be the case and that software code quality may not be improved much, if at all, by refactoring.&lt;/p&gt; &lt;p&gt;The study was done by researchers in Sri Lanka and recently published in the &lt;cite&gt;International Journal of Software Engineering &amp;amp; Applications&lt;/cite&gt; titled &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://arxiv.org/pdf/1502.03526v1.pdf&quot;&gt;&lt;cite&gt;An Empirical Evaluation of Impact of Refactoring On Internal and External Measures of Code Quality&lt;/cite&gt;&lt;/a&gt;. The goal was to test whether  common refactoring techniques resulted in measurable improvements in software quality, both externally (e.g., Is the code more maintainable?) and internally (e.g., Number of lines of code).&lt;/p&gt; &lt;p&gt;The researchers selected a small-scale application (about 4,500 lines of C# code) used by the academic staff at the University of Kelaniya for scheduling events and managing online documents for evaluation. 10 common refactoring techniques were applied to the code (e.g., Replace Type Code with Subclasses, Replace Conditional with Polymorphism).&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Reading the press account I expect objections such as:&lt;/p&gt; &lt;dl&gt;&lt;dt&gt;C#?&lt;/dt&gt; &lt;dd&gt;Well, language should not matter here&lt;/dd&gt; &lt;dt&gt;Too small an example!&lt;/dt&gt; &lt;dd&gt;This is a fair complaint, the impact of refactoring scales with code base size&lt;/dd&gt; &lt;dt&gt;Those weren't professionals&lt;/dt&gt; &lt;dd&gt;The reviewers were a mix, but this complaint overlooks how much code is written and maintained by &quot;non-programmers&quot;, an oxymoron as programming is an activity, not a type of person&lt;/dd&gt;&lt;/dl&gt; &lt;p&gt;My own objection is that the refactoring did not go far enough.  Deepening a type hierarchy does often make code &quot;worse&quot;, delegation is often a better choice than inheritance.  In a larger code base than the sample used, this become more obvious.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-2742891868927795375</guid>
         <pubDate>Wed, 04 Mar 2015 20:51:00 +0000</pubDate>
      </item>
      <item>
         <title>Architects, engineers?</title>
         <link>http://binkley.blogspot.com/2015/02/architects-engineers.html</link>
         <description>&lt;p&gt;Delightful passage from Sam Newman's new book, &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.amazon.com/Building-Microservices-Sam-Newman/dp/1491950358&quot;&gt;&lt;cite&gt;Building Microservices&lt;/cite&gt;&lt;/a&gt;:&lt;/p&gt; &lt;blockquote&gt;Part of us wants recognition, so we borrow names from other professions that already have the recognition we as an industry crave. But this can be doubly harmful. First, it implies we know what we are doing, when we plainly don’t. I wouldn’t say that buildings and bridges never fall down, but they fall down much less than the number of times our programs will crash, making comparisons with engineers quite unfair. Second, the analogies break down very quickly when given even a cursory glance. To turn things around, if bridge building were like programming, halfway through we’d find out that the far bank was now 50 meters farther out, that it was actually mud rather than granite, and that rather than building a footbridge we were instead building a road bridge. Our software isn’t constrained by the same physical rules that real architects or engineers have to deal with, and what we create is designed to flex and adapt and evolve with user requirements.&lt;/blockquote&gt; &lt;p&gt;A lot of times I really don't understand my own job.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-5349223335426619359</guid>
         <pubDate>Sat, 28 Feb 2015 03:07:00 +0000</pubDate>
      </item>
      <item>
         <title>Dice, Test First and saving time</title>
         <link>http://binkley.blogspot.com/2015/02/dice-test-first-and-saving-time.html</link>
         <description>&lt;p&gt;&lt;strong&gt;tl;dr&lt;/strong&gt; &amp;mdash; Test first saves time. Also a dice
    expression calculator.&lt;/p&gt;

&lt;h3&gt;The setup&lt;/h3&gt;

&lt;p&gt;Larry Wall &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://c2.com/cgi/wiki?LazinessImpatienceHubris&quot;&gt;famously
    remarked&lt;/a&gt;, &quot;the three great virtues of a programmer: laziness,
    impatience, and hubris.&quot; A skill earned by good programmers is knowing
    when to favor which virtue. I failed while writing a parser for &quot;dice
    expressions&quot; ala &lt;a rel=&quot;nofollow&quot;
 target=&quot;_blank&quot; href=&quot;http://dnd.wizards.com/articles/features/basicrules&quot;
 title=&quot;BASIC RULES FOR DUNGEONS &amp;amp; DRAGONS&quot;&gt;Dungeons &amp;amp;
        Dragons&lt;/a&gt;. (Example: &quot;3d6 + 1&quot; means &lt;dfn&gt;roll 3 6-sided dice, sum
        the results and add 1&lt;/dfn&gt;.)&lt;/p&gt;

&lt;p&gt;The parser is straight-forward using &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.antlr.org/&quot;&gt;the
    popular ANTLR4 tools&lt;/a&gt;:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;grammar DiceExpression;

expr: left=expr op=('*' | '/') right=expr #opExpr
    | left=expr op=('+' | '-') right=expr #opExpr
    | '(' group=expr ')' #groupExpr
    | van=('adv' | 'dis')? number=NUMBER? sides=SIDES #diceExpr
    | number=NUMBER #numberExpr
    ;

dice: number=NUMBER? sides=SIDES;

NUMBER: '1'..'9' '0'..'9'*;
SIDES: 'd' ('4' | '6' | '8' | '10' | '12' | '20' | '100')
    { setText(getText().substring(1)); };

WS: [ &amp;#92;t]+ -&amp;gt; skip;
&lt;/pre&gt;
&lt;p&gt;The grammar supports a 5&lt;sup&gt;th&lt;/sup&gt; Edition feature, &lt;a rel=&quot;nofollow&quot;
 target=&quot;_blank&quot; href=&quot;http://dnd.wizards.com/products/tabletop/players-basic-rules#howtoplay_1101&quot;&gt;Advantage/Disadvantage&lt;/a&gt;&amp;mdash;where
    you get to roll twice and pick the better/worse result&amp;mdash;, with the
    keywords &lt;code&gt;adv&lt;/code&gt;/&lt;code&gt;dis&lt;/code&gt;. A less-5&lt;sup&gt;th&lt;/sup&gt;
    Edition-specific grammar would leave out that term from &quot;#diceExpr&quot;.&lt;/p&gt;

&lt;h3&gt;Enter the rube&lt;/h3&gt;

&lt;p&gt;All tests pass: good! Then I thought, &quot;What about whitespace in dice rolls
    or with adv/dis?&quot; I was concerned with expressions such as &quot;1 +disd6&quot; or
    &quot;3 d4&quot;. Surely those are invalid, but I don't check for them. So I began
    adding explicit whitespace parsing in the &lt;code&gt;#diceExpr&lt;/code&gt; rule.
    Mistake!&lt;/p&gt;

&lt;p&gt;Several of my tests failed for perfectly good dice expressions.&lt;/p&gt;

&lt;p&gt;Okay, so I reverted my grammar changes. To understand what was going on, I
    added tests I should have started with before editing (lines marked
    &quot;FAIL&quot;):&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@RunWith(Parameterized.class)
public final class DiceExpressionTest {
    @Parameters(name = &quot;{index}: '{0}'&quot;)
    public static Collection&amp;lt;Object&amp;gt; parameters() {
        return asList(args(&quot;1&quot;, true),
                args(&quot;d6&quot;, true),
                args(&quot;3d6&quot;, true),
                args(&quot;1+3d6&quot;, true),
                args(&quot;adv d6&quot;, true),
                args(&quot;dis 3d6&quot;, true),
                &lt;strong&gt;args(&quot;disd6&quot;, false), // FAIL&lt;/strong&gt;
                &lt;strong&gt;args(&quot;1 + 3 d6&quot;, false)); // FAIL&lt;/strong&gt;
    }

    private final ExpectedException thrown = ExpectedException.none();

    @Parameter(0)
    public String in;
    @Parameter(1)
    public boolean ok;

    @Test
    public void shouldParse() {
        if (!ok)
            thrown.expect(ParseCancellationException.class);

        // Just check parsing works, ignore results
        DiceExpression.valueOf(in).evalWith(Roll.die());
    }

    private static Object[] args(final Object... args) {
        return args;
    }
}&lt;/pre&gt;
&lt;p&gt;And ... the &quot;FAIL&quot; tests pass with the original grammar. This got me to
    thinking more about how ANTLR works. It is a lexer/parser. The lexer grabs
    strings from the input and hands them to the parser to figure out. The
    lexer has no brains, it's an expert at chopping up input. (&lt;a rel=&quot;nofollow&quot;
 target=&quot;_blank&quot; href=&quot;http://meri-stuff.blogspot.com/2011/09/antlr-tutorial-expression-language.html&quot;
 title=&quot;ANTLR Tutorial - Expression Language&quot;&gt;Great post&lt;/a&gt; on
    this.)&lt;/p&gt;

&lt;p&gt;The cases I worried about? The lexer does not know how to chop up the first
    one (&quot;disd6&quot;): it matches no token pattern. The parser does not understand
    the tokens in the second one (&quot;1 + 3 d6&quot;): it expects an arithmetic
    operator between &quot;3&quot; and &quot;d6&quot;. My grammar already did the right thing.&lt;/p&gt;

&lt;p&gt;Had I started with tests for these cases, instead of jumping right to
    coding, I would have not spent time messing with whitespace in the
    grammar. Coding first &lt;em&gt;cost&lt;/em&gt; time rather than saved it.&lt;/p&gt;

&lt;h3&gt;Enlightenment by coding Kōan&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Write tests first!&lt;/strong&gt; No, really. Even when you &quot;know&quot; the
    solution, write tests first. There are many ways it saves time in the long
    run, it helps you think about your API, and it can save time in the short
    run. My dice expression example is not unique: test-first avoids unneeded
    work.&lt;/p&gt;

&lt;h3&gt;Epilogue&lt;/h3&gt;

&lt;p&gt;What does the dice expression implementation look like?&lt;/p&gt; &lt;pre
 class=&quot;code&quot;&gt;public final class DiceExpression {
    private final ExprContext expression;

    @Nonnull
    public static DiceExpression valueOf(@Nonnull final String expression) {
        final DiceExpressionLexer lexer = new DiceExpressionLexer(
                new ANTLRInputStream(expression));
        final DiceExpressionParser parser = new DiceExpressionParser(
                new CommonTokenStream(lexer));
        parser.setErrorHandler(new BailErrorStrategy());

        return new DiceExpression(parser.expr());
    }

    private DiceExpression(final ExprContext expression) {
        this.expression = expression;
    }

    public int evalWith(final Roll roll) {
        return expression.accept(new EvalWithVisitor(roll));
    }

    private static final class EvalWithVisitor
            extends DiceExpressionBaseVisitor&amp;lt;Integer&amp;gt; {
        private final Roll roll;

        public EvalWithVisitor(final Roll roll) {
            this.roll = roll;
        }

        @Override
        public Integer visitOpExpr(final OpExprContext ctx) {
            final int left = visit(ctx.left);
            final int right = visit(ctx.right);
            switch (ctx.op.getText().charAt(0)) {
            case '+': return left + right;
            case '-': return left - right;
            case '*': return left * right;
            case '/': return left / right;
            }
            throw new ArithmeticException(
                    &quot;Unknown operator: &quot; + ctx.getText());
        }

        @Override
        public Integer visitGroupExpr(final GroupExprContext ctx) {
            return visit(ctx.group);
        }

        @Override
        public Integer visitDiceExpr(final DiceExprContext ctx) {
            return Dice.valueOf(ctx).evalWith(roll);
        }

        @Override
        public Integer visitNumberExpr(final NumberExprContext ctx) {
            return Integer.valueOf(ctx.number.getText());
        }
    }
}&lt;/pre&gt;
&lt;p&gt;And &lt;code&gt;Dice&lt;/code&gt;, overly complicated until I can think through
    Advantage/Disadvantage further:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public class Dice
        implements Comparable&amp;lt;Dice&amp;gt; {
    @FunctionalInterface
    public interface Roll {
        int roll(final int sides);

        static Roll die() {
            final Random random = new Random();
            return sides -&amp;gt; random.nextInt(sides) + 1;
        }
    }

    public enum Advantage {
        DIS(2, Math::min),
        NONE(1, (a, b) -&amp;gt; a),
        ADV(2, Math::max);

        private final int rolls;
        private final IntBinaryOperator op;

        Advantage(final int rolls, final IntBinaryOperator op) {
            this.rolls = rolls;
            this.op = op;
        }

        public final int evalWith(final Roll roll, final Dice dice) {
            return range(0, rolls).
                    map(n -&amp;gt; dice.rollWith(roll)).
                    reduce(op).
                    getAsInt();
        }

        public final String toString(final Dice dice) {
            switch (this) {
            case NONE:
                return dice.stringOf();
            default:
                return name().toLowerCase() + ' ' + dice.stringOf();
            }
        }
    }

    private final Optional&amp;lt;Integer&amp;gt; number;
    private final int sides;
    private final Advantage advantage;

    @Nonnull
    public static Dice valueOf(@Nonnull final String expression) {
        final DiceExpressionLexer lexer = new DiceExpressionLexer(
                new ANTLRInputStream(expression));
        final DiceExpressionParser parser = new DiceExpressionParser(
                new CommonTokenStream(lexer));
        parser.setErrorHandler(new BailErrorStrategy());

        return valueOf((DiceExprContext) parser.expr());
    }

    @Nonnull
    static Dice valueOf(@Nonnull final DiceExprContext ctx) {
        final Optional&amp;lt;Integer&amp;gt; number = Optional.ofNullable(ctx.number).
                map(Token::getText).
                map(Integer::valueOf);
        final Integer sides = Integer.valueOf(ctx.sides.getText());
        final Advantage advantage = Optional.ofNullable(ctx.van).
                map(Token::getText).
                map(String::toUpperCase).
                map(Advantage::valueOf).
                orElse(NONE);
        return new Dice(number, sides, advantage);
    }

    public Dice(@Nonnull final Optional&amp;lt;Integer&amp;gt; number, final int sides,
            final Advantage advantage) {
        this.number = number;
        this.sides = sides;
        this.advantage = advantage;
    }

    public Dice(@Nullable final Integer number, final int sides,
            final Advantage advantage) {
        this(Optional.ofNullable(number), sides, advantage);
    }

    public Dice(@Nullable final Integer number, final int sides) {
        this(Optional.ofNullable(number), sides, NONE);
    }

    public int number() {
        return number.orElse(1);
    }

    public int sides() {
        return sides;
    }

    public Advantage advantage() {
        return advantage;
    }

    public int evalWith(final Roll roll) {
        return advantage.evalWith(roll, this);
    }

    protected int rollWith(final Roll roll) {
        return rangeClosed(1, number()).
                map(ignored -&amp;gt; roll.roll(sides())).
                sum();
    }

    @Override
    public int compareTo(@Nonnull final Dice that) {
        // Sort by roll average - adv/dis messes this up though
        final int compare = Integer.compare(number() + (sides() + 1),
                that.number() * (that.sides() + 1));
        return 0 == compare ? advantage().compareTo(that.advantage())
                : compare;
    }

    @Override
    public String toString() {
        return advantage.toString(this);
    }

    protected String stringOf() {
        return number.
                map(number -&amp;gt; number + &quot;d&quot; + sides()).
                orElse(&quot;d&quot; + sides());
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        final Dice that = (Dice) o;

        return sides() == that.sides() &amp;amp;&amp;amp; number() == that.number()
                &amp;amp;&amp;amp; advantage() == that.advantage();
    }

    @Override
    public int hashCode() {
        return 31 * (31 * sides() + number()) * advantage().hashCode();
    }
}&lt;/pre&gt;

&lt;strong&gt;UPDATE:&lt;/strong&gt; If you wonder about the parser visitor, you have to
explicitly enable it in ANTLR4 (even though it is recommended over tree
rewriting).  Use the command line flag, or in Maven &lt;pre class=&quot;code&quot;&gt;&amp;lt;plugin&amp;gt;
    &amp;lt;groupId&amp;gt;org.antlr&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;antlr4-maven-plugin&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;${antlr4.version}&amp;lt;/version&amp;gt;
    &amp;lt;configuration&amp;gt;
        &amp;lt;visitor&amp;gt;true&amp;lt;/visitor&amp;gt;
    &amp;lt;/configuration&amp;gt;
    &amp;lt;executions&amp;gt;
        &amp;lt;execution&amp;gt;
            &amp;lt;id&amp;gt;antlr4&amp;lt;/id&amp;gt;
            &amp;lt;goals&amp;gt;
                &amp;lt;goal&amp;gt;antlr4&amp;lt;/goal&amp;gt;
            &amp;lt;/goals&amp;gt;
        &amp;lt;/execution&amp;gt;
    &amp;lt;/executions&amp;gt;
&amp;lt;/plugin&amp;gt;&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-23748391246735352</guid>
         <pubDate>Mon, 02 Feb 2015 07:49:00 +0000</pubDate>
      </item>
      <item>
         <title>CompletableFuture and ExecutorService</title>
         <link>http://binkley.blogspot.com/2014/12/completablefuture-and-executorservice.html</link>
         <description>&lt;h3&gt;Introduction&lt;/h3&gt; &lt;p&gt;&lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html&quot;&gt;&lt;code&gt;CompletableFuture&lt;/code&gt;&lt;/a&gt; was one of the &quot;small gifts&quot; in Java 8.  It is a clever class but not well-integrated into the rest of the JDK.  Particularly, &lt;code&gt;ExecutorService&lt;/code&gt; still returns &lt;code&gt;Future&lt;/code&gt;s rather than &lt;code&gt;CompletableFuture&lt;/code&gt;s.  No class in the JDK references completable futures.&lt;/p&gt; &lt;p&gt;The other odd thing about &lt;code&gt;CompletableFuture&lt;/code&gt; is that methods such as &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#get--&quot;&gt;&lt;code&gt;get()&lt;/code&gt;&lt;/a&gt; declare throwing &lt;code&gt;InterruptedException&lt;/code&gt; but do not do so except under narrow circumstances: tasks which are interrupted and themselves throw &lt;code&gt;InterruptedException&lt;/code&gt; have those exceptions wrapped by &lt;code&gt;ExecutionException&lt;/code&gt;, making is difficult to handle interrupts in a general way.  This is &quot;baked into&quot; the API, which provides only static factory methods accepting &lt;code&gt;Runnable&lt;/code&gt; or &lt;code&gt;Supplier&lt;/code&gt; (&lt;i&gt;e.g.&lt;/i&gt;, &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#supplyAsync-java.util.function.Supplier-&quot;&gt;&lt;code&gt;supplyAsync&lt;/code&gt;&lt;/a&gt;), and clashes with standard &lt;code&gt;ExecutorService&lt;/code&gt; implementations.&lt;/p&gt; &lt;p&gt;Oddly the source for &lt;code&gt;CompletableFuture&lt;/code&gt; shows interrupts could have been addressed in a straight-forward way:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public T get() throws InterruptedException, ExecutionException {
    Object r; Throwable ex, cause;
    if ((r = result) == null &amp;&amp; (r = waitingGet(true)) == null)
        throw new InterruptedException();
    if (!(r instanceof AltResult)) {
        @SuppressWarnings(&quot;unchecked&quot;) T tr = (T) r;
        return tr;
    }
    if ((ex = ((AltResult)r).ex) == null)
        return null;
    if (ex instanceof CancellationException)
        throw (CancellationException)ex;
    // Hypothetical approach to exposing interrupts, NOT in the JDK:
    // if (ex instanceof InterruptedException)
    //     throw (InterruptedException)ex;
    if ((ex instanceof CompletionException) &amp;&amp;
        (cause = ex.getCause()) != null)
        ex = cause;
    throw new ExecutionException(ex);
}&lt;/pre&gt; &lt;p&gt;I suspect there is some deeper interaction I am missing that such an easy solution was avoided.  (This also shows off nicely the new ability in Java 8 to annotate assignments.)&lt;/p&gt; &lt;p&gt;That I can tell &lt;code&gt;CompletableFuture&lt;/code&gt; was modeled on other libraries and languages, especially Guava's &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/SettableFuture.html&quot;&gt;&lt;code&gt;SettableFuture&lt;/code&gt;&lt;/a&gt; and Akka's &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://doc.akka.io/api/akka/2.0/akka/dispatch/Promise.html&quot;&gt;&lt;code&gt;Promise&lt;/code&gt;&lt;/a&gt; (formerly named &lt;code&gt;CompletableFuture&lt;/code&gt;).  Tomasz Nurkiewicz points out &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.nurkiewicz.com/2013/05/java-8-definitive-guide-to.html&quot;&gt;the considerable value-add&lt;/a&gt; in the Java 8 variant.  Koji Lin provides &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.slideshare.net/kojilin/completable-future&quot;&gt;the slides&lt;/a&gt;.&lt;/p&gt; &lt;h3&gt;Solution&lt;/h3&gt; &lt;p&gt;Let's integrate &lt;code&gt;CompletableFuture&lt;/code&gt; into &lt;code&gt;ExecutorService&lt;/code&gt;.&lt;/p&gt; &lt;p&gt;The natural approach is to extend &lt;code&gt;ExecutorService&lt;/code&gt;, overriding methods which return &lt;code&gt;Future&lt;/code&gt; to return &lt;code&gt;CompletableFuture&lt;/code&gt; (&lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://blogs.oracle.com/sundararajan/entry/covariant_return_types_in_java&quot;&gt;covariant return&lt;/a&gt; from Java 5).  This means updating methods which construct or return &lt;code&gt;ExecutorService&lt;/code&gt; to return, say, &lt;code&gt;CompletableExecutorService&lt;/code&gt;.  My ideal solution uses &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://binkley.blogspot.com/2007/10/feature-request-for-jdk7-delegation.html&quot;&gt;a non-existent Java language feature&lt;/a&gt;, assignment to &lt;code&gt;this&lt;/code&gt; for delegation (alas not in this timeline).  A practical solution is &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://en.wikipedia.org/wiki/Mixin&quot;&gt;mixins&lt;/a&gt;.  So &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/binkley/blob/develop/concurrent/src/main/java/hm/binkley/util/concurrent/CompletableExecutors.java&quot;&gt;let's write that&lt;/a&gt;:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public interface CompletableExecutorService extends ExecutorService {
    /**
     * @return a completable future representing pending completion of the
     * task, never missing
     */
    @Nonnull
    @Override
    &amp;lt;T&amp;gt; CompletableFuture&amp;lt;T&amp;gt; submit(@Nonnull final Callable&amp;lt;T&amp;gt; task);

    /**
     * @return a completable future representing pending completion of the
     * task, never missing
     */
    @Nonnull
    @Override
    &amp;lt;T&amp;gt; CompletableFuture&amp;lt;T&amp;gt; submit(@Nonnull final Runnable task,
            @Nullable final T result);

    /**
     * @return a completable future representing pending completion of the
     * task, never missing
     */
    @Nonnull
    @Override
    CompletableFuture&amp;lt;?&amp;gt; submit(@Nonnull final Runnable task);
}&lt;/pre&gt; &lt;p&gt;A static factory method turns any &lt;code&gt;ExecutorService&lt;/code&gt; into a &lt;code&gt;CompletableExecutorService&lt;/code&gt;:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@Nonnull
public static CompletableExecutorService completable(
        @Nonnull final ExecutorService threads) {
    return newMixin(CompletableExecutorService.class,
            new Overrides(threads), threads);
}&lt;/pre&gt; &lt;p&gt;The grunt work is in &lt;code&gt;Overrides&lt;/code&gt;:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public static final class Overrides {
    private final ExecutorService threads;

    private Overrides(final ExecutorService threads) {
        this.threads = threads;
    }

    @Nonnull
    public &amp;lt;T&amp;gt; CompletableFuture&amp;lt;T&amp;gt; submit(
            @Nonnull final Callable&amp;lt;T&amp;gt; task) {
        final CompletableFuture&amp;lt;T&amp;gt; cf = new UnwrappedCompletableFuture&amp;lt;&amp;gt;();
        threads.submit(() -&amp;gt; {
            try {
                cf.complete(task.call());
            } catch (final CancellationException e) {
                cf.cancel(true);
            } catch (final Exception e) {
                cf.completeExceptionally(e);
            }
        });
        return cf;
    }

    @Nonnull
    public &amp;lt;T&amp;gt; CompletableFuture&amp;lt;T&amp;gt; submit(@Nonnull final Runnable task,
            @Nullable final T result) {
        return submit(callable(task, result));
    }

    @Nonnull
    public CompletableFuture&amp;lt;?&amp;gt; submit(@Nonnull final Runnable task) {
        return submit(callable(task));
    }
}&lt;/pre&gt; &lt;p&gt;What is &lt;code&gt;UnwrappedCompletableFuture&lt;/code&gt;?  It handles the pesky issue mentioned above with interrupts:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;private static final class UnwrappedCompletableFuture&amp;lt;T&amp;gt;
        extends CompletableFuture&amp;lt;T&amp;gt; {
    @Override
    public T get() throws InterruptedException, ExecutionException {
        return UnwrappedInterrupts.&amp;lt;T, RuntimeException&amp;gt;unwrap(super::get);
    }

    @Override
    public T get(final long timeout, final TimeUnit unit)
            throws InterruptedException, ExecutionException,
            TimeoutException {
        return UnwrappedInterrupts.&amp;lt;T, TimeoutException&amp;gt;unwrap(
                () -&amp;gt; super.get(timeout, unit));
    }

    @FunctionalInterface
    private interface UnwrappedInterrupts&amp;lt;T, E extends Exception&amp;gt; {
        T get() throws InterruptedException, ExecutionException, E;

        static &amp;lt;T, E extends Exception&amp;gt; T unwrap(
                final UnwrappedInterrupts&amp;lt;T, E&amp;gt; wrapped)
                throws InterruptedException, ExecutionException, E {
            try {
                return wrapped.get();
            } catch (final ExecutionException e) {
                final Throwable cause = e.getCause();
                if (cause instanceof InterruptedException)
                    throw (InterruptedException) cause;
                throw e;
            }
        }
    }
}&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-5375833267809821391</guid>
         <pubDate>Fri, 26 Dec 2014 11:28:00 +0000</pubDate>
      </item>
      <item>
         <title>LISP written in sed</title>
         <link>http://binkley.blogspot.com/2014/12/lisp-written-in-sed.html</link>
         <description>&lt;p&gt;As &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://plus.google.com/+EricRaymond/posts/WJp7aCMifY1&quot;&gt;Eric Raymond&lt;/a&gt; points out, &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/shinh/sedlisp&quot;&gt;sedlisp&lt;/a&gt; is wrong ... but right.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-1780119209500894321</guid>
         <pubDate>Wed, 24 Dec 2014 20:01:00 +0000</pubDate>
      </item>
      <item>
         <title>Blog code 0.5</title>
         <link>http://binkley.blogspot.com/2014/12/blog-code-05.html</link>
         <description>&lt;p&gt;I've published to Maven Central a set of Java jars capturing code and ideas from this blog and Internet reading.  The maven coordinates are &lt;code&gt;hm.binkley:*:0.5&lt;/code&gt;.  Other vital statistics:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;GitHub - &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/binkley&quot;&gt;https://github.com/binkley/binkley&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Travis CI - &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://travis-ci.org/binkley/binkley&quot;&gt;https://travis-ci.org/binkley/binkley&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Mingle - &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://binkley.mingle.thoughtworks.com/projects/binkley&quot;&gt;https://binkley.mingle.thoughtworks.com/projects/binkley&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I still need to update the javadoc pages hosted by GitHub.  I'm particularly happy to have finally worked out how to &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/binkley/blob/master/lombok/src/main/java/hm/binkley/lombok/ThreadNamed.java&quot;&gt;make a lombok processor&lt;/a&gt;.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-8322488443345290573</guid>
         <pubDate>Thu, 18 Dec 2014 05:48:00 +0000</pubDate>
      </item>
      <item>
         <title>Where I fit in</title>
         <link>http://binkley.blogspot.com/2014/12/where-i-fit-in.html</link>
         <description>&lt;p&gt;While reading on how to improve recruiting for Macquarie, I ran across an interesting job candidate description.  Not a particular applicant, a description of a type of applicant: &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.jrothman.com/htp/hiring-strategy/2014/11/five-tips-to-hiring-a-generalizing-specialist/&quot; title=&quot;Five Tips to Hiring a Generalizing Specialist&quot;&gt;&lt;cite&gt;Five Tips to Hiring a Generalizing Specialist&lt;/cite&gt;&lt;/a&gt;.  Apparently there is a name for people like me. (More at &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.agilemodeling.com/essays/generalizingSpecialists.htm&quot;&gt;&lt;cite&gt;Generalizing Specialists: Improving Your IT Career Skills&lt;/cite&gt;&lt;/a&gt;.)&lt;/p&gt; &lt;p&gt;My career path has been atypical.  I graduated a with a degree in classical music and jumped into programming out of need.  I was very fortunate to have smart, capable friends who recommended the right books.  And I wound up one of those, a &quot;generalizing specialist&quot;.&lt;/p&gt; &lt;p&gt;It makes for a non-linear work life, which is challenging, and leads to opportunities less available otherwise.  It is never dull.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-1340432323660581952</guid>
         <pubDate>Wed, 17 Dec 2014 15:45:00 +0000</pubDate>
      </item>
      <item>
         <title>Java validation</title>
         <link>http://binkley.blogspot.com/2014/12/java-validation.html</link>
         <description>&lt;p&gt;Martin Fowler posted &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://martinfowler.com/articles/replaceThrowWithNotification.html&quot; title=&quot;Replacing Throwing Exceptions with Notification in Validations&quot;&gt;&lt;cite&gt;Replacing Throwing Exceptions with Notification in Validations&lt;/cite&gt;&lt;/a&gt; discussing alternatives to data validation than throwing exceptions.  There are off-the-shelf solutions such as &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://commons.apache.org/proper/commons-validator/&quot; title=&quot;Commons Validator&quot;&gt;Commons Validator&lt;/a&gt; (XML driven) or &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://beanvalidation.org/&quot; title=&quot;Bean Validation&quot;&gt;Bean Validation&lt;/a&gt; (annotation driven) which are complete frameworks.&lt;/p&gt; &lt;p&gt;There is more to these frameworks than I suggest, but to explore Fowler's post better I quickly coded up my own simple-minded approach:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public final class ValidationMain {
    public static void main(final String... args) {
        final Notices notices = new Notices();
        notices.add(&quot;Something went horribly wrong %d time(s)&quot;, 1);
        try {
            foo(null);
        } catch (final Exception e) {
            notices.add(e);
        }
        notices.forEach(err::println);
        notices.fail(IllegalArgumentException::new);
    }

    public static String foo(final Object missing) {
        return missing.toString();
    }
}&lt;/pre&gt; &lt;p&gt;Output on stderr:&lt;/p&gt; &lt;pre&gt;lab.Notices$Notice@27f8302d
lab.Notices$Notice@4d76f3f8
Exception in thread &quot;main&quot; java.lang.IllegalArgumentException: 2 notices:
 Something went horribly wrong 1 time(s)
 at lab.ValidationMain.main(ValidationMain.java:21)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:483)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
 Suppressed: java.lang.IllegalArgumentException: Only 1 reason(s)
  at lab.ValidationMain.main(ValidationMain.java:14)
 Suppressed: java.lang.IllegalArgumentException
  at lab.ValidationMain.main(ValidationMain.java:18)
 Caused by: java.lang.NullPointerException
  at lab.ValidationMain.foo(ValidationMain.java:25)
  at lab.ValidationMain.main(ValidationMain.java:16)&lt;/pre&gt; &lt;p&gt;And the &lt;code&gt;Notices&lt;/code&gt; class: &lt;pre class=&quot;code&quot;&gt;public final class Notices
        implements Iterable&amp;lt;Notice&amp;gt; {
    private final List&amp;lt;Notice&amp;gt; notices = new ArrayList&amp;lt;&amp;gt;(0);

    public void add(final String reason, final Object... args) {
        // Duplicate code so stack trace keeps same structure
        notices.add(new Notice(null, reason, args));
    }

    public void add(final Throwable cause) {
        // Duplicate code so stack trace keeps same structure
        notices.add(
                new Notice(cause, null == cause ? null : cause.getMessage()));
    }

    public void add(final Throwable cause, final String reason,
            final Object... args) {
        // Duplicate code so stack trace keeps same structure
        notices.add(new Notice(cause, reason, args));
    }

    public &amp;lt;E extends Exception&amp;gt; void fail(
            final BiFunction&amp;lt;String, Throwable, E&amp;gt; ctor)
            throws E {
        final E e = ctor.apply(toString(), null);
        notices.forEach(n -&amp;gt; e.addSuppressed(n.as(ctor)));
        final List&amp;lt;StackTraceElement&amp;gt; frames = asList(e.getStackTrace());
        // 2 is the magic number: lambda, current
        e.setStackTrace(frames.subList(2, frames.size())
                .toArray(new StackTraceElement[frames.size() - 2]));
        throw e;
    }

    @Override
    public Iterator&amp;lt;Notice&amp;gt; iterator() {
        return unmodifiableList(notices).iterator();
    }

    @Override
    public String toString() {
        if (notices.isEmpty())
            return &quot;0 notices&quot;;
        final String sep = lineSeparator() + &quot;&amp;#92;t&quot;;
        return notices.stream().
                map(Notice::reason).
                filter(Objects::nonNull).
                collect(joining(sep,
                        format(&quot;%d notices:&quot; + sep, notices.size()), &quot;&quot;));
    }

    public static final class Notice {
        // 4 is the magic number: Thread, init, init, addError, finally the
        // user code
        private final StackTraceElement location = currentThread()
                .getStackTrace()[4];
        private final Throwable cause;
        private final String reason;
        private final Object[] args;

        private Notice(final Throwable cause, final String reason,
                final Object... args) {
            this.cause = cause;
            this.reason = reason;
            this.args = args;
        }

        public Throwable cause() {
            return cause;
        }

        public String reason() {
            return null == reason ? null : format(reason, args);
        }

        private &amp;lt;E extends Exception&amp;gt; E as(
                final BiFunction&amp;lt;String, Throwable, E&amp;gt; ctor) {
            final E e = ctor.apply(reason(), cause);
            e.setStackTrace(new StackTraceElement[]{location});
            return e;
        }
    }
}&lt;/pre&gt; &lt;p&gt;Comments:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;I manipulate the stack traces to focus on the caller's point of view.  This is the opposite of, say, Spring Framework.&lt;/li&gt; &lt;li&gt;I haven't decided on what an intelligent &lt;code&gt;toString()&lt;/code&gt; should look like for &lt;code&gt;Notice&lt;/code&gt;&lt;/li&gt; &lt;li&gt;Java 8 lambdas really shine here.  Being able to use exception constructors as method references is a win.&lt;/li&gt;&lt;/ul&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-818880213572544900</guid>
         <pubDate>Wed, 10 Dec 2014 05:54:00 +0000</pubDate>
      </item>
      <item>
         <title>Writing your own lombok annotation</title>
         <link>http://binkley.blogspot.com/2014/12/writing-your-own-lombok-annotation.html</link>
         <description>&lt;p&gt;It took me quite a while to get around to writing my own &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://projectlombok.org/features/index.html&quot; title=&quot;Lombok features&quot;&gt;lombok annotation&lt;/a&gt; and processor.  This took more effort than I expected, hopefully this post will save someone else some.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;tl;dr&lt;/strong&gt; &amp;mdash; Look at the source in &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/binkley/tree/develop/lombok&quot;&gt;my Github repo&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Motivation&lt;/h3&gt;

&lt;p&gt;Reading the excellent &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.nurkiewicz.com/2014/11/executorservice-10-tips-and-tricks.html&quot; title=&quot;ExecutorService - 10 tips and tricks&quot;&gt;&lt;cite&gt;ExecutorService - 10 tips and tricks&lt;/cite&gt;&lt;/a&gt; by Tomasz Nurkiewicz, I thought about tip #2, &lt;cite&gt;Switch names according to context&lt;/cite&gt;, which recommends wrapping important methods and code blocks with custom thread names to aid in logging and debugging.&lt;/p&gt; &lt;p&gt;&quot;This is a great use case for annotations!&quot; I thought.  The code screams &lt;em&gt;boilerplate&lt;/em&gt;:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public void doNiftyThings() {
    final Thread thread = Thread.currentThread();
    final String oldName = thread.getName();
    thread.setName(&quot;Boy this is nifty!&quot;);
    try {
        // Do those nifty things - the actual work
    } finally {
        thread.setName(oldName);
    }
}&lt;/pre&gt; &lt;p&gt;The whole point of the method is indented out of focus, wrapped with bookkeeping.  I'd rather write this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@ThreadNamed(&quot;Boy this is nifty!&quot;)
public void doNiftyThings() {
    // Do those nifty thing - the actual work
}&lt;/pre&gt; &lt;p&gt;Bonus: simple text search finds those places in my code where I change the thread name based on context.&lt;/p&gt;

&lt;h3&gt;Writing the annotation&lt;/h3&gt;

&lt;p&gt;Ok, let's make this work.  I started with cloning &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/rzwitserloot/lombok/blob/master/src/core/lombok/javac/handlers/HandleCleanup.java&quot;&gt;the &lt;code&gt;@Cleanup&lt;/code&gt; annotation and processor&lt;/a&gt;, and editing from there.  First the annotation, the easy bit.  I include the javadoc to emphasize the importance of documenting your public APIs.&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;/**
 * {@code ThreadNamed} sets the thread name during method execution, restoring
 * it when the method completes (normally or exceptionally).
 *
 * @author &amp;lt;a href=&quot;mailto:binkley@alumni.rice.edu&quot;&amp;gt;B. K. Oxley (binkley)&amp;lt;/a&amp;gt;
 */
@Documented
@Retention(SOURCE)
@Target({CONSTRUCTOR, METHOD})
public @interface ThreadNamed {
    /** The name for the thread while the annotated method executes. */
    String value();
}
&lt;/pre&gt; &lt;p&gt;Nothing special here.  I've made the decision to limit the annotation to methods and constructors.  Ideally I'd include &lt;em&gt;blocks&lt;/em&gt; but that isn't an option (yet) in Java, and you can always refactor out a block to a method.&lt;/p&gt;

&lt;h3&gt;Writing the processor&lt;/h3&gt;

&lt;p&gt;This is the serious part.  First some preliminaries:&lt;/p&gt; &lt;ol&gt;&lt;li&gt;I have only implemented support for JDK javac.  Lombok also supports the Eclipse compiler, which requires a separate processor class.  I have nothing against Eclipse, but it's not in my toolkit.&lt;/li&gt; &lt;li&gt;I'll discuss library dependencies below.  For now pretend these are already working for you.&lt;/li&gt; &lt;li&gt;I'm a big fan of static imports, the diamond operator, etc.  I don't like retyping what the compiler is already thinking.  You should note &lt;code&gt;List&lt;/code&gt; below is &lt;em&gt;not&lt;/em&gt; &lt;code&gt;java.util.List&lt;/code&gt;; it's &lt;code&gt;com.sun.tools.javac.util.List&lt;/code&gt;.  Yeah, I don't know this class either.&lt;/li&gt; &lt;li&gt;The implementation is hard to follow.  Most of us don't spend much time with &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://en.wikipedia.org/wiki/Binary_expression_tree&quot; title=&quot;Binary expression trees&quot;&gt;expression trees&lt;/a&gt;, which is how most compilers (including javac) see your source code.  A language like LISP lets you write you code as the expression tree directly, which is both nifty and challenging (macros being like annotation processors).&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;Without further ado:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;/**
 * Handles the {@code lombok.ThreadNamed} annotation for javac.
 */
@MetaInfServices(JavacAnnotationHandler.class)
@HandlerPriority(value = 1024)
// 2^10; @NonNull must have run first, so that we wrap around the
// statements generated by it.
public class HandleThreadNamed
        extends JavacAnnotationHandler&amp;lt;ThreadNamed&amp;gt; {
    /**
     * lombok configuration: {@code lab.lombok.threadNamed.flagUsage} = {@code
     * WARNING} | {@code ERROR}.
     * &amp;lt;p&amp;gt;
     * If set, &amp;lt;em&amp;gt;any&amp;lt;/em&amp;gt; usage of {@code @ThreadNamed} results in a warning
     * / error.
     */
    public static final ConfigurationKey&amp;lt;FlagUsageType&amp;gt;
            THREAD_NAMED_FLAG_USAGE = new ConfigurationKey&amp;lt;FlagUsageType&amp;gt;(
            &quot;lab.lombok.threadNamed.flagUsage&quot;,
            &quot;Emit a warning or error if @ThreadNamed is used.&quot;) {
    };

    @Override
    public void handle(final AnnotationValues&amp;lt;ThreadNamed&amp;gt; annotation,
            final JCAnnotation ast, final JavacNode annotationNode) {
        handleFlagUsage(annotationNode, THREAD_NAMED_FLAG_USAGE,
                &quot;@ThreadNamed&quot;);

        deleteAnnotationIfNeccessary(annotationNode, ThreadNamed.class);
        final String threadName = annotation.getInstance().value();
        if (threadName.isEmpty()) {
            annotationNode.addError(&quot;threadName cannot be the empty string.&quot;);
            return;
        }

        final JavacNode owner = annotationNode.up();
        switch (owner.getKind()) {
        case METHOD:
            handleMethod(annotationNode, (JCMethodDecl) owner.get(),
                    threadName);
            break;
        default:
            annotationNode.addError(
                    &quot;@ThreadNamed is legal only on methods and constructors&quot;
                            + &quot;.&quot;);
            break;
        }
    }

    public void handleMethod(final JavacNode annotation,
            final JCMethodDecl method, final String threadName) {
        final JavacNode methodNode = annotation.up();

        if ((method.mods.flags &amp;amp; Flags.ABSTRACT) != 0) {
            annotation.addError(
                    &quot;@ThreadNamed can only be used on concrete methods.&quot;);
            return;
        }

        if (method.body == null || method.body.stats.isEmpty()) {
            generateEmptyBlockWarning(annotation, false);
            return;
        }

        final JCStatement constructorCall = method.body.stats.get(0);
        final boolean isConstructorCall = isConstructorCall(constructorCall);
        List&amp;lt;JCStatement&amp;gt; contents = isConstructorCall
                ? method.body.stats.tail : method.body.stats;

        if (contents == null || contents.isEmpty()) {
            generateEmptyBlockWarning(annotation, true);
            return;
        }

        contents = List
                .of(buildTryFinallyBlock(methodNode, contents, threadName,
                        annotation.get()));

        method.body.stats = isConstructorCall ? List.of(constructorCall)
                .appendList(contents) : contents;
        methodNode.rebuild();
    }

    public void generateEmptyBlockWarning(final JavacNode annotation,
            final boolean hasConstructorCall) {
        if (hasConstructorCall)
            annotation.addWarning(
                    &quot;Calls to sibling / super constructors are always &quot;
                            + &quot;excluded from @ThreadNamed;&quot;
                            + &quot; @ThreadNamed has been ignored because there&quot;
                            + &quot; is no other code in &quot; + &quot;this constructor.&quot;);
        else
            annotation.addWarning(
                    &quot;This method or constructor is empty; @ThreadNamed has &quot;
                            + &quot;been ignored.&quot;);
    }

    public JCStatement buildTryFinallyBlock(final JavacNode node,
            final List&amp;lt;JCStatement&amp;gt; contents, final String threadName,
            final JCTree source) {
        final String currentThreadVarName = &quot;$currentThread&quot;;
        final String oldThreadNameVarName = &quot;$oldThreadName&quot;;

        final JavacTreeMaker maker = node.getTreeMaker();
        final Context context = node.getContext();

        final JCVariableDecl saveCurrentThread = createCurrentThreadVar(node,
                maker, currentThreadVarName);
        final JCVariableDecl saveOldThreadName = createOldThreadNameVar(node,
                maker, currentThreadVarName, oldThreadNameVarName);

        final JCStatement changeThreadName = setThreadName(node, maker,
                maker.Literal(threadName), currentThreadVarName);
        final JCStatement restoreOldThreadName = setThreadName(node, maker,
                maker.Ident(node.toName(oldThreadNameVarName)),
                currentThreadVarName);

        final JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents),
                source, context);
        final JCTry wrapMethod = maker.Try(tryBlock, nil(),
                maker.Block(0, List.of(restoreOldThreadName)));

        if (inNetbeansEditor(node)) {
            //set span (start and end position) of the try statement and
            // the main block
            //this allows NetBeans to dive into the statement correctly:
            final JCCompilationUnit top = (JCCompilationUnit) node.top()
                    .get();
            final int startPos = contents.head.pos;
            final int endPos = Javac
                    .getEndPosition(contents.last().pos(), top);
            tryBlock.pos = startPos;
            wrapMethod.pos = startPos;
            Javac.storeEnd(tryBlock, endPos, top);
            Javac.storeEnd(wrapMethod, endPos, top);
        }

        return setGeneratedBy(maker.Block(0,
                        List.of(saveCurrentThread, saveOldThreadName,
                                changeThreadName, wrapMethod)), source,
                context);
    }

    private static JCVariableDecl createCurrentThreadVar(final JavacNode node,
            final JavacTreeMaker maker, final String currentThreadVarName) {
        return maker.VarDef(maker.Modifiers(FINAL),
                node.toName(currentThreadVarName),
                genJavaLangTypeRef(node, &quot;Thread&quot;), maker.Apply(nil(),
                        genJavaLangTypeRef(node, &quot;Thread&quot;, &quot;currentThread&quot;),
                        nil()));
    }

    private static JCVariableDecl createOldThreadNameVar(final JavacNode node,
            final JavacTreeMaker maker, final String currentThreadVarName,
            final String oldThreadNameVarName) {
        return maker.VarDef(maker.Modifiers(FINAL),
                node.toName(oldThreadNameVarName),
                genJavaLangTypeRef(node, &quot;String&quot;),
                getThreadName(node, maker, currentThreadVarName));
    }

    private static JCMethodInvocation getThreadName(final JavacNode node,
            final JavacTreeMaker maker, final String currentThreadVarNAme) {
        return maker.Apply(nil(),
                maker.Select(maker.Ident(node.toName(currentThreadVarNAme)),
                        node.toName(&quot;getName&quot;)), nil());
    }

    private static JCStatement setThreadName(final JavacNode node,
            final JavacTreeMaker maker, final JCExpression threadName,
            final String currentThreadVarName) {
        return maker.Exec(maker.Apply(nil(),
                maker.Select(maker.Ident(node.toName(currentThreadVarName)),
                        node.toName(&quot;setName&quot;)), List.of(threadName)));
    }
}&lt;/pre&gt; &lt;p&gt;Wasn't that easy?&lt;/p&gt;

&lt;h3&gt;Dependencies&lt;/h3&gt;

&lt;p&gt;Of course the code depends on &lt;em&gt;lombok&lt;/em&gt;.  I'm using version 1.14.8.  It also needs &lt;code&gt;tools.jar&lt;/code&gt; from the JDK for compiler innards like expression trees.  (An Eclipse processor needs an equivalent.)&lt;/p&gt; &lt;p&gt;Unfortunately lombok itself uses &quot;mangosdk&quot; to generate a &lt;code&gt;META-INF/services/lombok.javac.JavacAnnotationHandler&lt;/code&gt; file for autodiscovery of processors.  I say 'unfortunately' because this library is not in maven and is unsupported.  Happyily Kohsuke Kawaguchi wrote the excellent &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html&quot;&gt;metainf-services&lt;/a&gt; library a while back, maintains it, and publishes to Maven central.  If you're new to annotation processors it's a good project to learn from.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Ok, that was not actually so easy.  On the other hand, finding a starting point was the biggest hurdle for me in writing a lombok annotation.  Please &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/binkley/tree/develop/lombok&quot;&gt;browse my source&lt;/a&gt; and try your hand at one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE&lt;/strong&gt; &amp;mdash; A little bonus.  This code:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@ThreadNamed(&quot;Slot #%2$d&quot;)
public void doSomething(final String name, final int slot) {
    // Do something with method params
}&lt;/pre&gt; &lt;p&gt;Produces the thread name &quot;Slot #2&quot; when called with &lt;code&gt;&quot;Foo&quot;, 2&lt;/code&gt;.  Strings without formatting or methods with params treat the annotation value as a plain string.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-635359288455370557</guid>
         <pubDate>Sat, 06 Dec 2014 12:59:00 +0000</pubDate>
      </item>
      <item>
         <title>The ORM anti-pattern</title>
         <link>http://binkley.blogspot.com/2014/12/the-orm-anti-pattern.html</link>
         <description>&lt;p&gt;Yegor Bugayenko writes on &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://www.yegor256.com/2014/12/01/orm-offensive-anti-pattern.html&quot; title=&quot;ORM Is an Offensive Anti-Pattern&quot;&gt;&lt;cite&gt;ORM Is an Offensive Anti-Pattern&lt;/cite&gt;&lt;/a&gt;, offering a pure OO alternative.&lt;/p&gt;

&lt;p&gt;(I've posted too many links to &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://plus.google.com/+BrianOxleyTexan/posts&quot;&gt;my Google+ account&lt;/a&gt;.  It's a ghetto over there as my public posts are science-oriented, programming is shared privately.)&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-2092388641580189809</guid>
         <pubDate>Mon, 01 Dec 2014 13:47:00 +0000</pubDate>
      </item>
      <item>
         <title>Aiming for the right level</title>
         <link>http://binkley.blogspot.com/2014/11/aiming-for-right-level.html</link>
         <description>&lt;p&gt;Vinod Kumaar Ramakrishnan writes &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://vinodkumaar.wordpress.com/2014/11/12/it-is-just-a-road-not-a-roadmap/&quot;&gt;&lt;cite&gt;It is just a road not a roadmap&lt;/cite&gt;&lt;/a&gt; making a strong point visually: &lt;em&gt;software needs a map, not a road&lt;/em&gt;. &lt;img src=&quot;https://vinodkumaar.files.wordpress.com/2014/11/screen-shot-2014-11-11-at-1-17-42-pm.png&quot; alt=&quot;Roadmap&quot; width=&quot;241&quot; height=&quot;300&quot; align=&quot;right&quot;&gt;&lt;/p&gt; &lt;p&gt;This is important to understand at any level of an organization.  The problem comes as you perform larger roles.&lt;/p&gt; &lt;p&gt;You can track only so much detail&amp;mdash;minds have a capacity.  Using a Road rather than a Map overcomes this for viewing lower down the organization.  Pull back your view and substitutes rough pictures for details.  Then build a bigger map, less granular, covering a larger area.  It's still a map, but a map of a country rather than a region or a place.&lt;/p&gt; &lt;p&gt;Managing calls for finding the right level of detail, be it the application or team or project or programme or department.  But remember to keep rebuilding your map and explore some.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-1956842181123661866</guid>
         <pubDate>Thu, 13 Nov 2014 06:53:00 +0000</pubDate>
      </item>
      <item>
         <title>Overcoming Java 8 streams</title>
         <link>http://binkley.blogspot.com/2014/08/overcoming-java-8-streams.html</link>
         <description>&lt;p&gt;Java 8 streams provide functional and LINQ-like features in a fluent API.  But streams are not without drawbacks:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;Referenced methods and lambdas cannot throw checked exceptions&lt;/li&gt; &lt;li&gt;Controlling the threads used, especially for parallel streams, is awkward&lt;/li&gt; &lt;li&gt;Streams are not designed for extension&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Overcoming these drawbacks requires a &quot;look-a-like&quot; API.  For example, implementing &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html&quot;&gt;&lt;code&gt;java.util.stream.Stream&lt;/code&gt;&lt;/a&gt; does not help: none of the existing methods throw checked exceptions, and none of the existing stream factory helpers would return your implementation with new methods.&lt;/p&gt; &lt;p&gt;So I wrote my own, copying the existing stream API, updating the methods to throw checked exceptions:&lt;/p&gt; &lt;p&gt;&lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/binkley/blob/develop/util/src/main/java/hm/binkley/util/stream/CheckedStream.java&quot;&gt;&lt;code&gt;hm.binkley.util.stream.CheckedStream&lt;/code&gt;&lt;/a&gt; ('develop' branch for now)&lt;/p&gt; &lt;p&gt;From the javadoc:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;&lt;code&gt;CheckedStream&lt;/code&gt; is a throwing &lt;code&gt;Stream&lt;/code&gt; look-a-like with control over thread pool. It cannot be a &lt;code&gt;Stream&lt;/code&gt; as it takes throwing versions of suppliers, functions and consumers. Otherwise it is a faithful reproduction.&lt;/p&gt; &lt;p&gt;Write this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;   long beanCount() throws SomeException, OtherException {
       checked(Stream.of(1, 2, 3)).
           map(this::someThrowingFunction).
           peek(That::oldBean).
           count();
   }&lt;/pre&gt; &lt;p&gt;not this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;   long beanCount() throws SomeException, OtherException {
       try {
           Stream.of(1, 2, 3).
               map(i -&amp;gt; {
                   try {
                       someThrowingFunction(i);
                   } catch (final SomeException e) {
                       throw new RuntimeException(e);
                   }
               }).
               peek(i -&amp;gt; {
                   try {
                       That.oldBean(i);
                   } catch (final OtherException e) {
                       throw new RuntimeException(e);
                   }
               }).
               count();
       } catch (final RuntimeException e) {
           final Throwable x = e.getCause();
           if (x instanceof SomeException)
               throw (SomeException) x;
           if (x instanceof OtherException)
               throw (OtherException) x;
           throw e;
       }
   }&lt;/pre&gt; &lt;p&gt;&quot;Intentional&quot; exceptions (checked exceptions plus &lt;code&gt;CancellationException&lt;/code&gt;) have &quot;scrubbed&quot; stacktraces: frames from framework/glue packages are removed before the intentional exception is rethrown to calling code. Scrubbed stacktraces are much easier to understand, the framework and glue code having been removed.&lt;/p&gt; &lt;p&gt;To see the unscrubbed stacktrace, set the system property &quot;hm.binkley.util.stream.CheckedStream.debug&quot; to &quot;true&quot;.&lt;/p&gt; &lt;p&gt;Controlling the thread pool used by &lt;code&gt;Stream&lt;/code&gt; is a challenge. Deep in the implementation, it checks if being run in a &lt;code&gt;ForkJoinTask&lt;/code&gt;, and uses that thread if so, otherwise using the common pool. So with &lt;code&gt;CheckedStream&lt;/code&gt; write this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;       checked(stream, new ForkJoinPool()).
           map(currentThread()).
           forEach(System.out::println);&lt;/pre&gt; &lt;p&gt;not this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;       try {
           new ForkJoinPool().submit(() -&amp;gt; stream.
                   map(currentThread()).
                   forEach(System.out::println)).
               get();
       } catch (final ExecutionException e) {
           final Throwable x = e.getCause();
           if (x instanceof Error)
               throw (Error) x;
           if (x instanceof RuntimeException)
               // Much tricker when stream functions throw runtime
               throw (RuntimeException) x;
           throw new Error(e); // We have no checked exceptions in this example
       }&lt;/pre&gt;&lt;/blockquote&gt; &lt;p&gt;Care is taken to respect &lt;em&gt;lazy&lt;/em&gt; and &lt;em&gt;terminal&lt;/em&gt; operations in using thread pools.  Changing thread pool or thread mode mid-stream is supported, and are &quot;immediate&quot; operations: they terminate the existing stream, and start a new one with the changes:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class=&quot;code&quot;&gt;stream.sequential().
    filter(this::someFilter).
    parallel(threads). // Existing lazy operations terminated
    map(this:someMapper).
    forEach(System.out::println);&lt;/pre&gt;&lt;/blockquote&gt; &lt;p&gt;Immediate operations ensure stream methods are run in the correct threading context.&lt;/p&gt; &lt;p&gt;I hope you'll agree: &lt;code&gt;CheckedStream&lt;/code&gt; is nicer to use, especially with existing code using checked exceptions.&lt;/p&gt; &lt;p&gt;Suggestions, bug fixes, improvements welcome!&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-4220627886037092800</guid>
         <pubDate>Sun, 31 Aug 2014 18:26:00 +0000</pubDate>
      </item>
      <item>
         <title>Java 8 magic exception copying</title>
         <link>http://binkley.blogspot.com/2014/07/java-8-magic-exception-copying.html</link>
         <description>&lt;p&gt;Since I can in Java 8 now parameterize constructors as functions, I can write a generic exception copier:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;&amp;lt;E extends Throwable&amp;gt;
E copy(final Throwable from, final Function&amp;lt;String, E&amp;gt; ctor) {
    final E to = ctor.apply(from.getMessage());
    to.setStackTrace(from.getStackTrace());
    for (final Throwable s : from.getSuppressed())
        to.addSuppressed(s);
    return to;
}&lt;/pre&gt; &lt;p&gt;Example:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;try {
    // Something throws
} catch (final AnException | BeException | KatException e) {
    throw copy(e, IOException::new);
}&lt;/pre&gt; &lt;p&gt;This is not a common strategy but one I sometimes use to reduce the incredible size of layered exceptions, especially for logging.  It is also handy for shoehorning 3&lt;sup&gt;rd&lt;/sup&gt;-party exceptions into a common framework exception, a nice feature for APIs to simplify calling code. &lt;code&gt;Copy&lt;/code&gt; helps reduce boilerplate code.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-5754494394020132073</guid>
         <pubDate>Tue, 15 Jul 2014 19:12:00 +0000</pubDate>
      </item>
      <item>
         <title>Lambda annotations</title>
         <link>http://binkley.blogspot.com/2014/07/lambda-annotations.html</link>
         <description>&lt;p&gt;I am still startled by Java.  While playing with &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://bytebuddy.net/#/tutorial#annotation&quot;&gt;Byte Buddy&lt;/a&gt; I noodled with &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://bytebuddy.net/javadoc/0.2.1/net/bytebuddy/dynamic/DynamicType.Builder.html#annotateType-java.lang.annotation.Annotation...-&quot;&gt;adding annotations&lt;/a&gt; to a class at runtime. I wrote this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;final Class&amp;lt;? extends X&amp;gt; dynamicType
            = (Class&amp;lt;&amp;lt; extends X&amp;gt;) new ByteBuddy().
        subclass(Object.class).
        implement(X.class).
        &lt;em&gt;annotateType(() -&amp;gt; Inject.class).&lt;/em&gt;
        method(named(&quot;toString&quot;)).intercept(value(&quot;Hello World!&quot;)).
        method(named(&quot;foo&quot;)).intercept(value(3)).
        make().
        load(ByteBuddyMain.class.getClassLoader(), WRAPPER).
        getLoaded();&lt;/pre&gt; &lt;p&gt;Get a load of &quot;annotatedType&quot;!  It wants an annotation instance.  Originally I tried:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;new Inject() {
    @Override
    public Class&amp;lt;Inject&amp;gt; annotationType() {
        return Inject.class;
    }
}&lt;/pre&gt; &lt;p&gt;What the hey, then I thought to try the lambda expression and live dangerously.  It works!&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-3733638019509349460</guid>
         <pubDate>Thu, 10 Jul 2014 22:27:00 +0000</pubDate>
      </item>
      <item>
         <title>Modern XML to Java</title>
         <link>http://binkley.blogspot.com/2014/07/modern-xml-to-java.html</link>
         <description>&lt;p&gt;How many frameworks are there for converting XML to Java?  Hard to count.  As an experiment I tried my hand at one.  I have two top-level classes plus an annotation:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public final class XMLFuzzy
        implements InvocationHandler {
    private static final XPath xpath = XPathFactory.newInstance().
            newXPath();
    private static final Map&amp;lt;Method, XPathExpression&amp;gt; expressions
     = new ConcurrentHashMap&amp;lt;&amp;gt;();

    private final Node node;
    private final Converter converter;

    public static final class Factory {
        private final Converter converter;

        public Factory(final Converter converter) {
            this.converter = converter;
        }

        public &amp;lt;T&amp;gt; T of(@Nonnull final Class&amp;lt;T&amp;gt; itf,
                @Nonnull final Node node) {
            return XMLFuzzy.of(itf, node, converter);
        }
    }

    public static &amp;lt;T&amp;gt; T of(@Nonnull final Class&amp;lt;T&amp;gt; itf,
     @Nonnull final Node node,
            @Nonnull final Converter converter) {
        return itf.cast(newProxyInstance(itf.getClassLoader(),
                new Class[]{itf},
                new XMLFuzzy(node, converter)));
    }

    private XMLFuzzy(final Node node, final Converter converter) {
        this.node = node;
        this.converter = converter;
    }

    @Override
    public Object invoke(final Object proxy, final Method method,
         final Object[] args)
            throws Throwable {
        return converter.convert(method.getReturnType(), expressions.
                computeIfAbsent(method, XMLFuzzy::compile).
                evaluate(node));
    }

    private static XPathExpression compile(@Nonnull final Method method) {
        final String expression = asList(method.getAnnotations()).stream().
                filter(From.class::isInstance).
                map(From.class::cast).
                findFirst().
                orElseThrow(() -&amp;gt; new MissingAnnotation(method)).
                value();
        try {
            return xpath.compile(expression);
        } catch (final XPathExpressionException e) {
            throw new BadXPath(method, expression, e);
        }
    }

    public static final class MissingAnnotation
            extends RuntimeException {
        private MissingAnnotation(final Method method) {
            super(format(&quot;Missing @X(xpath) annotation: %s&quot;, method));
        }
    }

    public static final class BadXPath
            extends RuntimeException {
        private BadXPath(final Method method, final String expression,
                final XPathExpressionException e) {
            super(format(&quot;Bad @X(xpath) annotation on '%s': %s: %s&quot;,
                    method, expression, e.getMessage()));
            setStackTrace(e.getStackTrace());
        }
    }
}&lt;/pre&gt;

&lt;p&gt;I have left out &lt;code&gt;Converter&lt;/code&gt;; it turns strings into objects of a given type, another example of overimplemented framework code in Java.  And the annotation:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@Documented
@Inherited
@Retention(RUNTIME)
@Target(METHOD)
public @interface From {
    String value();
}&lt;/pre&gt; &lt;p&gt;The idea is straight-forward: drive the object mapping from XML with XPaths.  Credit to &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://xmlbeam.org&quot;&gt;XMLBeam&lt;/a&gt; for introducing to me the elegant use of JDK proxies for this purpose.&lt;/p&gt; &lt;p&gt;Of course tests:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public final class XMLFuzzyTest {
    private Top top;

    @Before
    public void setUp()
            throws ParserConfigurationException, IOException, SAXException {
        final Document document = DocumentBuilderFactory.newInstance().
                newDocumentBuilder().
                parse(new InputSource(new StringReader(XML)));
        top = new XMLFuzzy.Factory(new Converter()).of(Top.class, document);
    }

    @Test
    public void shouldHandleString() {
        assertThat(top.a(), is(equalTo(&quot;apple&quot;)));
    }

    @Test
    public void shouldHandlePrimitiveInt() {
        assertThat(top.b(), is(equalTo(3)));
    }

    @Test
    public void shouldHandleRURI() {
        assertThat(top.c(), is(equalTo(URI.create(&quot;http://some/where&quot;))));
    }

    @Test(expected = MissingAnnotation.class)
    public void shouldThrowOnMissingAnnotation() {
        top.d();
    }

    @Test(expected = BadXPath.class)
    public void shouldThrowOnBadXPath() {
        top.e();
    }

    public interface Top {
        // For the purposes of this blog post, pretend Java supports
 // multiline string literals
        @Language(&quot;XML&quot;)
        String XML = &quot;&amp;lt;top&amp;gt;
                    &amp;lt;a&amp;gt;apple&amp;lt;/a&amp;gt;
      &amp;lt;b&amp;gt;3&amp;lt;/b&amp;gt;
      &amp;lt;c&amp;gt;http://some/where&amp;lt;/c&amp;gt;
         &amp;lt;/top&amp;gt;&quot;;

        @From(&quot;//top/a&quot;)
        String a();

        @From(&quot;//top/b&quot;)
        int b();

        @From(&quot;//top/c&quot;)
        URI c();

        void d();

        @From(&quot;dis' ain't xpath&quot;)
        void e();
    }
}&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-8760602012290057269</guid>
         <pubDate>Sun, 06 Jul 2014 12:48:00 +0000</pubDate>
      </item>
      <item>
         <title>Java 8 predicate for tee</title>
         <link>http://binkley.blogspot.com/2014/06/java-8-predicate-for-tee.html</link>
         <description>&lt;p&gt;A &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://download.java.net/lambda/b64/docs/api/java/util/streams/Stream.html#tee(java.util.functions.Block)&quot;&gt;&quot;tee&quot; method&lt;/a&gt; did not make it into Java 8 streams, but you can make your own easily enough:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public final class Tee&amp;lt;T&amp;gt;
        implements Predicate&amp;lt;T&amp;gt; {
    private final Predicate&amp;lt;T&amp;gt; test;
    private final Consumer&amp;lt;T&amp;gt; reject;

    @Nonnull
    public static &amp;lt;T&amp;gt; Predicate&amp;lt;T&amp;gt; tee(
            @Nonnull final Predicate&amp;lt;T&amp;gt; test,
            @Nonnull final Consumer&amp;lt;T&amp;gt; reject) {
        return new Tee&amp;lt;&amp;gt;(test, reject);
    }

    private Tee(final Predicate&amp;lt;T&amp;gt; test,
            final Consumer&amp;lt;T&amp;gt; reject) {
        this.test = test;
        this.reject = reject;
    }

    @Override
    public boolean test(final T t) {
        if (test.test(t))
            return true;
        reject.accept(t);
        return false;
    }

    public static void main(final String... args) {
        asList(&quot;a&quot;, &quot;bb&quot;, &quot;ccc&quot;, &quot;dddd&quot;).stream().
                filter(tee(Tee::even, err::println)).
                forEach(out::println);
    }

    private static boolean even(final String s) {
        return 0 == s.length() % 2;
    }
}&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-4437891792946305194</guid>
         <pubDate>Sun, 29 Jun 2014 11:29:00 +0000</pubDate>
      </item>
      <item>
         <title>Agile food for thought</title>
         <link>http://binkley.blogspot.com/2014/06/agile-food-for-thought.html</link>
         <description>&lt;p&gt;Jeffrey Davidson asks if &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://goodrequirements.com/2014/lightweight-agile/&quot;&gt;&lt;cite&gt;Lightweight agile only needs 2 goals&lt;/cite&gt;&lt;/a&gt;.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-1931927370124442503</guid>
         <pubDate>Thu, 12 Jun 2014 13:24:00 +0000</pubDate>
      </item>
      <item>
         <title>Help for Java parameterized tests</title>
         <link>http://binkley.blogspot.com/2014/05/help-for-java-parameterized-tests.html</link>
         <description>&lt;p&gt;JUnit has many great features.  One I especially like is &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/junit-team/junit/wiki/Parameterized-tests&quot; title=&quot;Parameterized tests&quot;&gt;parameterized tests&lt;/a&gt;.&lt;/p&gt; &lt;h3&gt;The problem&lt;/h3&gt; &lt;p&gt;One itch for me however is setting up the parameters and getting failed tests to name themselves.&lt;/p&gt; &lt;p&gt;Modern JUnit has help on the second itch with &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/junit-team/junit/wiki/Parameterized-tests#identify-individual-test-cases&quot; title=&quot;Identify Individual test cases&quot;&gt;the &lt;code&gt;name&lt;/code&gt; parameter to &lt;code&gt;@Parameters&lt;/code&gt;&lt;/a&gt;.  You still need to get the test name passed into the constructor.&lt;/p&gt; &lt;p&gt;But what about setting up the test data?&lt;/p&gt; &lt;p&gt;I write clunky code like this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@Parameters(name = &quot;{index}: {0}&quot;)
public static Collection&amp;lt;Object[]&amp;gt; data() {
    return asList(
            new Object[]{&quot;Some test&quot;, 1, &quot;a string&quot;},
            new Object[]{&quot;Another test&quot;, 2, &quot;another string&quot;}
            /* and so on for each test case */);
}&lt;/pre&gt; &lt;p&gt;This is not the worst code, but with more complex inputs or data it grows into a long list of eye-glazing use cases.  For me this is hard to maintain and document.&lt;/p&gt; &lt;h3&gt;The solution&lt;/h3&gt; &lt;p&gt;As an alternative I scouted around and settled on the venerable Windows INI file format.  It has several virtues in this context:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;The format is simple and well known&lt;/li&gt; &lt;li&gt;Section titles can be use to name tests&lt;/li&gt; &lt;li&gt;Comments are supported&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Looking at libraries for INI support in Java, one stands out: &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://ini4j.sourceforge.net/&quot;&gt;ini4j&lt;/a&gt;.  In particular: &lt;ul&gt;&lt;li&gt;Is stable and acceptably documented&lt;/li&gt; &lt;li&gt;Supports C-style escape sequences, e.g. &lt;code&gt;&amp;#92;t&lt;/code&gt; for TAB&amp;mdash;import for my particular tests&lt;/li&gt; &lt;li&gt;Accepts reasonable ways to input the INI (URL, input stream, &lt;i&gt;et al&lt;/i&gt;)&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Integrating this into &lt;code&gt;@Parameters&lt;/code&gt; is straight-forward.  One approach is this:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@Nonnull
public static List&amp;lt;Object[]&amp;gt; parametersFrom(
        @Nonnull final Ini ini, final Key... keys) {
    final List&amp;lt;Object[]&amp;gt; parameters = new ArrayList&amp;lt;&amp;gt;();
    for (final Section section : ini.values()) {
        final Object[] array = new Object[1 + keys.length];
        array[0] = section.getName();
        for (int i = 0; i &amp;lt; keys.length; i++) {
            final Key key = keys[i];
            final String value = section.fetch(key.name);
            array[1 + i] = null == value ? null : key.get.apply(value);
        }
        parameters.add(array);
    }
    return parameters;
}

public static final class Key {
    public final String name;
    public final Function&amp;lt;String, ?&amp;gt; get;

    @Nonnull
    public static Key of(@Nonnull final String name, @Nonnull final Function&amp;lt;String, ?&amp;gt; get) {
        return new Key(name, get);
    }

    @Nonnull
    public static Key of(@Nonnull final String name) {
        return of(name, Function.identity());
    }

    private Key(final String name, final Function&amp;lt;String, ?&amp;gt; get) {
        this.name = name;
        this.get = get;
     }
}&lt;/pre&gt; &lt;p&gt;A key might look like &lt;code&gt;Key.of(&quot;amount&quot;, BigDecimal::new)&lt;/code&gt;&lt;/p&gt; &lt;h3&gt;Example&lt;/h3&gt; &lt;p&gt;I simplified tests of a money value object to a test name, a value to parse and a currency and amount to expect:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;@RunWith(Parameterized.class)
public class MoneyTest {
    // Failed test messages look like:
    // 0: Missing currency: 1
    @Parameters(name = &quot;{index}: {0}: {1}&quot;)
    public static Collection&amp;lt;Object[]&amp;gt; parameters()
            throws IOException {
        return parametersFrom(
                new Ini(MoneyTest.class.getResource(&quot;MoneyTest.ini&quot;)),
                Key.of(&quot;value&quot;),
                Key.of(&quot;currency&quot;, Currency::getInstance),
                Key.of(&quot;amount&quot;, BigDecimal::new));
    }

    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    private final String description;
    private final String value;
    private final Currency currency;
    private final BigDecimal amount;

    public MoneyTest(@Nonnull final String description,
            @Nonnull final String value,
            @Nullable final Currency currency,
            @Nullable final BigDecimal amount) {
        this.description = description;
        this.value = value;
        this.currency = currency;
        this.amount = amount;

        if (!((null == currency &amp;amp;&amp;amp; null == amount)
                || (null != currency &amp;amp;&amp;amp; null != amount)))
            throw new IllegalArgumentException(
                    format(&quot;%s: currency and amount must both be null or non-null&quot;,
                            description));
    }

    @Test
    public void shouldParse() {
        if (null == currency) {
            thrown.expect(MoneyFormatException.class);
            thrown.expectMessage(value);
        }

        final Money money = Money.parse(value);

        assertThat(money.getCurrency(), is(equalTo(currency)));
        assertThat(money.getAmount(), is(equalTo(amount)));
    }
}&lt;/pre&gt; &lt;pre class=&quot;code&quot;&gt;; Format - INI file
; Section title is description of test, used in reporting failure
; value is the input to `Money.parse(String)`
; IFF parsing should fail:
;   - Do not provide currency/amount
; IFF parsing should pass:
;   - currency is input to `Currency.getInstance(String)`
;   - amount is input is `new BigDecimal(String)`

[Missing currency]
value = 1

[Single dollar, no whitespace]
value = USD1
currency = USD
amount = 1.00&lt;/pre&gt; &lt;p&gt;I like being able to add new tests by text editing of the INI file.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-1429173258546811433</guid>
         <pubDate>Mon, 26 May 2014 13:14:00 +0000</pubDate>
      </item>
      <item>
         <title>World's smallest DAO</title>
         <link>http://binkley.blogspot.com/2014/03/worlds-smallest-dao.html</link>
         <description>&lt;p&gt;The world's smallest Java DAO (with heavy lifting provided by Spring Framework):&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;public class SimpleDAO {
    private final DataSourceTransactionManager transactionManager;

    public SimpleDAO(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public &amp;lt;T&amp;gt; T dao(Dao&amp;lt;T&amp;gt; dao) {
        return dao.using(transactionManager);
    }

    public interface Dao&amp;lt;T&amp;gt; {
        default T using(DataSourceTransactionManager transactionManager) {
            return new TransactionTemplate(transactionManager).execute(
                    status -&amp;gt; on(new JdbcTemplate(transactionManager.getDataSource()), status));
        }

        T on(JdbcTemplate jdbcTemplate, TransactionStatus status);
    }
}&lt;/pre&gt; &lt;p&gt;Usage:&lt;/p&gt; &lt;pre class=&quot;code&quot;&gt;class InviteesDAO {
    private final SimpleDAO transact;

    InviteesDAO(DatabaseTransactionManager transactionManager) {
        transact = new SimpleDAO(tranactionManager);
    }

    List&amp;lt;String&amp;gt; getInvitees() {
        return transact.dao((jdbcTemplate, status) -&amp;gt; jdbcTemplate.queryForList(
            &quot;SELECT username FROM invitees&quot;, String.class));
    }

    void invite(String username) {
        transact.dao((jdbcTemplate, status) -&amp;gt; jdbcTemplate.update(
            &quot;INSERT INTO invitees (username) VALUES (?)&quot;, username));
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt; Demonstrate with composition rather than inheritance.&lt;/p&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-7980989460893458244</guid>
         <pubDate>Thu, 06 Mar 2014 07:14:00 +0000</pubDate>
      </item>
      <item>
         <title>ServiceBinder</title>
         <link>http://binkley.blogspot.com/2014/02/servicebinder.html</link>
         <description>&lt;p&gt;I've released ServiceBinder 0.2 to Maven Central (details below; soon to be 0.3 with more documentation).  I wrote this to fix a common problem for my projects.&lt;/p&gt; &lt;p&gt;I like using the JDK &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html&quot;&gt;&lt;code&gt;ServiceLoader&lt;/code&gt;&lt;/a&gt; for discovery: it is simple to use and understand and always available.  And Kawaguchi's &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;http://metainf-services.kohsuke.org/&quot;&gt;META-INF/services generator&lt;/a&gt; makes use as simple as an annotation.&lt;/p&gt; &lt;p&gt;However, &lt;code&gt;ServiceLoader&lt;/code&gt; is missing one key feature for me.  It requires a default constructor for implementations, and I am a fan of constructor injection.&lt;/p&gt; &lt;p&gt;ServiceBinder fills this gap.  It discovers service classes as ServiceLoader does, and injects them with Guice or Spring.  See &lt;a rel=&quot;nofollow&quot; target=&quot;_blank&quot; href=&quot;https://github.com/binkley/service-binder&quot;&gt;the GitHub site&lt;/a&gt; for examples and source.  A taste:&lt;/p&gt; &lt;h3&gt;Guice&lt;/h3&gt; &lt;pre class=&quot;code&quot;&gt;public final class SampleModule
        extends AbstractModule {
    @Override
    protected void configure() {
        ServiceBinder.with(binder()).bind(Bob.class);
    }
}&lt;/pre&gt; &lt;h3&gt;Spring Framework&lt;/h3&gt; &lt;pre class=&quot;code&quot;&gt;AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
ServiceBinder.with(context).bind(Bob.class);
context.refresh();&lt;/pre&gt;</description>
         <author>Brian Oxley</author>
         <guid isPermaLink="false">tag:blogger.com,1999:blog-5638372.post-2171564233873202905</guid>
         <pubDate>Sat, 08 Feb 2014 10:43:00 +0000</pubDate>
      </item>
   </channel>
</rss>
<!-- fe8.yql.bf1.yahoo.com compressed/chunked Thu Oct  1 15:52:02 UTC 2015 -->
