Tech Per

25 Jun

Tip: Debugging JAXP Internals

In my latest battle with JAXP and Schema validation, I found out a little trick. It turns out, that implementation classes in JAXP use a debug flag to control stdout debugging. And this little flag is initialized from the system property jaxp.debug

So, starting your program, application server, … with -Djaxp.debug=true enables all sorts of initialization/bootstrap debug information, that can be helpful.

25 Jun

JAXP Schema Validation in Java5 and Java6

I have had a little battle with schema validation of XML documents and thought I would share it with the world.

I wrote the below code on Java5, thinking this was a way of validating a piece of XML against a schema definition. And indeed, it does work on Java5:


SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setSchema(sf.newSchema(schemaUrl));
DocumentBuilder parser = dbf.newDocumentBuilder();
parser.parse(new InputSource(new CharArrayReader(xml.toCharArray())));

Only thing is, this does not validate on Java6. In fact, if I install an ErrorHandler on the DocumentBuilder that simply rethrows exceptions, the parsing will complain about the very first attribute it meets, even though the Schema allows it.

It took me a while, to figure out what to do. In the process, I debugged into both Apache and the com.sun…apache packages, to try and find out what was different with parser behaviour on Java6. In the end, it proved really simple. I just hard to learn to actually use the javax.xml.validation API instead. An API made for, … validation. Duuh! Here is the code, that works on both Java5 and Java6:


SchemaFactory sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = sf.newSchema(schemaUrl);
Validator validator = schema.newValidator();
Source source = new StreamSource(new CharArrayReader(xml.toCharArray()));
validator.validate(source);
05 Jun

How To Acess Target Object Behind a Spring Proxy

When annotating spring managed beans with stuff like @Transactional, spring will behind the scenes produce code, that ensures that transaction logic is applied before and after your code. Depending on the configuration, this is often done using a JDK proxy, which is a dynamically generated class implementing the bean interfaces. This dynamically generated code will apply its logic and then dispatch the call on to what is called the “target object”, that is, the object that has been proxied.

But sometimes, it would be nice to have direct access to the instance behind the proxy. In my case, it was in a test case, where I wanted to inject one dependency out of many, with a stub implementation. I am using the spring AbstractJpaTests class, which will inject proxied dependencies of beans into my testcase. All the dependencies of the injected, proxied class has also been setup by spring from the context, but I would like to set one specific of them to a stub implementation.

Problem is, the setters for dependency injection is not on the bean interface, and as such, I cannot call them on the bean instance. I also cannot cast it to the implementation class, because in my case, spring is applying the aspect using a JDK proxy, hence it is not the the implementation type, only the interface type.

Here is the code I ended up with for getting the target object:


  @SuppressWarnings({"unchecked"})
  protected <T> T getTargetObject(Object proxy, Class<T> targetClass) throws Exception {
    if (AopUtils.isJdkDynamicProxy(proxy)) {
      return (T) ((Advised)proxy).getTargetSource().getTarget();
    } else {
      return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
    }
  }

I found out (by debugger inspection), that the proxy class that spring generates implements Advised, which contains the getTargetSource() method. And on a TargetSource, one can get the actual target. I am not sure if all spring proxies always implement Advised, but it seems to do in my code :-)

I am using the code like this:


  @Override
  protected void onSetUp() throws Exception {
    getTargetObject(fooBean, FooBeanImpl.class).setBarRepository(new MyStubBarRepository());
  }

One question: The targetClass parameter on the above getTargetObject method is not used within the method itself. But I cannot find another good way to pass the type paramter into the method. Can you?

Another question: Are there any other good ways, from a test, to inject one dependency on a spring managed bean?

18 May

Auto-Grabbing Dependencies with Groovy Scripts

Now here’s something cool for your once-in-while, small, groovy sysadmin scripts…

When you write a groovy script, chances are that, when it gets just a little bigger than damn-small, it will require some third party dependencies, to be able to run properly. So, what do you do? You end up either a) package dependent jars in a lib folder and dist as a zip with a script that can build a classpath or, b) re-package all dependencies into one big runnable jar including both dependencies and your not so little script anymore.

But now, there’s “Grab” :-)


@Grab(group='com.ancientprogramming.fixedformat4j', module='fixedformat4j', version='1.2.2')
class Grabber {
  Grabber() {
    println "Code that is supposed to use fixedformat4j"
  }
}
new Grabber()

The “Grabber” class above is an example of a class, which is pretending it needs fixedformat4j in its classpath. When compiled, the groovy compiler will add code to lookup and download the dependencies from some repository (maven, ivy). When run, this generated code is executed, dependencies located and downloaded (if needed), and your script is then executed with access to the downloaded classes/jars.

After trying it out, a little digging around made me discover, that the downloaded dependencies end up in $HOME/.groovy/grapes

Cool?

18 May

Compile Time Meta Programming in Groovy

Today at gr8conf–which by the way is a grait conference–I heard Guillaume LaForge, talk about the new stuff in groovy 1.6. One of those being AST transformations or what they call compile time meta programming.

Through annotations, one is able to tell the compiler to change the code, before it is producing actual byte-code output from the AST. One example is the ever present Singleton “pattern”, which is implemented as an annotation, like this:


@Singleton
public class SingletonTest {
}
new SingletonTest()

When run, this code will produce an exception at runtime, like this:


Caught: java.lang.RuntimeException: Can't instantiate singleton SingletonTest. Use SingletonTest.instance
  at SingletonTest.<init>(SingletonMain.groovy)
  at SingletonMain.run(SingletonMain.groovy:4)

What happens here is, that the compiler is producing a singleton from SingletonTest, putting a property “instance” on the class, at compile-time.

I guess stuff like this are making the job even harder for IDE developers. Not only do they not get as much type information to work with as with statically typed languages, but also shall they know about meta-programming like this, that changes the code when compiled. The code above does not color red in IDEA (yet).

14 May

Open RAWs from iPhoto in External Editor

I finally got my Adobe Photoshop Elements for Mac and of course jumped right into iPhoto to try and open an image in the great Camera Raw converter.

First thing to do was to go into iPhoto preferences “General” and set Photoshop Elements as the external editor program. Nice and easy. I then tried to open my photos in external editor and sure enough, photoshop elements opened up, … with the JPEG image :-(

Here is the tip: You need to set the “Use RAW when using external editor” inside iPhoto preferences “Advanced”. Like this pictures shows:

Only thing I need now, is to find out how to make iPhoto notice the edits in Photoshop Elements when I come back. Anyone know how to do that?

28 Apr

Oracle, WebLogic and “The Network Adapter could not establish the connection”

Today I battled a periodic error, where my development WebLogic would not start, due to connection problems against the database. It was kinda strange, because other Java tools like DbVisualizer had no trouble. The exception:

Error starting JDBC transaction. Cause: java.sql.SQLException: Io-exeption: The Network Adapter could not establish the connection.

..turned out to lead me in the wrong direction.

I have had these kind of exceptions before, saying “The Network Adapter could not establish the connection”, and it has always been a problem of network connectivity. But this time, it was due to a driver misconfiguration. Or at least, an update of the ojdbc14.jar inside weblogic lib directory made the problem go away.

I do not know which version of ojdbc14.jar that came with my weblogic 8.1, but I dropped a v10.2.0.2.0 there, and it worked.

27 Apr

Flex DataGrid and Image as ItemRenderer

Just a quick note or advice.

When using the Image component as a drop-in item renderer in a Flex DataGrid, there are things to remember or know about sizing. You can give the individual columns a width setting of their own, but the row height is a little different:

  • either (a) set rowHeight of the grid, which will render all rows same height no matter the dimensions of the images…
  • or, (b) set variableRowHeight to true, in which can the dimensions of the images will determine the height of each individual row
04 Apr

IDEA Is Back to Being Great!

Some time ago, I got frustrated with working with IDEA flex support. I had some complaints about the quality of the flex support in IDEA7 and 8, and I let the steam come out in that blog entry.

Well, just to be fair, I thought I would post a short blog entry about how things have changed.

Since then, many of the issues I and others have reported in the IDEA Feedback Jira have been solved, sometimes within hours of them being reported. Currently, I am really enjoying Flex development using IDEA, and I am doing it day in and day out.

What is really nice is, that when I am not doing Flex code, I am doing backend code for the Flex client. And that code is Java. And IDEA never left being the greatest IDE for Java development. Now, it is also great for Flex.

Sincerely, an IDEA fan boy! :-)

04 Apr

Where is that damn oblique arrow on my Mac?

Here’s a question for the reader: When using IDEA on my MacBook Pro, I cannot find the key combination to “goto end of file” or “goto top of file”. It used to be Ctrl-End or Home on PC, as far as I remember. But, MacBook Pro users do not need Home and End keys, … or so it seems.

So, I went into IDEA settings for keyboard bindings and found what the picture below shows:

IDEA Keymap settings

First thing: I assume, that “Move Caret to Text End” is what I want, as in, other words for “goto file end”. Am I right?

Next thing: What the heck is that oblique arrow doing in the shortcut :-) I looked hard but could not find it on my MacBook Pro keyboard:

I then got to looking on the external keyboard for the mac of a colleague of mine, and spotted the keys on that keyboard, like here:

Is there any way for me to emulate these keybindings on my MacBook Pro, using some kind of weird and hard to remember combination of shift, fn, ctrl, option, arrows, command key or something completely different like a secret trackpad gesture?

© 2009 Tech Per | Entries (RSS) and Comments (RSS)

GPS Reviews and news from GPS Gazettewordpress logo