Thursday, 9 August 2012

Spring @Autowired and the new operator

So there I was happily shooting the breeze and added @Autowired to things like it was going out of fashion.  But I then added it to a normal bean, which I was creating using the new operator in a RowMapper. Something like this
private static final class MyBeanMapper implements RowMapper {

  @Override
  public CapSumLineBean mapRow(ResultSet resultSet, int rowNum) throws SQLException {

    MyBean myBean = new MyBean();
    myBean.setParam1(resultSet.getString("param1"));
    myBean.setParam1(resultSet.getString("param1"));
    return myBean;
  }
}
And MyBean looks something like
public class MyBean implements Serializable
{
    /** The Constant serialVersionUID. */ private static final long serialVersionUID = 2292124910377623287L;
    @Autowired private transient SomeUtil someUtil;
    private String param1;
    private String param2;
    public String getParam1
    {
        return someUtil.doSomething(this.param1);
    }
    public void setParam1(String param1)
    {
        this.param1 = param1;
    }
    public String getParam2
    {
        return this.param2;
    }
    public void setParam2(String param2)
    {
        this.param2 = param2;
    }
}
So when you call getParam1 you will get a NullPointerException because the @Autowired didn't do anything.  It didn't do anything because this bean was created by me and not Spring and for @Autowired or any of its mates to work the bean must be Spring managed which something created by the new operator generally isn't.

Getting MyBean Spring Managed

So 'simple' solution, make the bean one that's managed by Spring.  A bit of googling and  I could create a factory class to produce these objects and tie that factory into Spring so the beans produced are Spring managed.  That seems clunky to me at the time, it may be the best approach as I started down the rabbit hole with the next bit.

It's easy just use @Configurable

Found this
 http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-atconfigurable
Add an annotation and some config and Spring will catch the new operator operation and do it's magic, or something like that general Aspect Voodoo happens anyway.

Right.... it's never that easy I added @Configurable to MyBean and added
<context:spring-configured/> to my root-context.xml and I get the error
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect 


Time to check the dependencies I already had

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>${org.aspectj-version}</version>
</dependency>
<dependency>
  <groupId>cglib</groupId>
  <artifactId>cglib</artifactId>
  <version>${cglib.version}</version>
</dependency>
 
Which brought in spring-aop So I added

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>${org.springframework-version}</version>
</dependency>


Which stopped the errors anyway
But still getting the NullPointerException
Found something which suggested adding in
<context:annotation-config />
Which did no harm but didn't solve anything
Next discovered was that @Configurable needs load time weaving, thought I had that I'm sure STS asked me about it, must have been compile time weaving?
Anyway I added in
<context:load-time-weaver/>
Which resulted in
Caused by: java.lang.IllegalStateException: ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar

Turns out Tomcat isn't that happy about load time weaving
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-aj-ltw-environments
I got the jar from
http://mvnrepository.com/artifact/org.springframework/spring-instrument-tomcat
And added it into $CATALINA_HOME/lib
I went blunderbuss and added
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader" />

to the Servers context.xml
Which lead to the error
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context 

Well time to throw more dependencies at this so
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>${org.aspectj-version}</version>
</dependency>

And it works!

Conclusion

Once setup with the dependencies and config elements @Configurable should just work like the rest of the magic annotations all be it there's more Aspect Voodoo going on.  All in all it might be worth considering the factory option but this should be cleaner... I probably need to revisit the config and take out what's not needed and I just started adding things in to try get it to work.

Thursday, 3 May 2012

Get prettify to behave in Firefox

Force wrap of long lines in Firefox

So having got Google code prettify working on blogger and being quite happy with myself I was testing it on Firefox bit of a habit I guess.  So all looked well on Chrome but on Firefox the long lines didn't wrap and extended beyond the prettyprint box and beyond the blogger page and even beyond the page for the compressed css I displayed.  This did not sit well with my OCD.
So I initially thought it was the theme I put on, there's no way the google css is wrong right... well sons-of-obsidian.css was totally innocent.
And I guess it's a bit harsh to say prettify.css is wrong.  As it's the pre tag that's the offender.
I guess it's a choice Blogger made to not wrap the pre tag even though it sure looks as ugly as sin when it over flows.  I would also have thought the prettify css would handle it as it's job is to make code look pretty.  When I knew the culprit is was handy to find some punter that solved the problem.

So back into the well worn path of Template --> Edit HTML in Blogger I added this to the head section

<style type='text/css'>
   pre {
      white-space: pre-wrap; /* css-3 */
      white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
      white-space: -pre-wrap; /* Opera 4-6 */
      white-space: -o-pre-wrap; /* Opera 7 */
      word-wrap: break-word; /* Internet Explorer 5.5+ */
    }
</style>

Things now look fine in Firefox and I can sleep tonight :)

Google Code Prettify - Add a Theme

Adding a theme to Google Code Prettify

So in my first post I got Google Code Prettify to work, happy days.  I wasn't happy with how it looked though.  Probably to do with the simple theme I picked so that might be changing in the near future.  But i know the prettify has themes so decided to add in one.


The Sons-Of-Obsidian looks like the one for me. So the theory should be to modify the instructions from my first post 
So went to Template --> Edit HTML and added this to the head section after your prettify.css entry

<link href="http://google-code-prettify.googlecode.com/svn/trunk/styles/sons-of-obsidian.css" rel="stylesheet" type="text/css"></link>

As an aside you can't just paste the likes of the html code above into the post, but that's another post.

So I thought this would work but it didn't.  I could see the entry in the html using Firebug and I could see it download the file but it didn't show up as a css for some reason.  Tried in chrome as well just to be sure and again the response body showed the file downloaded but blank in the css section.

So decided to get old school on it's ass and include it inline.
Rather than have all the spaces I ran the css through a compressor

I kept the comment header of course, the compressor will strip that

<style type='text/css'>
 /*
 * Derived from einaros&#39;s Sons of Obsidian theme at
 * http://studiostyl.es/schemes/son-of-obsidian by
 * Alex Ford of CodeTunnel:
 * http://CodeTunnel.com/blog/post/71/google-code-prettify-obsidian-theme
 */ 

.kwd{color:#93C763}.com{color:#66747B}.typ{color:#678CB1}.lit{color:#FACD22}.tag{color:#8AC763}.atn{color:#E0E2E4}.dec{color:purple}pre.prettyprint{border:0 solid #888}ol.linenums{margin-top:0;margin-bottom:0}.prettyprint{background:#000}li.L0,li.L1,li.L2,li.L3,li.L4,li.L5,li.L6,li.L7,li.L8,li.L9{color:#555;list-style-type:decimal}li.L1,li.L3,li.L5,li.L7,li.L9{background:#111}.str,.atv{color:#EC7600}.pun,.pln{color:#F1F2F3}@media print{.com{color:#600;font-style:italic}.typ{color:#404;font-weight:700}.lit{color:#044}.pun{color:#440}.pln{color:#000}.atn{color:#404}.str,.atv{color:#060}.kwd,.tag{color:#006;font-weight:700}}
</style>

And that worked, I now have pretty prettified code. 


Blogger Getting Started

Blogger Getting Started

So I decided to give this blogging thing a go.  Mainly so that when I figure out something I'll have a place to find it again and in theory should help me document the process of doing things etc...

So I decided to go with blogger, Wordpress is good of course but I have a Google account and sure it seems to offer more customisation... kind of.

So first order to business was code highlighting, I reckon I will be posting code so I want it to look pretty and be readable etc... So it turns out there are loads of options for this but two seem to stand out

SyntaxHighlighter
http://alexgorbatchev.com/SyntaxHighlighter/
Which sure seems to have alot of hits on Google

Google Code Prettify
http://code.google.com/p/google-code-prettify/
Used on Google code and stackoverflow it seems

So maybe because I'm used to seeing it on stackoverflow I think I'll try the google code prettify and sure it's another Google project so it'll be easy to integrate into Blogger right?

So how does random code look in normal mode

/**
 * @author David Kerwick
 * Created 3 May 2012
 */

public class HelloWorld {
    
    public void hi(){
        System.out.println("Hello Blogger");
    }
}
Not bad really, a bit dull though and as soon as the code got longer it would be hard to read.
I also had to get the HelloWorld in, it just won't feel right starting without it :)

So how to add the highlighting.  Like most things I'm way behind the curve so it was easy find other people who had added it.

Adding SyntaxHighlighter
Adding Google Code Prettify

So first roadblock, that sure didn't take long, I haven't even finished my first post!
The Edit HTML button they both speak of in the Template section is greyed out.
Turns out Dynamic Views don't allow the addition of third party scripts or css.
Bummer.

So you can do get it working
http://www.alexconrad.org/2011/12/highlight-code-with-bloggers-dynamic.html

But that's a bit of a hack I think, so Dynamic Views it was nice not to use you, time to switch to something else. Switched to a simple view and now this should work
/**
 * @author David Kerwick
 * Created 3 May 2012
 */

public class HelloWorld {
    
    public void hi(){
        System.out.println("Hello Blogger");
    }
}
Which it does, happy days all praise the Internet. It looks butt ugly now time to try figure out themes on prettify, another post perhaps