Friday, November 30, 2012

WebPageTest

Ryan Hurst posts How Facebook can avoid losing $100M in revenue when they switch to always-on SSL, an interesting discussion of web page performance when using SSL.

What I noticed: WebPageTest, a fantastic resource for tuning public web pages courtesy AOL, Google & others. WebPageTest can also be downloaded, for testing your internal web site.

Sunday, November 25, 2012

Monday, November 19, 2012

Alternative to Java 8 virtual extension methods

Tired of waiting for Java 8? Project Lombok brings a little piece to you today, virtual extension methods similar to those proposed for JDK8. The most interesting bit: Lombok works using only JDK annotation processors and no required run-time library.

JUnit testing that a call blocks

Certain that I missed an existing solution, I post this in hopes of helping anyone who also misses it. But if you know a better way, please comment.

Usage

class SomeTest {
    @Test(timeout = 1000L)
    public void shouldBlock() {
        assertBlocks(new BlockingCall() {
            @Override
            public void call()
                    throws InterruptedException {
                // My blocking code here
            }
        });
    }
}

Implementation

import javax.annotation.Nonnull;
import java.util.Timer;
import java.util.TimerTask;

import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static org.junit.Assert.fail;

/**
 * {@code BlockingCall} supports blocking call assertion for JUnit tests.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public interface BlockingCall {
    /**
     * Calls blocking code.  The blocking code must throw {@code
     * InterruptedException} when its current thread is interrupted.
     *
     * @throws InterruptedException if interrupted.
     */
    void call()
            throws InterruptedException;

    /** Wrapper class for block assertion. */
    public static final class Assert {
        /**
         * Asserts the given <var>code</var> blocks at least 100ms.  Interrupts
         * the blocking code after 100ms and checks {@code InterruptedException}
         * was thrown.  When not blocking, appends <var>block</var> to the
         * failure message.
         *
         * @param block the blocking call, never missing
         */
        public static void assertBlocks(@Nonnull final BlockingCall block) {
            final Timer timer = new Timer(true);
            try {
                final Thread current = currentThread();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        current.interrupt();
                    }
                }, 100L);
                block.call();
                fail(format("Did not block: %s", block));
            } catch (final InterruptedException ignored) {
            } finally {
                timer.cancel();
            }
        }
    }
}

UPDATE: Idioms like this would be far more attractive with Java 8 lambdas:

public void shouldBlock() {
    assertBlocks(() -> { /* blocking code */ });
}

Friday, November 09, 2012

Python's enumerate for Java

Surprisingly I did not find Python's enumerate in Guava Iterables.

A little static import and all is well:

import com.google.common.collect.UnmodifiableIterator;

import javax.annotation.Nonnull;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * {@code EnumerateIterable} wraps an iterable like Python {@code enumerate}.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public final class EnumerateIterable<T>
        implements Iterable<Entry<Integer, T>> {
    @Nonnull
    private final Iterable<T> delegate;

    public EnumerateIterable(@Nonnull final Iterable<T> delegate) {
        this.delegate = delegate;
    }

    /**
     * Creates a new enumerated iterable for the given <var>delegate</var>.
     *
     * @param delegate the underlying iterable, never missing
     * @param <T> the underlying wrapped type
     *
     * @return the new enumerated iterable, never missing
     */
    @Nonnull
    public static <T> Iterable<Entry<Integer, T>> enumerate(@Nonnull final Iterable<T> delegate) {
        return new EnumerateIterable<>(delegate);
    }

    @Nonnull
    @Override
    public Iterator<Entry<Integer, T>> iterator() {
        return new EnumerateIterator<>(delegate);
    }

    private static final class EnumerateIterator<T>
            extends UnmodifiableIterator<Entry<Integer, T>> {
        @Nonnull
        private final Iterator<T> it;
        int i;

        EnumerateIterator(@Nonnull final Iterable<T> delegate) {
            it = delegate.iterator();
            i = 0;
        }

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        @Nonnull
        public Entry<Integer, T> next() {
            return new SimpleImmutableEntry<>(i++, it.next());
        }
    }
}

UPDATE: Completeness requires a static factory method for arrays as well as iterables.

ISO8601 UTC with XStream

I need ISO8601 conversion with XStream for UTC (GMT/Zulu) time. Originally I went with ISO8601DateConverter which comes with XStream and uses Joda. However I found that it read in UTC (GMT/Zulu) time but wrote back out local time.

To fix this I wrote my own converter using JAXB in the JDK, and dropped the Joda runtime dependency from my project.

I unit tested full roundtrip with "2012-10-22T12:34:56Z". The original converter parsed correctly but serialized as "2012-10-22T07:34:56-05:00". My converter serializes as the input string.

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

import java.util.Date;
import java.util.GregorianCalendar;

import static java.util.TimeZone.getTimeZone;
import static javax.xml.bind.DatatypeConverter.parseDateTime;
import static javax.xml.bind.DatatypeConverter.printDateTime;

/**
 * {@code UTCConverter} converts {@code java.util.Date} objects in ISO8601
 * format for UTC without milliseconds.
 *
 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
 */
public final class UTCConverter
        extends AbstractSingleValueConverter {
    @Override
    public boolean canConvert(final Class type) {
        return Date.class.isAssignableFrom(type);
    }

    @Override
    public String toString(final Object obj) {
        final GregorianCalendar gmt = new GregorianCalendar(getTimeZone("GMT"));
        gmt.setTime(Date.class.cast(obj));
        return printDateTime(gmt);
    }

    @Override
    public Object fromString(final String str) {
        return parseDateTime(str).getTime();
    }
}