Sunday, March 23, 2014

Scala Play Framework Template Imports

The template compiler is pretty sweet. Using a template like a function is awesomely simple.  If you have a bit of html code that makes up a reused block on more than one page you just factor it out to it's own ___.scala.html. Then reference it with the "magical" @ character.

However, the error messages that the template engine provides are less-than-detailed. I had created a subdirectory named: app/views/tags. When I tried to use one of the template functions out of that directory I got the error: not found: value gallery

So let's take a look at the important parts.

I have templates:

  • app/views/main.scala.html
  • app/views/tags/gallery.scala.html
With this as the important parts of main.scala.html

@(artist: models.ArtistModel,
      tags: List[String])(implicit artistModel: Option[models.ArtistModel]) @import tags._
.....
...
@gallery()....
Hmmmm, "not found: value gallery"? Why can't it find gallery? I imported it. It's formed correctly. Well, this is painfully obvious now, but it took a few minutes for me to reconcile that the "tags: List[String]" is clashing with the "@import tags._" 

More on the Play Framework Templates

Saturday, February 23, 2013

Are You Following the Golden Rule?

Well, are you? I'm often asking my sons that exact question. The Golden Rule: Treat others the way you want to be treated. Pretty simple. No room for interpretation. I may have heard it growing up. I don't remember. The Golden Rule was core to the culture at (the company formerly known as) A.G. Edwards & Sons. Ben Edwards often referenced it in his monthly news letters as he visited branches. Mr. Edwards would inevitably digress to how the food tasted and how that branch was following the golden rule. But now I digress.

It occurred to me the other day that The Golden Rule should not just be about how you treat other people. But how you think about other people. To my sons (11 and 8 at this time) this applies to knowing without hesitation that there is no need to say, "Stephen, don't break it!" But as software developers, we should remind ourselves, "This crap code I'm looking at, well, I'm sure the person who wrote it had good intentions and isn't just an idiot." Because remember, the crap code you're looking at just might be your own.

Tuesday, October 2, 2012

Logging Configuration for Testing

I realized this morning that putting the name of the test in the logging frameworks (log4j/slf4j) Mapped Diagnostic Context (MDC) gives great context to every logging statement. I'm not sure why I didn't do this before. Well, I've always had a different log4j (and now slf4j) configuration file sitting in src/test/java to change the level of local classes while executing tests. This configuration almost always goes to the console where the main code will log to a file.
This example uses log4j but slf4j has the same MDC class.
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender class="org.apache.log4j.ConsoleAppender" name="console">
    <param name="Target" value="System.out" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{ISO8601} %X{testMethod} %-5p %c - %m%n" />;
    </layout>
  </appender>
  <root>
    <priority value="debug" />
    <appender ref="console" />
  </root>
</log4j:configuration>
Then, in Java, you'll need a custom TestWatchman that uses the same string 'testmethod' as seen above inside the french braces %X{testMethod}):
/**
 * This helpfull little thing works in concert with the log4j configuration.
 * There are two steps to it's use:
 * <ol>
 * <li>declare a Rule in your test: @Rule public TestNameMDC testNameMDC = new TestNameMDC();</li>
 * <li>include the %X in the log4j pattern: %X{testMethod}</li>
 * </ol>
 * Note that the 'testMethod' in french braces above must match the {@link #MDC_KEY} defined here.
 *
 */
public class TestNameMDC extends TestWatchman {

  private static final String MDC_KEY = "testMethod";

  @Override public void starting(FrameworkMethod method) {
    MDC.put(MDC_KEY, method.getName());
  }
 
  @Override public void finished(FrameworkMethod method) {
    MDC.remove(MDC_KEY);
  }

  public String getMethodName() {
    return (String)MDC.get(MDC_KEY);
  } 
}

Tuesday, September 25, 2012

Scala on Play 2: List to Json Response

I've been writing some Scala. My first Scala app as a matter of fact. I looked at lift, I looked at play. I liked play better, so I'm learning Scala within the context of creating an application on the Play 2.0 framework.
So there's this problem. I have a list of objects, created via case class from the DTO layer. I want them returned from the Controller as Json. Oddly, the documentation on github does not give an example of this use case. I'm sure that if I were more versed in Scala, the solution would be obvious. If I were doing this in java, I would just for-loop over the list of case-class-instances to build a new list of Json. Or, I would annotate the case class (or DTO in java-speak) so that the Json layer would know how to json-ify each instance in the list.
What really surprises me is why doesn't the transformation happen automatically. Just create the Json for me. I don't really care what the names of the fields are in the json. Honestly, it's easier if the json uses the same field names.
But what's the Scala way?
Well, that documentation I liked to indicates that you need to
Json.toJson( Map )
Sure, that makes sense, I want the keys of the map to be the label and the value of the map is the value of the json field.
val jsonObject = Json.toJson(
  Map(
    "users" -> Seq(
      toJson(
        Map(
          "name" -> toJson("Bob"),
          "age" -> toJson(31),
          "email" -> toJson("bob@gmail.com")
        )
      ),
      toJson(
        Map(
          "name" -> toJson("Kiki"),
          "age" -> toJson(25),
          "email" -> JsNull
        )
      )
    )
  )
)
Being new to Scala, I have to scream WTF!? Why does the example show making up all the $%#!&@ data! How does that help put it into place? How can I utilize that? Oh, wait, I know. In that controller where I manufacture stupid data! OK, so after calming down, lets go try stackoverflow. I found this:http://stackoverflow.com/questions/8695335/how-to-render-json-response-in-play-framework-v2-0-latest-build-from-git
I was really expecting the answer to be a transformation. But no. This stackoverflow answer shows the solution as being an implicit object. Hmmm? I had not heard of those implicit objects.
implicit object BlahFormat extends Format[Blah] {...}

Friday, October 14, 2011

Import Self Signed Certs

Day three of using self signed certs and I was tired of telling chrome to accept it. Under the wrench menu there was an import certificate process. However, for Ubunutu, what it really needed was importing them into the OS keystore

First step, install the libnss3-tools:
sudo apt-get install libnss3-tools

There is a mention on that page linked above that says the cert needs to be imported as a CA due to a bug. On Natty Ubuntu it was not necessary. I put the following function in my .bashrc

function trustCert() {
[ $# -ne 2 ] && echo "you need to provide [certificate_nickname] and [certificate_filename]" && return 1
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n $1 -i $2
}

Friday, June 10, 2011

Gradle Dependencies

I was looking for the command to tell gradle to list the project dependencies (think maven dependency:tree). I came across this closed bug. Annoyingly that bug does not say how to actually output the listing.

Well, it's a command line option (run gradle --help) that was deprecated in favor of:
gradle dependencies

Tuesday, May 31, 2011

Architecting and Building A startup

This is not my usual flavor of posts in this space. However, it seems like a good place to mention that my users of Book Mobile have been feeling even more abandoned lately as I've left the corporate world to Architect and build a startup. Stealth mode requires that I say nothing about the startup or it's architecture.

Hopefully those Book Mobile users understand the nature of spare-time-projects and how that spare time ebbs and flows.