Happy New Year 2013!

Happy New year, of course! My last year was a bit poorer blog-wise. For some reasons I was more lazy to write about things. Heck, sometimes I think that I was less lucky with new technology in overall. I achieved some nice results with testing in our company during the previous year. This year I wanted to push Continuous Integration, testing a bit further, maybe Gradle – but results in CI area are mixed and the rest brought no real results at all.

On the brighter side, I managed to finish my quest for system time shifter on JVM that would be usable for testing purposes – all documented in my post. Blogging is not all of course and I am quite happy how topics around Clean Code got some attention around me. We pushed Java Simon project a bit further too, I learned a few interesting things around Spring, MVC and jQuery… Add this beautiful Scala class on Coursera and this year was more than fun after all.

Still I’d like to make some resolutions. I discovered QueryDSL (thanks to a colleague of mine) and this seems to be answer to readable and compile time safe Criteria – because those shipped with JPA2 are simply horrible to read. It works well with IDEA’s annotation processor, Maven and it should be no problem with Gradle either. Ah, Gradle! For around two years I’m watching this guy but for whatever reason I was not able to use it for anything more than a few tests – but that is not Gradle’s fault. I like it, I like the idea, I like the language – and I think this year is time to switch Java Simon from Maven to Gradle. And after that I’ll go on with projects in our company, although the battle there will be more difficult I guess.

Out of technology, I managed to put together a few songs with my colleagues and it was fun – the first time I played in something close to a band. We played only on our company party but it doesn’t change anything… it was a real fun. We didn’t have a drummer so I used my Native Instruments Maschine Mikro and pre-programmed our songs – and I was really happy with the results. I’ll probably dedicate a post to Maschine Mikro, because it is one really interesting controller (and software too!).


Maschine Mikro controller

Talking about music, I managed to upload two full-blown tracks to my Soundcloud and later added two simple guitar+voice tracks. While mixing/mastering is still my weakness, I’m happy that I was able to pull through this recording-wise. And just how I imagined – my songs composed with paper, pen and acoustic guitar many years ago can really work as rock recording too.

So what about this year and those resolutions? Gradle – sure. More testing methodology on our projects – maybe I’ll even manage to document it here on the blog. Pushing Continuous delivery just a bit further again. Scala or other JVM language? I don’t know. Maybe, maybe for tests. And a bit of my music – I need to practice more with keyboard, guitar and bass guitar (yeah, I bought lovely Yamaha bass too).


Bass guitar Yamaha RBX375

Last resolution is no resolution at all – we have to survive somehow “socialistic” experiments of our government here in Slovakia (although there is nothing social about them). Europe has its own deal of problems – and USA? Well they saved themselves from falling down that fiscal cliff or what – just a few hours ago. And it probably means to make the cliff a bit higher for the next time. So we might have escaped one Doom’s day lately at the end of 2012, but who knows how our civilization will fare in the future.

Then I remember those really poor and I know we have nothing really horrible to complain about. So once again – Happy New year – and whole year of 2013!

My last two years with technology

I’ve been quite busy lately – hence the pause in my blogging. My last post was very specific Java related article, today we’re going to do something lighter – a little whine about various devices, gizmos and maybe even software/services I’ve encountered during the last two years. While generally I love our age for the current level of technology, sometimes I’m desperate seeing unnecessary flaws, often just software ones – and these can seriously affect the final experience. However, today I decided to add a lot of good examples, too, and every case should be short (though I’m bad at keeping stuff short ;-) ).

BTW: Now I see that this is actually sort of continuation of this post.

Phone case: HTC One V

I like Android phones in general. And I like both my Wildfire and One V – however they both have quite funny flaws. Wildfire’s display is unresponsive when I pull it out of my pocket while ringing (that’s why I call back my friends right after I can’t pick them up) and One V – for a change – is very quite in-call. In both cases those are quite crucial phone related issues – and in both cases many people observe the same (but not all). Other than that – on Wildfire (2.x Android) I liked that default HTC clock application showed time of the next alarm and this view was removed from newer OS. Of course One V is faster and better in overall, but still… 3 out of 5 stars. Both.

Partition case: EASEUS Partition Master Home Edition

I wanted some free legal replacement for Partition Magic – and I found this. It may not be all-powered tool for every thing around partitions, but it did anything I wanted and so far never failed. Partitions smaller or bigger? Merge partitions? (Here it actually needs enough space on the partition you are going to merge to for all the files from the other partition – but that’s rather a non-issue.) System copied to my new SSD disk? No problem. Using Windows repair process took much longer after that. ;-) 5/5! For free? Yes!

Disc case: SSD drives (Crucial M4 in my case)

Talking about SSD – well, technically it is indeed non-disk, but you know how it goes. SSD generally is fast, of course, but also cheap enough nowadays – so to put there your system volume at least is a really good idea. I did so and my computer runs and starts programs much faster. This is currently probably the best boost you can get for your money. CPU or memory or GPU? Phew… SSD made my computer fleet-footed. I can’t say more really, I somehow decided one day, checked the prices, cross-referenced all the new names for me (like Crucial, never heard of them before!), reviews were good, so I bought this one. And I’m not even having SATA3 on my mobo. 5/5

Java case: Spring JdbcTemplate

When I can I program against standard APIs – like JPA2 instead of Hibernate. When I can. Sometimes you need to go through the select cursor-style and while I could use underlying Hibernate, I decided to go straight for JDBC. And I wrote all the code. With ifs and wheres and parameters. After a couple of hours, I was done, piece was tested and then it hit me! “Man, there is supposed to be that Spring class making it much easier!” JdbcTemplate made the job, I didn’t have to write my ifs twice (first to get the query, then the parameters again), all the exceptions were handled for me and there was even every case you could think about how to process the result set (in my case callback for every row of it). This is how I like stuff made. Documentation clear… actually I mostly just let IDEA to offer me the choices and I made them right there the right way thanks to proper names. Love that. 5/5

JavaScript case: File download plugin for jQuery

Check what this plugin is about – and also its demo. Users sometimes want silly things like “can you disable the button after I press download…” (sure I can!) “…and then after download enable it again?” (are you crazy?!) But you can do it with this plugin based on hidden iframe and a cookie. I had to adjust it a bit because I had a corner case (but quite common) that there were no data and no download, which is third case from user’s perspective in addition to success and (server) failure. I’m no JavaScript expert, on the contrary – but I fell in love with jQuery in the process. And however silly HTTP is for delivering applications, things like jQuery and this plugin make it more bearable (though HTML5 and things like WebSocket mend a lot of my 10-year old concerns). For this plugin and the whole idea – 5/5.

Command-line case: GNU tools for Windows – GnuWin

I never liked all that CygWin heavy-weighted stuff, but GnuWin packages made my day. I just installed them, added c:\Program Files (x86)\GnuWin\bin into my PATH (they all go to the same dir, luckily) and stared cmd just to enjoy grep (package grep), awk (gawk), ls (and many more in coreutils), zip/unzip/gzip/tar/bzip2 and of course sed! Mentioning typical Unix/Linux tools – you may also like (not related to GnuWin) vim, though I’m happy with notepad2 for most cases (read second half of this post). But you never know when you need vim’s macros. But yeah, these are not really command line tools in Windows. GnuWin packages definitely are and they deserve 5/5 for making my life easier.

Windows environment case: Rapid Environment Editor

After so many times heading into System, Advanced, bla-bla, setting the PATH in that super short line I realized “there must be a better way and someone must have already fixed this”. Yes, they have – with Rapid Environment Editor. Adding new paths with this tool is just so much better, it checks whether the path is valid – even with other variables you are referencing (if those are paths, like JAVA_HOME for instance). No more needs to be added: 5/5

Corporate tool case: Planview

For me Planview is just a tool to report my hours. I don’t use its powerful project management features. And every time I need some report out of it I don’t understand the language it is speaking to me. This tool one of those tools forgetting that they are not my only primary tools I use. Honestly, I openly hate it. Terms out of other world, a lot of misuses of the application (not only mine actually), tons of discussion how we should use it – and still we’re not using it the right way. Personally – I blame the tool. I can use Jira, Confluence and many other tools without any problem, but Planview is simply killing me. 1/5 (and yup, it’s IE only)

More-than-a-mail case: Lotus Notes

Lotus – I think this is love or hate thing, but however defended by people who like it, it is still viewed as pain by the vast majority of users. My Lotus for instance doesn’t display mouse cursor in mail editor when it’s not focused window, wrongly shows which tab is selected when two are opened at once, pastes Excel tables is as image by default and there are many other silly defaults. Date you see in trash is trash date, not the date of the message? You can’t reply to mail in your sent mail?! My contacts get often screwed by some cashing I don’t understand and don’t care at all. Not to mention it doesn’t look like normal Windows application (not that I’m a big fan of Windows, but still). Once a colleague closed Notes by accident and I just thought it funny to remark “see, stupid Lotus Notes” – just because whatever bad happens there is kinda Notes’ fault. I read people testifying how Notes rocks, etc. But these people live in the closed world of Lotus. Linux guys can hate Outlook, but it is really usable. Lotus? As a mail and calendar? Not a chance here… 2/5

Blu-ray case: Samsung BD-E6100

Recently I’ve got myself a blu-ray player (finally). I wanted Samsung, because my TV is Samsung, price was alright, I chose model with wi-fi, brought it home and after some initial scare (it didn’t play any disk first, I had to unplug it and after this kind of restart it was fine) I was happy about its performance, speed and everything, especially compared to our older DVD player (newer Philips luckily have remotes for common people too, not only for snipers). I managed to play content from computers (with Serviio installed, though SRT subtitles don’t work unexpectedly) and remote control provided four crucial buttons for TV (on/off, Source, volume up/down) – actually many of buttons from Samsung TV remote work as well (expected). After some time I decided to plug ethernet cable in though, because wi-fi often lost the connection to the router (our notebooks never have the problem, even from the same place). Even with ethernet most of the Smart HUB stuff is quite slow. In overall it was a big upgrade compared to DVD player and I was actually surprised how well it works and plays. And Smart stuff? They still might upgrade it somehow and I didn’t buy it for that anyway. 4/5

Conclusion

Not once I was thinking about myself as a “toiletologist”, because I just think too much about every single flaw of toilets as well. I never could understand why we – mankind – are unable to develop total toilet that always flushes everything, why we again and again put urinals so close together that you can use only 2 of 3 in the end, why we put toilet cubicles with legs on shiny reflective floor, not to mention various silly ways how to screw with automation of flushing, washing, drying or whatever.

Sometimes I want to scream “how could you do such a silly mistake?” But then I realize: “Man, it’s just software, it’s meant to be buggy (not that I agree that much :-) ), the whole computer science is so much younger compared to the building industry – and look what they are able to do in a silly way every now and then. Not only on toilets, but when these are still not ‘debugged’ after all those millennia then what should we expect from the software, hm?”

The more I am happy for technology that really helps and doesn’t “think” that it will be the only thing I need to pay attention to. I have my own real life beyond technology too, after all.

Changing system time in Java

I always wanted to find some reasonable way how to tell JVM “hey, it’s 3:47 AM, January the first, 2000″. When you have a need like this you probably use some DateFactory pattern. People argue – “that’s the cleanest way, put it into the design!” However this comes with a price:

  • This cleanest way means to pollute your code on many, many places with your DateFactory – one place where a programmer forgets and you’re screwed. No need to mention how difficult to trace these problems may be, though they are not difficult to locate when you find out what the problem is – because there is only one place where new Date() and/or System.currentTimeMillis() may appear – in your DateFactory class. (Now when I think of it, I’d probably come up with a technical solution to force this pattern, some Java language aware analysis tool searching for exactly these two calls.)
  • This DateFactory may or may not be dictated by the requirements – real, inherent ones, not derived from technical needs…
  • …actually, in many cases you need to shift time only because of the tests.

When the application somehow implies DateFactory solution, so be it. There surely are systems where it makes sense. In my line of work, however, I messed with some kind of the DateFactory only because of the need to test the system on a specific date, or (in rare cases) to run some highly administrative feature as if it ran on a specific date. While the second case could be just right for the DateFactory, it wasn’t part of our main application code, but rather our migration/preparation/installation utilities and they were never run by the user. So if I had known about any other solution than DateFactory, I’d have gladly welcomed it. I hadn’t then.

Every single time this situation occurred I cursed JVM creators for not adding unified standard way how to mess with system time (guarded by security manager just in case), or some “java” command option, or whatever. My need arises again and again – especially during testing. It’s much harder to prepare time aware data (you have to generate/customize them every time) then declare “you run at this time!” Unless the second thing is impossible of course. But imagine you need to test specific billing job running on New Year’s Day. “Go for the DateFactory you moron!” Yeah, but imagine you have system with @Past annotation from Bean Validation framework. Guess how that one uses your DateFactory? Finally I got the idea – to mock it somehow. Mocking such a thing though is messing with JVM to a degree – as you will see later. Now let’s follow the story as it went…

Solution: jmockit

Actually – I wasn’t the first one. I found that other people wanted to use jmockit library to mock the system time. Jmockit is surely powerful library, more powerful than I can tell, because I actually (sorry to say that) suck in mocking. If you mock System.currentTimeMillis, you’re done (new Date() and all other ways to get the real time use this call). But how to mock this system static native call? Jmockit can do it, and it does it on the side of the callee – which means you don’t need to modify anything else – just set up the mock on the side of System class. During some troubleshooting I tried to use different mock libraries and different approaches, but unless I’m mistaken there are only two ways how to do it – on the caller’s side – or on the callee’s one. Callee is the right side, right? The same way how you have to pollute your code with DateFactory call, you’d have to enumerate, autoscan or whatever else your code in order to mock it on the caller’s side. No way to do this simply and completely when you think about dynamic class loading too and I bet you can throw many other problems on this solution. So I reiterate: *Mock the system time on the callee’s side.* (That is System class, obviously.) Jmockit can do just that.

First we need the class “overriding” currentTimeMillis – here it is (it can be nested class BTW, that’s why it’s static on my listing):

import mockit.Mock;
import mockit.MockClass;
...
   @MockClass(realClass = System.class)
   public static class SystemMock {
       /**
        * Fake current time millis returns value modified by required offset.
        *
        * @return fake "current" millis
        */
       @Mock
       public static long currentTimeMillis() {
           return INIT_MILLIS + offset + millisSinceClassInit();
       }
   }

And now we will use this class:

import mockit.Mockit;
...
           Mockit.setUpMock(SystemMock.class);

Done! From now on all time is changed for the JVM. Or is it? This solution actually has two problems. Let’s deal with the problem numero uno:

Problem 1: you can’t call the original currentTimeMillis

How can you base your shifted time on the real time, when you don’t have the original time now? It would be nice if you just could set the offset and your method simply returned non-mocked millis + the offset. Jmockit can mock the call, but then it is not possible to call the original method without the mock – not for static native calls. So if you use it, you’ll run out of stack in recursion gone wild.

Luckily since Java 5 we have System.nanoTime(). While nanoTime itself is not based on any real world time, we can still use it to determine the time since we set up the mock – if we remember what were nanoTime and currentTimeMillis before we did so – and it can be any particular time, for instance class initialization time:

   private static final long INIT_MILLIS = System.currentTimeMillis();
   private static final long INIT_NANOS = System.nanoTime();

Now it’s easy to tell how might method called from my mock method look like:

   private static long millisSinceClassInit() {
       return (System.nanoTime() - INIT_NANOS) / 1000000;
   }

The only thing you need to do now is to set offset in some meaningful way. I offer my whole solution wrapped in a class straightforwardly called SystemTimeShifter:

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import mockit.Mock;
import mockit.MockClass;
import mockit.Mockit;

/**
 * Class changes the system time returned by {@link System#currentTimeMillis()} via JMockit weaving.
 * <p/>
 * Original System class can be restored any time calling {@link #reset()} method. There are a few ways how to specify modified system time:
 * <ul>
 * <li>setting ms offset via {@link #setOffset(long)}
 * <li>changing ms offset (relatively) via {@link #changeOffset(long)}
 * <li>setting new date, time or ISO date/time via {@link #setIsoDate(String)}
 * </ul>
 * <p/>
 * Any of these methods can be used through system properties (-D) this way (first property in this order is used, others ignored):
 * <ul>
 * <li>{@code -Dsystime.offset=1000} - shift by one second to the future (negative number can be used)
 * <li>{@code -Dsystime.millis=1000} - set system time one second after start of the era (1970...)
 * <li>{@code -Dsystime.iso=2000-01-01T00:00:47} - 47 seconds after beginning of the 2000, alternatively you can set only time (00:00:47, date stays current) or
 * only date (2000-01-01, current time) without 'T' in both cases.
 * </ul>
 * <p/>
 * There must be something that causes class load, otherwise nothing happens. In order to allow this without modifying the original program, one may use this
 * class as a main class with original main class as the first argument (they will be correctly shifted when served to the original class). If no relevant
 * property is specified via -D, nothing happens. In any case (programmatic or main class replacement) this class has to be on a classpath. For application
 * server usage this means it has to be in its system libraries, not in EAR/WAR that is not loaded during the AS start yet.
 * <p/>
 * Example:
 * 
 * <pre>
 * java -Dsystime.iso=2000-01-01T00:00:47 SystemTimeShifter my.uber.appserver.Main arg1 second "third long with spaces"
 * </pre>
 * <b>WARNING:</b> Sun/Oracle HotSpot JVM and its inline optimization may mess up with the mock after it is set up, so if you notice that the time
 * returns to normal after number of invocations, you should add {@code -XX:-Inline} option to your java command line. Other JVM specific options
 * may be needed for different JVM implementations.
 * 
 * @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a>
 */
public class SystemTimeShifter {
	/**
	 * System property setting ms offset.
	 */
	public static final String PROPERTY_OFFSET = "systime.offset";

	/**
	 * System property setting "current" millis.
	 */
	public static final String PROPERTY_MILLIS = "systime.millis";

	/**
	 * System property setting ISO date/time (or date, or time).
	 */
	public static final String PROPERTY_ISO_DATE = "systime.iso";

	private static final long INIT_MILLIS = System.currentTimeMillis();
	private static final long INIT_NANOS = System.nanoTime();
	private static long offset;

	private static boolean mockInstalled;

	@Deprecated
	protected SystemTimeShifter() {
		// prevents calls from subclass
		throw new UnsupportedOperationException();
	}

	static {
		String isoDate = System.getProperty(PROPERTY_ISO_DATE);
		String millis = System.getProperty(PROPERTY_MILLIS);
		String offset = System.getProperty(PROPERTY_OFFSET);
		try {
			if (isoDate != null) {
				setIsoDate(isoDate);
			} else if (millis != null) {
				setMillis(Integer.parseInt(millis));
			} else if (offset != null) {
				setOffset(Integer.parseInt(offset));
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Bootstrap main to allow time shifting before actually loading the real main class. Real
	 * main class must be the first argument, it will be removed from the list when calling the
	 * real class. Without using any relevant -D property there will be no time shifting.
	 * 
	 * @param args argument list with original (desired) class as the first argument
	 * @throws Exception may happen during the reflection call of the other main
	 */
	@SuppressWarnings({"unchecked", "rawtypes"})
	public static void main(String[] args) throws Exception {
		String[] newArgs = new String[args.length - 1];
		System.arraycopy(args, 1, newArgs, 0, args.length - 1);

		Class clazz = Class.forName(args[0]);
		Method main = clazz.getMethod("main", newArgs.getClass());
		main.invoke(null, (Object) newArgs);
	}

	/**
	 * Sets the new "system" time to specified ISO time. It is possible to set exact time with the format {@code yyyy-MM-dd'T'HH:mm:ss} (no apostrophes around T
	 * in the actual string!) or one can set just time
	 * (then current date stays) or just date (then current time stays).
	 * <p/>
	 * If parse fails for whatever reason, nothing is changed.
	 * 
	 * @param isoDate String with ISO date (date+time, date or just time)
	 */
	public static synchronized void setIsoDate(String isoDate) {
		try {
			if (isoDate.indexOf('T') != -1) { // it's date and time (so "classic" ISO timestamp)
				long wantedMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(isoDate).getTime();
				offset = wantedMillis - millisSinceClassInit() - INIT_MILLIS;
			} else if (isoDate.indexOf(':') != -1) { // it's just time we suppose
				Calendar calx = Calendar.getInstance();
				calx.setTime(new SimpleDateFormat("HH:mm:ss").parse(isoDate));

				Calendar cal = Calendar.getInstance();
				cal.set(Calendar.HOUR_OF_DAY, calx.get(Calendar.HOUR_OF_DAY));
				cal.set(Calendar.MINUTE, calx.get(Calendar.MINUTE));
				cal.set(Calendar.SECOND, calx.get(Calendar.SECOND));
				offset = cal.getTimeInMillis() - millisSinceClassInit() - INIT_MILLIS;
			} else { // it must be just date then!
				Calendar calx = Calendar.getInstance();
				calx.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(isoDate));

				Calendar cal = Calendar.getInstance();
				cal.set(Calendar.DAY_OF_MONTH, calx.get(Calendar.DAY_OF_MONTH));
				cal.set(Calendar.MONTH, calx.get(Calendar.MONTH));
				cal.set(Calendar.YEAR, calx.get(Calendar.YEAR));
				offset = cal.getTimeInMillis() - millisSinceClassInit() - INIT_MILLIS;
			}
			mockSystemClass();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Sets ms offset against current millis (not against real, instead changes current value relatively).
	 * 
	 * @param offset relative ms offset against "current" millis
	 */
	public static synchronized void changeOffset(long offset) {
		SystemTimeShifter.offset += offset;
		mockSystemClass();
	}

	/**
	 * Sets ms offset against real millis (rewrites previous value).
	 * 
	 * @param offset new absolute ms offset against real millis
	 */
	public static synchronized void setOffset(long offset) {
		SystemTimeShifter.offset = offset;
		mockSystemClass();
	}

	/**
	 * Sets current millis to the specified value.
	 * 
	 * @param timestamp new value of "current" millis
	 */
	public static synchronized void setMillis(long timestamp) {
		offset = timestamp - INIT_MILLIS;
		mockSystemClass();
	}

	/**
	 * Resets the whole System time shifter and removes all JMockit stuff. Real system call is restored.
	 */
	public static synchronized void reset() {
		Mockit.tearDownMocks(System.class);
		mockInstalled = false;
		offset = 0;
		System.out.println("Current time millis mock REMOVED");
	}

	private static void mockSystemClass() {
		if (!mockInstalled) {
			Mockit.setUpMock(SystemMock.class);
			System.out.println("Current time millis mock INSTALLED: " + new Date());
			mockInstalled = true;
		} else {
			System.out.println("Current time millis mock probably INSTALLED previously: " + new Date());
		}
	}

	public static boolean isMockInstalled() {
		return mockInstalled;
	}

	/**
	 * Handy if you set up the mock by some other means like {@link Mockit#setUpStartupMocks(Object...)}.
	 *
	 * @param mockInstalled true if you want to pretend that the mock is already in place (or is/will be installed otherwise)
	 */
	public static void setMockInstalled(boolean mockInstalled) {
		SystemTimeShifter.mockInstalled = mockInstalled;
	}

	/**
	 * Returns real time millis based on nano timer difference (not really a call to {@link System#currentTimeMillis()}.
	 * 
	 * @return real time millis as close as possible
	 */
	public static long currentRealTimeMillis() {
		return INIT_MILLIS + millisSinceClassInit();
	}

	private static long millisSinceClassInit() {
		return (System.nanoTime() - INIT_NANOS) / 1000000;
	}

	@MockClass(realClass = System.class)
	public static class SystemMock {
		/**
		 * Fake current time millis returns value modified by required offset.
		 *
		 * @return fake "current" millis
		 */
		@Mock
		public static long currentTimeMillis() {
			return INIT_MILLIS + offset + millisSinceClassInit();
		}
	}
}

I’m not suggesting it’s a masterpiece of engineering – but it works pretty well and you can set up the offset in many handy ways (just the date/time, both, offset in ms, you name it), you can use it as the main class before you start some other real main class (this way I started the whole application server in completely different time – Weblogic 12c in my case, but I think it doesn’t really matter). But I did mention two problems, right?

Problem 2: After some time the time returns to normal!

This problem quickly manifests on Sun’s JVM (can’t tell about others) and I found this non-solution:
http://code.google.com/p/jmockit/issues/detail?id=43

At least originally it was no-go for me as the suggested solution was -Xint – using interpreted JVM. This made tests unbearably slow, nobody would run them! I felt I’m pretty close to the solution and thanks to Rogerio Liesenfeld (jmockit author) and my private conversation with him above this issue I got pushed into the right direction. Sure, first I tried other mocking libs, but then I got back to jmockit (because it mocks the target, not the source of the call) and I tried again. I focused on what Rogerio wrote in his comment #7 (which was actually his reply to my mail). “So OK, if it’s HotSpot optimization, can’t I disable just that one? Even for that single class?” While I could not disable it for the class with Sun’s HotSpot (and I don’t know if it is any problem at all on different JVMs) I could disable it globally with -XX:-Inline. And yes, it’s much much faster than -Xint. Generally it should not be much slower than 1.5x of normal run with inlining – this depends on many factors of course (on overall “inline-likeness” of your application/test), but it’s much better than typical 10x penalty for interpreted JVM.

Problem 3: TestNG integration

Ok, I lied about two problems only – but only because this one is beyond the system time shifter itself. This problem was caused by my lack of understanding of jmockit and its interaction with TestNG. I wanted to shift my time for the whole TestNG suite without realizing that jmockit/TestNG may have their own agendas too. I tried to run my code with @Before/AfterSuite setting up my mocked time with SystemTimeShifter.setIsoDate(…) call and tearing it down again with reset(). But it didn’t work inside the test methods anyway, because something uninstalled my mock before the test method was run. Cedric from TestNG told me it’s jmockits business and Rogerio told me I’m using it the wrong way because it was never meant to be run this way for the whole Suite. I could use it around class or even method call, but I didn’t like the idea of time being shifted to the same point for every single method. I didn’t like the idea, that I can’t tell from log files how long the test is running (though the log file times were shifted too, I hope you don’t mind :-) ). Silly on my part, however, this should work for you just fine:

   @BeforeSuite
   public final void setupSystemTime() {
       SystemTimeShifter.setMockInstalled(true); // because of the setUpStartupMocks further, which sets up the mock
       SystemTimeShifter.setIsoDate("2011-10-14T10:00:00"); // this set's the offset - but doesn't set up the mock (thanks to the assert above)

       // this line performs all the suite scope magic
       Mockit.setUpStartupMocks(SystemTimeShifter.SystemMock.class);
   }

   @AfterSuite
   public final void resetSystemTime() {
       SystemTimeShifter.reset();
   }

While technically the AfterSuite part is not necessary, it is cleaner this way. Jmockit uninstalls his part by itself, but time shifter doesn’t know about it. This way it got reset as well.

Conclusion

There it is – not perfect and not without little hassles (-XX:-Inline namely), but working fine so far, at least for my cases. In my eyes – this is really tragic fault of the current JVM date library, fault that cannot be mended easily. System.currentTimeMillis is the only relevant source of real time and unless we can mess with it somehow in a clear way we will always have need to mess with it in ugly ways. This reminds me of the t-shirt I have. There is a stargate like ring on it, it is just named “TIME GATE” – and Java Duke comes out of it, opening the future for us. I’m curious a bit how he could do it. Did he cheat on JVM somehow too? When will we have clean solution that makes any DateFactory rather obsolete? Will we ever? Or do we have to unlock the future with TimeShifters in such obscure ways? Java, Java…

Let me know your story with system time cheating. I know I haven’t talked about setting the computer system time. That is simplest solution for many occasions, but not for running the tests on Continuous Integration server shared with many other projects, so I just omitted this altogether. If you have any success story with SystemTimeShifter, if it helps you somehow, please, be so kind and let me know to lift up my spirit. :-)

Live architecture with Java, Spring, JPA and OSIV

This post is about an architecture where live (attached) JPA objects are used in the presentation layer. You can expect OSIV (Open Session In View) pattern mentioned, though I’ll focus more on ways how we made it work well enough for us – safely and without LIEs (LazyInitializationException). It is just my story with my experiences, no big discovery here. :-)

I can’t tell if it is any official name, but we call it “Live architecture” because live JPA entities are available in the presentation layer. While we use it with Spring/Wicket mostly, it is the same with any other presentation framework – and probably applies to JavaEE without Spring too (if you use OSIV).

DTO vs Live architecture

In our company there are “DTO guys” and “live architecture guys”. We all know DTOs (Data Transfer Object) and how to work with them, more or less. Their rise to fame came with the need of coarse-grained calls to remote EJBs and they became prominent “pattern” then. Even with local calls people use them to strictly divide layers. I used them on some projects, then not on others and then again I used them with GWT/Seam applications (never liked the idea of JPA entities being preprocessed for me and dragged all the way to the GWT application).

Everytime I start talking about “live architecture” that drags entity objects into the view there are architects who just say “that is no architecture at all”. And I say “whatever…” I remember projects where we “broke” a clean architecture (e.g. “everything must go through this facade!”) and the result was less and cleaner code, easier to understand, better performance even. Was it universal? Hell no, it wouldn’t scale in most cases, but in that particular case scaling was not (and after all those years still is not) necessary.

My recent story with the live architecture is based on a project where it was settled that it will be used instead of DTOs. You have to translate DTOs somehow from business objects and back. You can generate it, you can automate it, use reflection – or do it manually. Any way always adds something that is not necessary for all cases. Our views were mostly based on JPA entities and it was just shame to translate them to DTOs for the sake of transformation itself. I’m not saying DTOs are bad – well we use them for more complicated views, mostly for lists showing joined tables. You can of course build a view and design an entity over it – and we do it too…

There is no fundamentalism in this – we use entities as much as we can. I strongly believe that in normal scope projects people often overdo it with “clean architecture” and don’t care about “clean code” as much. And I strongly believe that cleaner code itself matters much more than that cloud castle of architecture (without underestimating the architecture itself!). After all our projects are quite simple multi-tier applications with a bit of clustering. No grid, no hi-perf, no America. So we use entities, because they are placed under the presentation layer (good dependency direction) and they only carry data. And when this is not enough, we use DTOs too. Simple.

Business logic objects and dumb entities

You may have different rules for your live architecture (projects using OSIV) – and that is fine. Ours start with don’t use entities to anything else – no business logic, maybe some simple computed properties, that is alright. You may call this Anemic Domain Model – but I don’t care. Logic is in separated objects that use one or more entities. It is not exactly DCI, but it is not very far from this. For many other reasons (unrelated to the live architecture) I prefer having business logic objects that performs specific scenario – the best case is 1-to-1 mapping with a Use case from the analysis document.

Let’s talk about this picture for a while:

Presentation layer can be anything – component (Wicket) or controller (Web MVC) driven. It calls the service layer (typically a Spring bean or EJB) and this further uses that “cloud” with various business logic objects. Very often I prefer create/use/throw-away pattern. In constructor the object gets its context and then it does something – preferably in one method call, but it may be a sequence too, although this is more fragile approach. Important thing is that business object can store its state during the business logic execution – it is thread safe if it is created locally for one service call (that’s why I don’t use singletons here). Sometimes state is not necessary, but in more complex cases it is. And I like fields much more than dragging list of parameters between private methods.

This business logic uses DAOs (or @EntityManager directly) to work with the DB – and of course works with entities in the process. Because entities are dumb (DCI idea, but not only theirs) they are perfect DTOs (that are also dumb). Of course there are some concerns about entities used as DTOs and you can find many questions about this issue (and not only in the Java world). Entities are POJOs – in theory – but you may drag some proxy object up there into the presentation layer. There is a lot of magic in entities, you sometimes don’t know what they are (my class or some modified class already?) – but under the most circumstances you don’t have to care that much really.

Best practices

Now let’s talk about our best practices. Presentation layer code knows entities, but doesn’t know ORM! This is probably the most important thing. Of course the dependency on the JPA is implied somehow. Of course client programmer has to know the data model and has to know how to traverse the objects he wants to display. But he absolutely can’t use EntityManager. Our first “live architecture” project didn’t have clear separation of these roles and some LIEs were fixed like “you know, here in this page before you call the service… put evict on this object there”. I wasn’t there when this project started, so I just went like “what?!?!” And I forbade this for the next project I could affect.

Next rule is rather about the communication than the technical one – presentation programmer always has to know what he gets from the service call. Otherwise he risks that LIE again. But LIEs in presentation are easy. They are easy to fix in model, in service/business code or in the presentation code (that is the most of the cases). You always have to share some model between business logic and presentation (and developers!) – and we share the data model itself. If you don’t plan to change your layers this is perfectly acceptable. I’ve actually never saw any change of technology that would satisfy using different model introduced on the facade level. So why to do it if you ain’t gonna need it? (Of course, you may need it – and you are there to say as an architect.)

Getting data is easy (talking about live architecture problems only :-) ). You may need separate methods for every view – especially if selects are not generic enough. We have “filter beans” with single superclass and we use these beans with a few service methods (getSingleResult, getList, etc.) that are rather generic in nature. DAO-like even. It works for us, filter beans are the common ground for client and server programmer to communicate and they are part of the service layer API. We can have common FilterBean interface, because we use our custom filter framework behind. But you can use filter beans without common ancestor and have many service methods to obtain data. This is probably even cleaner.

Transactions, saves, updates

Originally we used DAO-like save on service layer too. We also didn’t have clear strategies when objects are alive and when not when the presentation layer called the service layer. If you had in one HTTP request read and write call, then the entities were alive if the write used result of the read. If you had just an update, then they were not. “Objects may come alive or not, let’s not assume that they are alive,” was our first strategy, though I didn’t feel very well about “or” used in the sentence. Never use contradictions in your assumptions. With a big help of our tests we managed to clean this mess up.

Our tests were TestNG based, they were not unit tests but mostly we tested the service layer playing the role of the presentation layer. It was funny how often the test passed and the user test (using browser) failed, but also vice-versa! Sometimes the test didn’t prepare the same environment – and we started to realize, that the service layer must assume less and be more strict. The biggest problem was that the presentation layer could change an entity A that was read in the request (hence alive) and then call service saving an entity B. The service layer had no chance to know about the A being saved in the same transaction. This lead to one very simple idea – we always clear session before calling transactional service methods. I forgot to say that we use transactions on service layer, so you can have more transactions in one HTTP request/persistence session.

Stepping back for a bit – client programmer knows that when he calls a service, his objects are alive. He can call multiple reads – and he knows that all things are still alive and he can base the next read on an attribute that is loaded lazily. In our case there is only one write/transaction called in one HTTP request – and it’s mostly the last call as well. If I wanted to make our policies even more precise I could say “always clear the session – for every service call”. This would mean less comfort for the client programmer. Or you can go for “dead” entities instead of live ones (see Other possibilities further).

Now the business programmer knows that any object that enters transactional service is detached and he can choose what to do with it. Do you need just to save the changes? Merge it (or call JPQL update, or whatever). Do you need to compare it to its original state? Read the object by its id and do what you need. Do you want to traverse its attributes? Well, better reload it first to make it attached again. We enforce this by a custom aspect that is hooked on an existing Spring @Transactional annotation.

This assumption would be very useful for read/list method too. Now the developer never knows if he has to reload or not. But read methods are not so complex and reload of the parameter entity should never harm either. Also – read/list methods are not transactional, so whatever he does, he can’t mess up with the persisted data. So this is our compromise between the client programmer using live objects and the service layer being secured enough. There is much less LIEs in our back-end code (which are harder to catch than those on the presentation layer) – actually I didn’t see one for a long time – and there is no chance to tamper with the data accidentally.

As a side note: Many of our problems were also caused by our presentation architecture – we load data, display them, then forget the content to keep page/session small and we just remember the IDs of the objects. When edit action comes, we reload the object from the service by its ID, modify it and then call the transactional write service method. To make this more convenient we have our custom ReloadableModel class for our Wicket pages, so before the model (entity obect) is to be updated, it is always reloaded from the service too (this is not a big performance hit, it often goes from the 2nd level cache anyway). This may not be very lucky solution but it was one of those we had to stick with for the time. You may or may not run into these kinds of problems. In any case, making your contracts and policies more strict and clean is always a good thing.

Other possibilities

There is not only Live vs DTO option. You can also use entities, yet always closing the session when the service call ends. This gives you the same model, less easy presentation changes, but it definitely is cleaner from the service layer point of view. You can make more strict contracts, performance is all down there and not ruined by lazy loads on the presentation layer, etc. I know this, we use this for other projects too. But I also know that people use OSIV a lot and that is why I wanted to wrap-up our experiences with it. You can come up with other policies too – for instance one read or write per request and nothing more. Do it all in one proper service call, don’t call many selects for every single combo-box model for instance. I agree with these approaches actually. But sometimes we don’t have the luxury of choice. :-)

In any case, try to do your best to clean up the contracts as much as possible, avoid contradictory ORs in your assumptions and – I didn’t focus on this point much in this post – test your service/business layer. Contract and policy is one thing, but you have to ensure them – force them, otherwise they are not contracts, just promises. Because that is your safety net not only from the architectural standpoint, but also from the functional one. But that is a completely different story.

Three years with Java Simon (4)

Today I’d like to cover the rest of my Java Simon story. In the previous posts we talked hardly about the start, but the rest was actually quite quick. With Callbacks, JMX support, JDBC proxy driver and much better design we were ready to release our 2.0 version.

June 23, 2009, Java Simon 2.0, monitoring API, released

There was one major problem with this version – we needed 2 different JDKs to build it. JDBC 3 would not compile against JDK 1.6 because Java 6 required higher version of it – which we didn’t want, so we could use it on application servers without support of newer JDBC. JMX 1.2 shipped with Java 5 – on the other hand – didn’t support features we needed, mostly around MX Beans, returning more types of objects and so on. So JMX was compiled with Java 6. You can imagine the problems we had when we started using Maven as a build (though Maven still is not exclusive build tool for us).

Well… Maven. While I like the idea of it – especially dependency management is truly great – as a build tool it is incredibly in the way unless you read tons of the stuff. Originally I hosted Java Simon on java.net repository, but then Oracle somehow made it more complicated (and malfunction altogether for a while if I recall correctly) and I decided to switch to Maven Central. That was right decision of course, but the pain behind it was just crazy. Unless you have the process mastered it takes a lot of pain to deploy your first software there. However – our clients wanted Maven repo – and I did my best to provide. I learned a lot in the process, but no one will convince me that Maven can’t be MUCH simpler. And deployment on Maven Central is just horribly bureaucratic compared to FTP upload. Guys at Sonatype do their best in support though, they probably have to answer tons of stupid questions (at least for them). After all I complained more about it previously, so let’s just skip the rest with saying that 2.5.0 version was the first on Maven Central – and someone else had to deploy it for me. 3.0.0 was delayed a lot – Maven being 95% of the reason. Now I can release (at least from that computer where release plugin doesn’t throw infamous out of bounds exception without providing reason…) and it is a tremendous relief.

Talking about 3.0.0 – release announcement was here:

Java Simon alive and kicking with 3.0.0 available

As you can read in it the biggest theme was aligning of the Java dependency – now we can build it with JDK 6 only. Aside from that it was rather just a wrap-up of all the changes in 2.x line with some bug fixes reported for 2.5. Talking about bugs and issues – this was maybe the reason why I kept working on Java Simon and eventually made all the changes that slowly but surely shape the library. And this would not be possible without users – and especially active users. Reports were coming more in bursts, often from one reporter for some time. One thing I can say with my head straight up – I was always very prompt to answer and fix where appropriate (mostly they were indeed bugs).

To talk to our users we created Java Simon Google Group shortly after version 1, but this was mostly an announcement tool. Here and there someone new asked the question though – and again, I answered as soon as possible. Luckily, Java Simon is low-profile library, so the traffic was rather negligible. To sum it up – users who had problems were my motor in the end. The main problem probably was that later we had no project to use with Java Simon. There seems to be some chance now at my current job, so I expect more enhancements.

Here and there I still change some method names (some changed in 3.1, next changes will appear in 3.2) – not that I like doing that but I rather name it properly later than never (oh, how I hate broken promises of original Java’s @deprecated!), but otherwise the core seems to be pretty stable for now. But there is still some room for improvements – especially new features:

  1. delivering more useful tools like JDBC proxy driver – that one I particularly like for its simplicity, just add “simon:” in the JDBC URL and have it on the classpath – right now monitoring part comes to my mind, charts, logging, dumps to some history DB, etc.;
  2. providing some neat Callbacks (many things from the point 1 are actually implemented thanks to these);
  3. web console where you can easily read your Simons.

Actually – there should be web console available in our next release (3.2.0) – we acquired new committer from among our users. That’s the true open source community story. :-) You can’t even imagine how happy I was about it.

Of course – my life is not only about Java Simon. I have a family, regular job where they’d hardly pay me for Java Simon alone, I like doing music (soon more about it too) and then I just don’t care about Simon for a few weeks, sometimes even months. Though right now I’m just taking a short break before we wrap up that 3.2.0 version – and you’ll hear about it.

Follow

Get every new post delivered to your Inbox.

Join 217 other followers

%d bloggers like this: