The intersection of technology and leadership

Category: Development (Page 6 of 18)

Adding toSortedSet on Seq in Scala

We recently wanted to do some transformation on our small XML document in order to present some information on it. In this example, our example looks like this:

<basket>
  <item cost=".99" discountCode="A5">Last year's red Christmas baubles</item>
  <item cost=".10" discountCode="A5">Halloween lamps</item>
  <item cost="101.99" >Pine Tree</item>
  <item cost="20" discountCode="B2">Gold star</item>
</basket>

It’s a pretty simple structure with some simple rules. A basket can contain one or more items. Each item has:

  • A simple description
  • A cost in dollars
  • An optional discount code

The task we had was to display a list of human-readable discounts that had been applied to this particular basket. In the example given about the discount codes are A5 and B2.

We have a very simple list of known discounts, and can implement a simple conversion function:

object Discounts {
  def displayString(code : String): String = {
    code match  {
      case "A5" => "Reduced to clear"
      case "B2" => "Pre-Christmas offer"
    }
  }
}

We already had a class that wrapped this small XML document, creating a cached field for the item nodes.

class Basket(val rootNode: Node) {
  private lazy val items = (rootNode \ "item");
}

We can then apply a series of functions to convert the items:

class Basket(val rootNode: Node) {
  private lazy val items = (rootNode \ "item");

  lazy val discountsApplied = 
    items.map(item => item.attribute("discountCode")
         .map(attribute => displayString(attribute.text)))
         .flatten
}

The above code pulls out all the “discountCode” attributes, and applies a conversion function to convert them to human-readable form. Since item.attribute returns an Option, we use flatten to get rid of elements that are essentially null.

Unfortunately, while there is a toSet method, and a list, there isn’t a great way to do both inbuilt. However, by constructing a TreeSet (a sorted set), we can append all the results and get the same effect. We end up with the following:

class Basket(val rootNode: Node) {
  private lazy val items = (rootNode \ "item");

  lazy val discountsApplied = sortedUniqueSet(
    items.map(item => item.attribute("discountCode")
         .map(attribute => displayString(attribute.text)))
         .flatten)

  private def sortedUniqueSet(sequence: Seq[String]) = {
    TreeSet.empty[String] ++ sequence
  }
}

Scripting web applications with cURL

I first used cURL on a project a few years ago whilst testing a RESTful applciation. It’s a really great tool and plenty of options to do things. I however, keep forgetting some of the simple commands you might use to interact with a RESTful, or even just a web application. This is really good if you want to test AJAX resources as well.

I’m putting the examples I’ve used the most up here for easy reference. You might even find it handy as well.

Perform a HTTP GET instead of POST

curl -G -F "formParamName=@fileToSendOnDisk.txt" http://localhost/someGetUri

Sending the contents of a file from disk as part of FORM data

curl -F "formParamName=@fileToSendOnDisk.txt" http://localhost/someUri

Note that the @ is very important here. You can use curl to give it content type as well.

curl -F "formParamName=@fileToSendOnDisk.json;type=text/json" http://localhost/someUri

Sending form post data as a single string

curl -d "param1=value1&param2=value2" http://localhost/someUri

Send some form post data and print the HTTP response code as the last row to the console

url -d "param1=value1&param2=value2" http://localhost/someUri -w "%{http_code}\n"

Post data to a HTTPs endpoint ignoring self-signed certificates

curl -d "param1=value1&param2=value2" https://localhost/someUri -k

Follow redirects, printing out response code and URL that was last fetched after posting data

curl -d "param1=value1&param2=value2" http://localhost/someUri -k -w "%{http_code}\n%{url_effective}\n" -L

Hope you find this useful although you can find a much larger manual in the man page, or on this site here.

Testing logging with Logback

On my current project, we’re using the logback framework (behind SL4J) to do logging. For some parts of our system, it was particularly important some information made their way into the log files, and so we wanted to not test the correct output. Rather than do it with interaction based tests, I followed the pattern that I described in a previous post.

Here’s a test I might write (note that I’m writing the test in a way to actually test the appender behaviour in this case because my domain class doesn’t nothing special):

package com.thekua.spikes;

import org.junit.After;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class LogbackCapturingAppenderTest {
    @After
    public void cleanUp() {
        LogbackCapturingAppender.Factory.cleanUp();
    }

    @Test
    public void shouldCaptureAGivenLog() throws Exception {
        // Given
        LogbackCapturingAppender capturing = LogbackCapturingAppender.Factory.weaveInto(OurDomainWithLogger.LOG);
        OurDomainWithLogger domainClass = new OurDomainWithLogger();

        // when
        domainClass.logThis("This should be logged");

        // then
        assertThat(capturing.getCapturedLogMessage(), is("This should be logged"));
    }

    @Test
    public void shouldNotCaptureAGiveLogAfterCleanUp() throws Exception {
        // Given
        LogbackCapturingAppender capturing = LogbackCapturingAppender.Factory.weaveInto(OurDomainWithLogger.LOG);
        OurDomainWithLogger domainClass = new OurDomainWithLogger();
        domainClass.logThis("This should be logged at info");
        LogbackCapturingAppender.Factory.cleanUp();

        // when
        domainClass.logThis("This should not be logged");

        // then
        assertThat(capturing.getCapturedLogMessage(), is("This should be logged at info"));
    }
}

And the corresponding Logback appender used in tests.

package com.thekua.spikes;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.AppenderBase;

import java.util.ArrayList;
import java.util.List;

public class LogbackCapturingAppender extends AppenderBase<ILoggingEvent> {
    public static class Factory {
        private static List<LogbackCapturingAppender> ALL = new ArrayList<LogbackCapturingAppender>();

        public static LogbackCapturingAppender weaveInto(org.slf4j.Logger sl4jLogger) {
            LogbackCapturingAppender appender = new LogbackCapturingAppender(sl4jLogger);
            ALL.add(appender);
            return appender;
        }

        public static void cleanUp() {
            for (LogbackCapturingAppender appender : ALL) {
                appender.cleanUp();
            }
        }
    }

    private final Logger logger;
    private ILoggingEvent captured;

    public LogbackCapturingAppender(org.slf4j.Logger sl4jLogger) {
        this.logger = (Logger) sl4jLogger;
        connect(logger);
        detachDefaultConsoleAppender();
    }

    private void detachDefaultConsoleAppender() {
        Logger rootLogger = getRootLogger();
        Appender<ILoggingEvent> consoleAppender = rootLogger.getAppender("console");
        rootLogger.detachAppender(consoleAppender);
    }

    private Logger getRootLogger() {
        return logger.getLoggerContext().getLogger("ROOT");
    }

    private void connect(Logger logger) {
        logger.setLevel(Level.ALL);
        logger.addAppender(this);
        this.start();
    }

    public String getCapturedLogMessage() {
        return captured.getMessage();
    }

    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        captured = iLoggingEvent;
    }

    private void cleanUp() {
        logger.detachAppender(this);

    }
}

I thought it’d be useful to share this and I’ve created a github project to host the code.

General testing approach for logging in Java

I’ve seen a number of different patterns for testing logging and we just ran into this again at work, so I thought it’d be worth writing up a couple of them.

Simple logging
Many of the java based logging frameworks allow you to log and then choose to separate what you log from what needs to be done by attaching appenders to them. The common pattern here is to declare a static log instance inside each class, typically using the fully qualified class name. Most logging frameworks then treat this as a hierarchy of loggers that allow you to configure what type of logging at different levels.

I find the best strategy for testing this style of logging is to add an in memory appender that will capture the output that is sent to the logging framework. I will post an example with given frameworks in a second, but here are a few different concerns you need to think about:

  • Getting a reference to the log – Most loggers are made private static. You can choose to break encapsulation slightly by weakening the access to package local just so that a test can get access to the log. I find that injecting it in as a dependency in the constructor appears to complicated, and dislike setter based dependency injection in an attempt to keep fields more immutable.
  • Creating an appender to capture the output – This is where you’ll have to go to whichever logging framework and find out how appenders work. Most have a console appender, or something that you can simply extend and capture a logging event
  • Make the appender capture the output – This is pretty easy. You must make a choice whether or not you want only your appender to capture the log events, or if you want it to go to other appenders as well.
  • Clean up – The consequence of adding an appender with state is not a problem in a single test. When wired up across a long test suite, you potentially increase the amount of memory being consumed to the point where you’ll get out of memory errors. I find that it’s important to make sure that your appenders remove themselves from the logger at the end of the test to avoid side effects and to make sure they get garbage collected by the JVM. In a following post, you’ll see the pattern I tend to use.

More complex logging services
If you’re application requires more than just file based logging, and other actions need to be performed, you may still consider injecting a type of logger into the class that uses it. At this point, testing it becomes like any other interaction-based test and you can probably use mocking or stubbing to test the correct things are passed to to it.

By default, I wouldn’t really go through the motions of setting up a logging service unless there was some real need for it. The standard style of loggers and configuration of behaviour gives you quite a lot already.

Converting Code to Images

I needed to convert some code into an image for a presentation recently and found a number of different ways of doing so. The easiest, of course, is when you take a screen capture of the code in your IDE. This fails when your code goes well past the side of your screen and you still want to show it all.

Alternatively, you can do this in a two step process.

  • Save the code to HTML – I know that both IntelliJ and NetBeans allow you to do this for Java code.
  • Use webkit to save to an image – I used PhantomJS for doing this. Take a look at the example code of how to do this.

Leave a comment if you’ve had any other good experiences doing this. I’d be interested in other ways that have worked for you.

String XML interpolation in Scala

In java, if you’re formatting a small XML document, it might be tempting to simply do a String.format to substitute it directly into a string. Transitioning into scala, this is then easy to convert into one of their XML representations with XML.loadString. You might very well end up with code that looks like this:

val myValue = "will be substituted"
val xml = XML.loadString(String.format("<node>%s</node>", node))

You can actually just do this inline with scala directly, and end up with this instead

val myValue = "will be substituted"
val xml = <node>{myValue}</node>

Neat-o!

RESTEasy could not find writer for content-type application/xml type…

I had been spiking around with RESTEasy in order to use some of the JAX-RS stuff for dealing with remote endpoints. We had a client library that already wrapped some of these end points and some DTOs that mapped to the XML the remote end point wanted. We wanted to use the JAX-B annotations to deal with the automatic conversions but kept getting the dreaded…

java.lang.RuntimeException: could not find writer for content-type application/xml type: [.... Dto]

The secret to getting this to work was to ensure that you have the correct runtime libraries in the classpath, or more specifically the following jar.

GroupID: org.jboss.resteasy
ArtifactID: resteasy-jaxb-provider

Thanks to this thread for the help on that.

Running Scalatra Tests with JUnit (in a maven or ant build)

I’ve been playing around with Scalatra and one of the things that wasn’t quite obvious was when I had it running as part of a test run build (using the JUnit) runner, these tests weren’t getting picked up.

The key to this was ensuring you annotate the class with the @RunWith(classOf[JUnitRunner]) attribute as part of the build.

package com.thekua.scala.example

import org.scalatra.test.scalatest.ScalatraFunSuite
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.junit.{JUnitRunner, JUnitSuite}
import org.junit.runner.RunWith

@RunWith(classOf[JUnitRunner])
class JsonScalatraTest extends ScalatraFunSuite with ShouldMatchers {
  val servletHolder = addServlet(classOf[JsonifiedServlet], &quot;/*&quot;)
  servletHolder.setInitOrder(1) // force load on startup

  test(&quot;JSON support test&quot;) {
    get(&quot;/&quot;) {
      status should equal (200)
    }
  }
}

Smooth Scala XML APIs

As an alternative to using JAXB for reading input, we thought we’d try simply wrapping an XML document in a class structure. XML is a first class citizen in scala, so we thought we’d have a look at what it would be. Note that we don’t expect very large XML documents (they all easily fit into memory) but the external structure is a little bit ugly.

We inject the XML document into the class via the constructor and then using scala X-Path equivalents, we pull out the interesting fields. I have to admit it’s better than dealing with XML xpath in the java world, and the code is pretty simple.

I’ve written an equivalent to give you an idea of what we evolved from.

Given we have an XML document that looks like this (domain made up here)

&lt;profile&gt;
  &lt;names&gt;
     &lt;defaultName&gt;Harry Potter&lt;/defaultName&gt;
     &lt;alternativeNames&gt;
        &lt;name&gt;Harry&lt;/name&gt;
        &lt;name&gt;Mr Potter&lt;/name&gt;
     &lt;/alternativeNames&gt;
  &lt;/names&gt;
  &lt;contact&gt;
     &lt;email&gt;harry.potter@hogwarts.com&lt;/email&gt;
     &lt;website&gt;http://hogwarts.com&lt;/website&gt;
     &lt;phone&gt;http://hogwarts.com&lt;/phone&gt;     
  &lt;/contact&gt;
&lt;/profile&gt;

We ended up with a class that looks like this

import xml.Node
class Profile (xml: Node) {
  def name = {
    (xml \ &quot;names&quot; \ &quot;defaultName&quot;).text
  }

  def email = {
    (xml \ &quot;contact&quot; \ &quot;email&quot;).text
  }

  def website = {
    (xml \ &quot;contact&quot; \ &quot;website&quot;).text
  }

  def phone = {
    (xml \ &quot;contact&quot; \ &quot;phone&quot;).text
  }
}

We can apply a couple of small refactorings here. Simple one line expressions do not need curly braces. The class now becomes:

import xml.Node
class Profile (xml: Node) {
  def name =  (xml \ &quot;names&quot; \ &quot;defaultName&quot;).text
  def email = (xml \ &quot;contact&quot; \ &quot;email&quot;).text
  def website = (xml \ &quot;contact&quot; \ &quot;website&quot;).text
  def phone = (xml \ &quot;contact&quot; \ &quot;phone&quot;).text
}

Maybe we also wanted to remove a little bit of duplication in the xpath. Though this increases the size of the class a bit:

import xml.Node
class Profile (xml: Node) {
  def name =  (xml \ &quot;names&quot; \ &quot;defaultName&quot;).text
  def email = (contact \ &quot;email&quot;).text
  def website = (contact \ &quot;website&quot;).text
  def phone = (contact \ &quot;phone&quot;).text

  private def contact = (xml \ &quot;contact&quot;)
}

Since our XML structure will now change, we also had some feedback that we could use the lazy val option to cache the results. The code now looks like this:

import xml.Node
class Profile (xml: Node) {
  lazy val name =  (xml \ &quot;names&quot; \ &quot;defaultName&quot;).text
  lazy val email = (contact \ &quot;email&quot;).text
  lazy val website = (contact \ &quot;website&quot;).text
  lazy val phone = (contact \ &quot;phone&quot;).text

  lazy val contact = (xml \ &quot;contact&quot;)
}

I’m not so sure if the last two refactorings give much more than the second refactoring, but it certainly helped me learn a a bit more scala. I think we had some pretty good wins by dealing with XML the scala way. Our tests are very readable because you don’t have weird string concatenation or sucking in XML from a file to test it, and I think the code is quite readable. I would have preferred closer XPath-y syntax, but I guess learning the scala XML syntax for traversing XML isn’t too bad. The other good thing about this is that you don’t have to worry about null or non existant nodes – you simply get back an empty string. Pretty decent default behaviour for at least our use case.

We do “TDD.” Oh really?

During Agile 2011 I tried to speak to people about what technical practices they did, and to what degree as well. Unfortunately I left the conference slightly disappointed and now understand why Uncle Bob champions the Software Craftsmanship movement as a way of addressing a balance the agile community at large has lost.

Don’t get me wrong. I appreciate that we need to focus on people and system issues in software development just as well. However, it’s laughable to think that software development is the easy part. I’m not the only one who feels this way. In order to succeed at real agility, you need just as much discipline and attention to detail to the technical practices, tools and methods just as you do everything else. It seemed like people were trying to be a good sports team, by finding the best people, hiring the best coaches, and then forgetting to schedule time for the drills and training.

One particular conversation stuck with me. We had this in the airport lounge at Salt Lake City before departing for Chicago. It kind of went something like this:

Other: We only tend to TDD the happy path
Me: Oh? Out of interest, what sort of test coverage do you end up with?
Other: About 20 or 30%. Why, how about you?
Me: Depends on what sort of application. Adding up the different types of tests (unit, integration, acceptance), I’d probably guess in the high 80s to 90s.
Other: Wow. That’s really high.

This conversation got me thinking about whether the other person’s team really benefits from doing TDD. I’m guessing not. They are probably getting some value from the tests, but probably equal value by doing test after. If you really wanted to be a pedant, you could argue, how do you do TDD without actually driving (most of) the code with tests? I’m not a TDD zealot. I’ve even blogged about when to skip TDD, however one of the biggest benefits of writing tests is the feedback they give and the way that it changes the way that you design code. I’m guessing by skipping the “unhappy paths”, there’s plenty of feedback they miss out on.

« Older posts Newer posts »

© 2024 patkua@work

Theme by Anders NorenUp ↑