Converting Java enums to values and back – with Java 8!

Yeah, I know, I know – it seems just like yesterday when I talked about this topic. I focused mostly on conversion to values and back in the context of JPA 2.1 converters. This time we’ll focus on that part that helped us with “reverse resolution” – that is you have the value (for instance an int, but not ordinal number, of course!) that represents particular enum instance – and you want that enum instance. Mapping between these values and enum instances is a bijection, of course.

Our solution (here on GitHub) works fine, but there are two limitations:

  • ConvertedEnumResolver depends on the common interface ConvertedEnum our enums must implement, hence it is implicitly tied to the conversion framework.
  • If we need another representation (mapping) to different set of values we have to develop new resolver class.

Ok, the first one may not be a big deal. The second one is a real thing though. I realized this limitation before – and few weeks later, here we are, with enum that has not only DB representation (int) but also some String representation for different purposes. New resolver class was developed… But was it really necessary?

Everything in the resolver class is the same – but the instance method getting the value on the enum. I’m not going for any reflection, forget it. But hey, we recently switched to Java 8 and I’ve heard it has these method references! If we can pass it to the resolver constructor… is it possible?

Those who know Java 8 know that the answer is indeed positive. Our new resolver will look like this (I renamed it since the last time):

/**
 * Helps reverse resolving of enums from any value back to enum instance.
 * Resolver uses provided function that obtains value from enum instance.
 *
 * @param <T> type of an enum
 * @param <Y> type of a value
 */
public final class ReverseEnumResolver<T extends Enum, Y> {
    private final String classCanonicalName;
    private final Map<Y, T> valueMap = new HashMap<>();

    public ReverseEnumResolver(Class<T> enumClass, Function<T, Y> toValueFunction) {
        classCanonicalName = enumClass.getCanonicalName();
        for (T t : enumClass.getEnumConstants()) {
            valueMap.put(toValueFunction.apply(t), t);
        }
    }

    public T get(Y value) {
        T enumVal = valueMap.get(value);

        if (enumVal == null) {
            throw new IllegalArgumentException("No enum constant for '" + value + "' in " + classCanonicalName);
        }
        return enumVal;
    }
}

There is no conversion mentioned anymore. Just reverse resolving. So, our new enum does not have to be “Converted” anymore – unless you still need this interface for JPA conversion (which you may). Notice those method references:

/** Now we don't need to implement any interface for the sake of conversion/reverse resolving itself. */
public enum SomeEntityType {
    NORMAL(0, "norm"),
    SPECIAL(1, "spec");

    private final Integer dbValue;
    private final String strValue;

    private SomeEntityType(Integer dbValue, String strValue) {
        this.dbValue = dbValue;
        this.strValue = strValue;
    }

    public Integer getDbValue() {
        return dbValue;
    }

    public String getStrValue() {
        return strValue;
    }

    // static resolving for DB values
    public static final ReverseEnumResolver<SomeEntityType, Integer> dbValueResolver =
        new ReverseEnumResolver<>(SomeEntityType.class, SomeEntityType::getDbValue);

    public static SomeEntityType fromDbValue(Integer dbValue) {
        return dbValueResolver.get(dbValue);
    }

    // static resolving for String values
    public static final ReverseEnumResolver<SomeEntityType, String> strResolver =
        new ReverseEnumResolver<>(SomeEntityType.class, SomeEntityType::getStrValue);

    public static SomeEntityType fromStrValue(String value) {
        return strResolver.get(value);
    }
}

Plus we demonstrated that you can use two different values (dbValue, strValue). Of course it works:

System.out.println("SomeEntityType.fromStrValue(\"norm\") = " + SomeEntityType.fromStrValue("norm"));
System.out.println("SomeEntityType.fromDbValue(1) = " + SomeEntityType.fromDbValue(1));

This prints NORMAL and SPECIAL – as expected. Code for the classes can be found here, the whole demo is here and I’ll point you also directly to the README addition for this solution.

While Java libs get more and more bloated, these Java 8 syntax additions are definitely more than welcome. :-)

Making Windows 7/8 work again

OK, kinda questionable title, as Windows somehow works after install (and reinstall). But I have some additional professional needs. I don’t want to edit system properties in a single line, I want proper command line – preferably bash – and when at it, I’d welcome many Unix text/file utils too. I want proper console that resizes, allows more than silly block-mode copy. I want alt-tab working properly and not disappearing after a while. Better basic editor.

I wrote about some of the stuff, but maybe someone will find it helpful concentrated in a single post.

I’m actually no tools freak, I don’t check the landscape for new fancy tools every now and then, so there may be better alternative (“better” can have many meanings though :-)). So let’s just go through the stuff I need to do with a fresh Windows installation. Some stuff is related to 7 or 8, but most applies for both.

Many of my needs come from my profession. I’ll omit Java, Gradle/Maven, TortoiseSVN and others, but I’ll name those that help me be productive in command line for instance.

Alt Tab working again (Win 7)

Depends whether you like it or not. I want Alt+Tab to display the application switcher and keep it that way. Because that’s how I switch faster. Aero Peek is function that displays the application – which is cool when you’re in doubt which of those many same icons is the one you want – but when you continue hitting Alt+Tab it just does not display the switcher anymore. That sucks. Hit the Start button (or WinKey) and write “performance”. One of the filtered options should be “Adjust the appearance and performance of Windows”. Go for that. In Visual Effects tab, there is long list of checkboxes. And you want to disable Enable Aero Peek. Never missed it actually.

Windows 8 adjustments

I’ll be swift here, as I have adjusted just a single installation so far. My biggest concern I remember – from those that are easy to fix – was the sticky corner (corner clip) when I used dual-head. When I move window from one monitor to the other, I slide on the top edge – and I stumble upon the edge of the screen here. Fix is easy, although you have to edit the registry.

And then there was Narrator on Win+Enter which I accidentally pressed here and there. Just delete the executable or disable it other way. It can’t be disabled in any normal way.

Browsers, more browsers

So this one is obvious. What you need Internet Explorer for? To download Firefox (Chrome, whatever), right? Then you may need some Web Developer extension, Firebug and you’re ready to go.

BTW: If for nothing else, then for funny bug that ruins my Google Drive document writing on Firefox every time… copy/paste works for a while and then suddenly it stops. Restart does not help, nothing seems to help. Chrome does not have this problem (or it didn’t manifest so far). Copy/paste on Google Drive is quite popular problem so it seems, I don’t care who’s “fault” it is here. Just one of those many funny things about current innovations. ;-)

Notepad2 – what Notepad was supposed to be

No tabs, no complications, just Notepad. But with toolbar (should you want it) and some basic settings options. Better status line. That’s Notepad2. My biggest gripes with default Notepad are:

  • doesn’t work with unix newlines properly;
  • no reasonable support for various file encodings or re-coding.

Notepad2 does have these and some basic syntax highlight, newline conversion, regex search and more. Check FAQs to find out Notepad2’s position on some additional features. If it had hex editing, I’d probably never need anything else. For anything serious I use IntelliJ IDEA anyway.

Do you need a bigger gun? Go for Notepad++, Ultraedit, or whatever else, the list is way too long. What I like about Notepad2 is that it is exactly what I’d expect from Notepad – simple single document editor that doesn’t lack features you need way too often today – especially work with various encodings. Instead of reconfiguring apps to use this as a default editor, or associating file extensions, I simply replace both c:\windows\notepad.exe and c:\windows\system32\notepad.exe with this one. You need to claim the ownership and all this hardness, but it is well worth it.

Or you may try this BAT to do it (not sure how it works with domains, but you can’t screw anything except those notepad.exe binaries :-)). It uses notepad2.exe already copied into Windows directory which you have to do as Administrator:

REM run as admin
c:
cd \windows

takeown /f notepad.exe
icacls notepad.exe /grant %USERNAME%:F
copy notepad.exe notepad.exe.orig
copy notepad2.exe notepad.exe

takeown /f system32\notepad.exe
icacls system32\notepad.exe /grant %USERNAME%:F
copy system32\notepad.exe system32\notepad.exe.orig
copy notepad2.exe system32\notepad.exe

Total Commander

Or any other beast you like. I personally can’t get rid of these two-panel commanders. Bookmarks, tabs, many handy features (synchronize, multi-rename tool, built-in ZIP). I strip my Total Commander to hide F-buttons, toolbar, command line (right-arrow displays it) switch Quick Search to Letter only – and I’m ready to go.

Git

Ok, so I excluded SVN but here I come with Git – what is that? Well with Git for Windows you’ll get git bash – that is bash! And tons of useful Unix commands, though not all of course. So for the rest I go for…

GnuWin32

GnuWin32 contains tons of GNU tools ported for Windows. I don’t know the status of GnuWin64, but GnuWin32 works just fine on 64-bit system too. All packages neatly put their binaries into common bin directory, so a single PATH entry is enough.

Give some thought to your PATH order, I personally have git’s binaries before GnuWin32 because they are in some cases better integrated with its bash. But if you use also GnuPG, put it even before git.

Rapid Environment Editor

Talking about variables… I mentioned this one already some time ago. This is my hero for setting environment variables. Download it, use it, love it. It is handy to put all the *_HOME variables (JAVA_HOME, GRADLE_HOME, …) to System Variables and just reference them in PATH. And for bash usage it is handy to define HOME (for cd without arguments if for nothing else) in User Variables and set it to %USERPROFILE% – use variable of type Expandable String for that. Don’t forget to Save it (Ctrl+S as expected) and restart any program you expect using the stuff.

Real console, please!

And here I’m split a bit. I used Console2 for a long time, works fine, except it doesn’t maximize in Windows fashion. I also used ConEmu on another computer. Works fine, maximizes… but I didn’t work with it that hard like with Console 2. So I don’t know. ConEmu seems to have more features and more actively developed, so I’d check that one now. Both are far better than default cmd, where you – of course – can switch to bash, when you have it on path. For ConEmu, download something that extracts 7z – like 7-Zip – unless you go for MSI (whatever works better for you) or you install a packer plugin (WCX) to your Total Commander.

As for ConEmu settings (Win+Alt+P), you may want to make some changes:

  • First in Keys & Macro – Controls section disable Change prompt text cursor position, so we can make copy/paste work both from left mouse button select and from other programs too.
  • In Keys & Macro – Mark/Copy section for Text selection change the value to Always.
  • In Keys & Macro you may want to change Scroll buffer one page up/down from Ctrl+PgUp/Dn to Shift. It may be easier to find the functions if you sort the list by Description.

With these two I’m mostly ready.

Console with bash from Total Commander

BTW: I talked about Total Commander and Git Bash Here integration already – using Console 2. For ConEmu, let’s do it with editing your INI files – they will probably be in %USERPROFILE%\AppData\Roaming\GHISLER\. Just define your custom command in user.ini (adjust paths of course, bash is in PATH already in my case):

[em_bash]
button=C:\work\tools\ConEmu\ConEmu.exe
cmd=C:\work\tools\ConEmu\ConEmu.exe
param=-cmd bash --login -i

And in wincmd.ini just use this command – I chose Ctrl+B shortcut:

[Shortcuts]
C+B=em_bash

Happy bashing.

Bashing who?

Obviously I’m no big Windows lover. I even hate it as a server platform. I love ssh to my boxes spitting commands on them. This is probably possible for Windows too, but actually not many people use it. I’m still waiting to meet good Windows administrator and enthusiast who will show me some meaning of Windows as a server. Combined with Java. Screw performance comparisons now, just talking about my life as an administrator or developer.

But I’m using Windows in my daily job as my desktop and I like many of the stuff. I don’t turn it into Linux (ok, bash, GnuWin…, but…), I don’t use virtual desktops (I loved them), or any advanced keyboard shortcut solutions. All these tools and adjustments are really rather elementary to me.

I like some of the Windows stuff (when I remove some other). So I don’t want to bash Windows. Installing and integrating all the things together is no doubt more demanding than a couple of apt-get commands Linux users are used to. But then, they often need to go through many configurations as well.

Cool stuff that works

Learn WinKey shortcuts. It really pays off. You may stun your boss when you tell them, “just press Win+Shift+Right to get it on the projector” (switching app between screens).

Pin your applications on the taskbar and start or switch to them using Win+number.

If you use localized keyboard a lot, learn AltGr shortcuts, at least the basic ones. When you need a single curly brace it is much faster to press AltGr+B than Alt+Shift, { and Alt+Shift again. Often these AltGr symbols are printed on the keyboard.

Windows 8?

Windows 8 is generally step in a wrong direction for (not only) me, but it has some interesting additions. While you can’t Alt+F4 after closing the last application to get Shutdown dialog anymore, you can use new Win+X (Power User Menu) and then just double tap U, U to do the same. And many, many more through this menu. There is more for sure, but generally Windows 8 rather does maximum to get into our way if we use the PC the old way (no touch display, etc.). Kinda shame.

I hope you found some of the tips and tools helpful. If you have your tricks and favourite tools, feel free to share them in comments! :-)

Releasing to Maven Central with Git on Windows

Originally I wanted to write about two problems. I think both were somehow related to interactions between Maven, Git and GPG on my Windows. But because I didn’t document it both on time, things got lost. So this will be only half of the story.

Short version? Don’t mix various gpg on your PATH. If you use Gpg4Win, prefer that one.

Switching to Git

When you start with Git, you’ll probably get lost often even when you get the basic ideas and read those intro manuals. There was no big deal about SVN coming from CSV, but Git is different beast altogether and definitely worth studying. For example, it may happen that your local master branch is ahead of remote master by hundreds of commits (the whole history really), while push is pushing just new commits… And you have no idea what you did first – and I bet there will be more surprises like this. (Little note, for me fetch didn’t work, but the second answer with rebase -p did. Don’t ask, I still have to study it. :-))

With just a few glitches like this I was reasonably afraid of my first release to Maven central with Java Simon on Git repository. But it was much smoother in the end, especially from Maven’s side. Credit to Maven this time, I remember its release plugin throwing bugs at me – and now it did its job with VCS I don’t understand yet.

GPG vs Git’s GPG

The problem I managed to write down is related to the fact, that I had Gpg4Win installed previously (for Maven Central requires signed artifacts) and Git brought another GPG with it too. So this is – obviously – kinda Windows specific.

First I needed to create my new GPG keys for signing artifacts going to Maven central, because for unknown reasons I elegantly deleted the .gnupg directory some time before. So you create the key with:

gpg --gen-key

And then you go to upload it:

gpg --keyserver hkp://pool.sks-keyservers.net --send-keys 08XXXXXX

And there is this error:

gpg: sending key 081A513E to hkp server pool.sks-keyservers.net
gpg: system error while calling external program: No error
gpg: WARNING: unable to remove tempfile (out) `...\AppData\Local\Temp\gpg-515B3D\tempout.txt': No such file or directory
gpg: no handler for keyserver scheme `hkp'
gpg: keyserver send failed: keyserver error

It sounds like anything but the proper solution – your gpg did not find gpgkeys_* executables in the same directory. You can eventually Google it and there is some StackOverflow question too, but answers are various. This is the first strike of git-bash and my PATH settings. There is /bin/gpg, but you better use gpg from where it is installed:

/c/Program\ Files/GNU/GnuPG/gpg --keyserver hkp://pool.sks-keyservers.net \
--send-keys 08XXXXXX

Fixing the PATH

Cleanest solution is to prefer Gpg4Win, so just put C:\Program Files\GNU\GnuPG to the first spot of your PATH – or at least anywhere before Git’s bin directory (which is also high on my list to prefer its commands before binaries from GnuWin32). If you have C:\Program Files\GNU\GnuPG\pub on the list too, bump it up as well. Or just check what Gpg4Win put onto your PATH and move that. Sorry for being a bit vague here – this happened to me with gpg.exe in GnuPG directory first, but now I have only gpg2.exe there and gpg.exe in pub sub-directory which was added to the PATH. This seems to be a change since 2.x versions of gpg or Gpg4Win.

You could – of course – just delete or rename /bin/gpg.exe. But after unplanned Git reinstall it would be there again. Proper order in PATH is important anyway, although I too feel much better when there are no colliding binaries.

GPG speaking different languages?

Is your GPG talking to you in native language and you want it English? Simply set LC_MESSAGES=C (Rapid Environment Editor recommended, use User Variables). Alternatively just delete GnuPG/share/locale directory :-) seems not to hurt anything.

Conclusion

I believe my other problem was also related to gpg, it was another twist on the PATH problem when running Maven – which uses gpg to sign those artefacts with keys you prepared. So the main advice still applies. Organize your PATH properly, preferably in Windows System Variables, as Git’s bash will translate it into UNIX format just fine. Also with proper system-wide PATH things will run properly in both cmd and bash, unless they are shell specific. For instance mvn clean release should work in both.

Converting Java enums to values and back

You know the stuff, you have some enums that logically wraps for instance integer constants. Typical case is numeric DB column mapped to enum. We all know that using EnumType.ORDINAL is one of those worse solutions. And EnumType.STRING is not really loved by our DB admins (if you have them) – even though it’s easy to read for sure. :-) Normalization suffers, enum constant renaming is a bit problem too. So we want to map it to numeric (for instance) which would be Integer in JPA entity.

This mapping does not necessarily related only to JPA, there are many cases when you want to convert enum to something and back. For instance, with generated web-services I often map generated enum to my “business” one and if it suits me (as it is not always clean) I embed this mapping into my enum (not the generated one of course :-)). So I map enum to another related enum and back. But we will work with JPA example. JPA 2.1 with AttributeConverter<X,Y> to be precise. You can do something similar with Hibernate converters too, I’m sure.

This blog post is accompanied by this GitHub project containing all the variations. Copy and paste and use whatever however you like.

Naive approach

Before going on, know that you can check all examples in this GitHub repository. First case can be found in this location. We have our simple enum:

public enum SomeEntityType {
	NORMAL,
	SPECIAL
}

And we have our entity that is mapping numeric column to our enum:

@Entity
public class SomeEntity {
	@Id private Integer id;

	@Convert(converter = SomeEntityTypeConverter.class)
	@Column(name = "type")
	private SomeEntityType type;
}

This entity will be the same throughout all of our solutions, so we will not repeat it. Important line is the one with @Convert annotation that finally allows us to do conversion (JPA 2.1, part of Java EE 7). All we have to do now is to implement that converter:

import javax.persistence.AttributeConverter;

/**
 * This is coupled too much to enum and you always have to change both classes in tandem.
 * That's a big STOP (and think) sign in any case.
 */
public class SomeEntityTypeConverter implements AttributeConverter<SomeEntityType, Integer> {
	@Override
	public Integer convertToDatabaseColumn(SomeEntityType someEntityType) {
		switch (someEntityType) {
			case NORMAL: return 0;
			case SPECIAL: return 1;
			default:
				// do we need this? if for nothing else it catches forgotten case when enum is modified
				throw new IllegalArgumentException("Invalid value " + someEntityType);
				// actually the value is valid, just this externalized switch sucks of course
		}
	}

	@Override
	public SomeEntityType convertToEntityAttribute(Integer dbValue) {
		switch (dbValue) {
			case 0: return SomeEntityType.NORMAL;
			case 1: return SomeEntityType.SPECIAL;
		}
		// now what? probably exception would be better just to warn programmer
		// but if it happens in production, it doesn't really matter if it's here or NPE later
		return null;
	}
}

Ok, so I revealed the problems in the comments. There may be just one reason to do it this way. If you need the enum independent from that dbValue mapping – but I really don’t know why. On the contrary, you should go for cohesive solution. And in this case you will be just fine with encapsulation. Put the stuff that changes into one place – the enum.

Encapsulated conversion

You need to implement AttributeConverter, because it is kind of glue between JPA and your class. But there is no reason to leave the actual mapping in this infrastructure class. So let’s enhance the enum to keep the converter simple. Converter I want to see looks like this:

public class SomeEntityTypeConverter implements AttributeConverter<SomeEntityType, Integer> {
	@Override
	public Integer convertToDatabaseColumn(SomeEntityType someEntityType) {
		return someEntityType.getDbValue();
	}

	@Override
	public SomeEntityType convertToEntityAttribute(Integer dbValue) {
		// this can still return null unless it throws IllegalArgumentException
		// which would be in line with enums static valueOf method
		return SomeEntityType.fromDbValue(dbValue);
	}
}

Much better, we don’t have to think about this class at all when we add values to enum. The complexity is now here, but it’s all tight in a single class:

public enum SomeEntityType {
	NORMAL(0),
	SPECIAL(1);

	// ENUM -> DB VALUE CONVERSION
	// first part is easy and most programmers get here (Effective Java 101 after all)
	// fields are not final implicitly, but we better make them
	private final Integer dbValue;

	private SomeEntityType(Integer dbValue) {
		this.dbValue = dbValue;
	}

	public Integer getDbValue() {
		return dbValue;
	}

	// DB VALUE -> ENUM CONVERSION
	// static reverse resolving:
	public static final Map<Integer, SomeEntityType> dbValues = new HashMap<>();

	static {
		for (SomeEntityType value : values()) {
			dbValues.put(value.dbValue, value);
		}
	}

	public static SomeEntityType fromDbValue(Integer dbValue) {
		// this returns null for invalid value, check for null and throw exception if you need it
		return dbValues.get(dbValue);
	}
}

I saw also some half-solutions without the static reverse resolving, but I hope we all agree it goes into the enum. If it’s two value enum, you may start with switch in fromDbValue, but that’s just another thing to think about – and one static map will not kill anyone. You can find this solution here on GitHub.

Now this works, so let’s imagine we need this for many enums. Can we find some common ground here? I think we can.

Conversion microframework

Let’s say we want to have order in these things. We will require the method named toDbValue, etc. So our enums will implement interface ConvertedEnum:

/**
 * Declares this enum as converted into database, column value of type Y.
 *
 * In addition to implementing {@link #toDbValue()} converted enum should also
 * provide static method for reverse conversion, for instance {@code X fromDbValue(Y)}.
 * This one should throw {@link IllegalArgumentException} just as {@link Enum#valueOf(Class, String)} does.
 * Check {@link EnumAttributeConverter} for helper methods that can be used during reverse conversion.
 */
public interface ConvertedEnum<Y> {
	Y toDbValue();
}

It’s parametrized, hence flexible. Javadoc says it all – we can’t enforce the static stuff, because that’s how Java works. While I suggest that reverse fromDbValue should throw IllegalArgumentException, I’ll leave it to return null for now – just know that I’m aware of this. :-) I’d personally go strictly for IAE, but I’ll show how we can use null in conversion.

What are the changes in the enum? Minimal really, just add implements ConvertedEnum<Integer> and you can add @Override over toDbValue method. Not worth the listing as it’s all here on GitHub anyway.

Now to utilize all this we need a base class for AttributeConverter – here it goes:

/**
 * Base implementation for converting enums stored in DB.
 * Enums must implement {@link ConvertedEnum}.
 */
public abstract class EnumAttributeConverter<X extends ConvertedEnum<Y>, Y>
	implements AttributeConverter<X, Y>
{
	@Override
	public final Y convertToDatabaseColumn(X x) {
		return x.toDbValue();
	}

// you can end here, or you can add handy stuff if necessary
	public X notNull(X x) {
		return notNull(x, null);
	}

	public X notNull(X x, Y dbValue) {
		if (x == null) {
			throw new IllegalArgumentException("No enum constant" + (dbValue != null ? (" for DB value " + dbValue) : ""));
		}
		return x;
	}

	public X withDefault(X x, X defaultValue) {
		return x != null ? x : defaultValue;
	}
}

As you can see, only convertToDatabaseColumn is mandatory here. Here is our concrete converter:

public class SomeEntityTypeConverter extends EnumAttributeConverter<SomeEntityType, Integer> {
	@Override
	public SomeEntityType convertToEntityAttribute(Integer integer) {
		return notNull(SomeEntityType.fromDbValue(integer));
	}
}

What a beauty suddenly! I also used notNull to enforce IllegalArgumentException (unless you do it on enum level), or I could use withDefault to fallback to some default value – if it makes sense of course (better when it doesn’t :-)).

Refinement?

And now the last push. What is repeating? And what we can do about it?

  • It would be cool to have just a single converter class – but this is impossible, because there is no way how to instruct the converter about its types. Especially method convertToEntityAttribute is immune to any approach because there is nothing during runtime that can tell you what the expected enum type would be. No reflection or anything helps here, so it seems.
  • So we have to have separate AttributeConverter classes, but can we pull convertToEntityAttribute into our EnumAttributeConverter? Not easily really, but we’ll try something.
  • How about the static resolving? Can we get rid of that static initialization block? It is static, so it seems problematic – but indeed, we can do something about it.

Let’s try to hack our converters first. We need to get the type information into the instance of the superclass. It can be protected field like this:

public abstract class EnumAttributeConverter<X extends ConvertedEnum<Y>, Y>
	implements AttributeConverter<X, Y>
{
	protected Class<X> enumClass;

And subclass would initialize it this way:

public class SomeEntityTypeConverter extends EnumAttributeConverter<SomeEntityType, Integer> {
	{
		enumClass = SomeEntityType.class;
	}

But this is not enforced in any way! Rather use abstract method that must be implemented. In abstract converter:

	protected abstract Class<X> enumClass();

And in concrete class:

public class SomeEntityTypeConverter extends EnumAttributeConverter<SomeEntityType, Integer> {
	@Override
	protected Class<SomeEntityType> enumClass() {
		return SomeEntityType.class;
	}
}

But we’re back to 3 lines of code (excluding @Override) and we didn’t get to ugly unified convertToEntityAttribute:

	@Override
	public X convertToEntityAttribute(Y dbValue) {
		try {
			Method method = enumClass().getMethod("fromDbValue", dbValue.getClass());
			return (X) method.invoke(null, dbValue);
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			throw new IllegalArgumentException("...this really doesn't make sense", e);
		}
	}

Maybe I missed something on the path, but this doesn’t sound like good solution. It would be if it lead to unified converter class, but it is not. There may be one more problem with hunt for unified solution. While the concrete implementation contains methods that have concrete parameter and return types, unified abstract implementation don’t. They can use the right types during runtime, but the method wouldn’t tell you if you used reflection. Imagine JPA checking this. Right now I know that unified public final Y convertToDatabaseColumn(X x) {…} works with EclipseLink, but maybe we’re asking for problems. Let’s check it really:

// throws NoSuchMethodException
// Method method = converter.getClass().getMethod("convertToDatabaseColumn", Integer.class);
Method method = converter.getClass().getMethod("convertToDatabaseColumn", Object.class);
System.out.println("method = " + method);

// prints:
method = public java.lang.Object com.github.virgo47.enumconv._4evenmore.EnumAttributeConverter.convertToDatabaseColumn(java.lang.Object)

Great… so if something strictly matches the method types with column/enum types, we may have a misunderstanding. Sometimes too smart may be just that – too smart. Check this overboard solution here on GitHub.

Simplified static resolving

Anyway, let’s look into that enum’s static resolving. This is actually really useful. Without further ado, this is how enum part may look like:

	// static resolving:
	public static final ConvertedEnumResolver<SomeEntityType, Integer> resolver = new ConvertedEnumResolver<>(SomeEntityType.class);

	public static SomeEntityType fromDbValue(Integer dbValue) {
		return resolver.get(dbValue);
	}

So we got rid of static initializer. But the code must be somewhere:

/**
 * Helps reverse resolving of {@link ConvertedEnum} from a DB value back to enum instance.
 * Enums that can be resolved this way must have unified interface in order to obtain
 * {@link ConvertedEnum#toDbValue()}.
 *
 * @param <T> type of an enum
 * @param <Y> type of DB value
 */
public class ConvertedEnumResolver<T extends ConvertedEnum<Y>, Y> {

	private final String classCanonicalName;
	private final Map<Y, T> dbValues = new HashMap<>();

	public ConvertedEnumResolver(Class<T> enumClass) {
		classCanonicalName = enumClass.getCanonicalName();
		for (T t : enumClass.getEnumConstants()) {
			dbValues.put(t.toDbValue(), t);
		}
	}

	public T get(Y dbValue) {
		T enumValue = dbValues.get(dbValue);
		if (enumValue == null) {
			throw new IllegalArgumentException("No enum constant for dbValue " + dbValue + " in " + classCanonicalName);
		}
		return enumValue;
	}
}

And this I actually really like. Here I went for strict checking, throwing exception. Without it, or without needing/wanting the type name it could be even shorter. But you write this one once and save in each enum. Check the complete sources here on GitHub.

So there are three players in this “framework”:

  • ConvertedEnum – interface for your enums that are converted in this way.
  • ConvertedEnumResolver – wraps the reverse mapping and saves you most of the static lines in each converted enum.
  • EnumAttributeConverter – maybe the most questionable part here. It takes care of one direction of the conversion, just be aware of potential problems if something introspect the method types.

Alternative conversions with entities

While not exactly on the topic of enum to value mapping (and back), we were demonstrating this all in context of JPA 2.1. So I’d like to at least mention alternative solutions for older JPA versions.

  • You can always use vendor specific extensions. Hibernate has its Custom types and I’m sure EclipseLink doesn’t fall behind.
  • But there is also possibility to use mapping annotations on properties. That is put your @Id on the getter, or specify AccessType.PROPERTY. This allows you to convert anything to anything in getter/setter. I even used it to back Dates by long (or Long if nullable). This way various tools (like Sonar) didn’t complain about silly mutable Date breaking the encapsulation when used directly in get/set methods, because it was not stored directly anymore. Hibernate used get/set for Date, and I had @Transient get/set for millis long available. I actually liked comparing millis more than before/after methods on Date, but that’s another story. The same can be used for mapping enums – just have JPA compatible type mapped for JPA and @Transient get/set with enum type. Most of the stuff about enum encapsulation and static resolving still applies.

I hope you liked our tour around enums. If you knew or used this before, good for you. I’m surprised how many programmers don’t try to design and refactor these little things where you don’t even need to think in UML.

And if you have better solutions, share them in comments, please. :-)

RESTful Spring Security with Authentication Token

Recently I had to do some “research” how to use Spring Security for a RESTful API serving rich JavaScript UI. There were also questions whether to use Spring Security at all, but as of now, we’re still deciding to take this path. While it is possible to have a JSON API that is not really RESTful and we can have HTTP session behind it all, we decided to go with REST. That sets the scene: REST, Spring Security and token-based authentication.

HTTP authentication and tokens

Big question is what mechanism of authentication we want to use. If for nothing else, than at least for username (login) and password we will have SSL/TLS in place, so let’s say we will have HTTPS there all the time. This blurs the difference between classical HTTP Basic and Digest access authentication. So I decided to support Basic only for simplicity. For even easier development I introduced custom X-Username and X-Password headers, which allowed to test my solution with curl and similar tools entering plain values.

I’ve read more than a couple of articles and while I hardly became an expert on security, authentication (with HTTP or not), REST or tokens, I felt I got the basics. I also got familiar with enough ideas that I had to do some choices. I thought it would be easier, but obviously there are many ways how to construct a token. And people are probably still inventing more. So I decided to use randomly generated token that does not utilize user’s password at all – but it doesn’t really matter. You somehow create that token, that’s it. I aimed for solution that allows me to change this behavior easily.

There is also questions whether one token is enough, should you transfer it in HTTP headers or utilize HttpOnly cookie so that JavaScript can’t “share” it with some attacker, etc. Way too many questions and if you feel like, you can share your ideas and reasons in the comments. For I’ll focus on server side now, that is the part related to Spring Security. The landscape here is not that deserted actually – and I got lucky I stumbled upon this StackOverflow question which lead me to this demo on GitHub. I have to admit that some parts are from there and for other parts I used it at least as to check my solution.

Spring Security for REST?

Book Spring Security 3.1 by Robert Winch and Peter Mularien was another important source of understanding what is happening here. I tackled Spring Security before but never had a chance to go in-depth (that is beyond reactive Google/StackOverflow and some reference documentation reading), mostly because I tried to get in-depth with something else. Now was the time to understand what this framework is about. Good book, nice examples – maybe some UML class diagrams would help when introducing new important classes and interfaces and their roles.

The result is my take on RESTful Spring Security – it’s not really that revolutionary, but I tried to do couple of things differently. I even provided UML diagram. :-) So I’ll copy it from README.md right here, ok?

restful-spring-security-class-uml

Now what is going on here and – if you insist – how is this different from philipsorst’s solution?

  1. I wasn’t interested in real UI, so I tested it with any REST testing extension you can find, or with curl. In the end I even put together mini-framework based on bash and curl. :-)
  2. I wasn’t interested in JPA/DB. I wanted as little frameworks thrown in as possible. So there is DAO with hardcoded users.
  3. I also wanted to come up with design that clearly separates the concept (package restsec) from any concrete implementation (secimpl), principles from details, Spring Security from the domain/application code (domain/mvc). Looking at the class diagram I think I did quite well.
  4. I wanted to try access control configured in XML and using annotations like @PreAuthenticate.
  5. Then there are some side-quests – I practiced some Gradle in combination with Spring Boot as my Bill Of Materials (kinda Maven style import scope) and I tested WildFly 8.1 (not really important).
  6. Finally – I wanted to document it sufficiently, both in code (comments) and in README + planned this post too. For self documentation. It pays off. I don’t remember what I need to do to make client certificates up and running on Tomcat, but I know where to look at (if it is not obsolete yet). And I used my own articles here and there already! (Actually, even my colleagues googled out my articles and found them helpful – you can’t imagine how it made me proud. ;-))

Spring Security going session-less

So how is it all working together? Because everything related to HTTP and authentication is concentrated essentially in TokenAuthenticationFilter, you don’t need any unprotected login URL. Filter is sitting in Spring Security filter chain, specifically in FORM_LOGIN_FILTER position. All you need is to provide authentication headers in any request. Because we are RESTful, we don’t want to utilize session at all. If you check spring-security.xml, this is set in http element:

<http realm="Protected API"
        use-expressions="true"
        create-session="stateless"
        entry-point-ref="unauthorizedEntryPoint"
        authentication-manager-ref="restAuthenticationManager">

It is important to set it to stateless (don’t use session at all), not to never (which allows Spring Security to use if it somehow exists already, just don’t create it).

Let’s stop at this statelessness for a while, shall we? This does not mean that there is no server-side state at all. It just means that we don’t work with HTTP session. We still need to remember valid tokens – we may do so within DB, application context, shared distributed memory, wherever – that is definitely stateful. But from HTTP standpoint, we should be RESTful enough now. Also we utilize Spring’s SecurityContextHolder because it makes sense if you want to benefit from other Spring Security stuff, like their annotations, etc. This way we smuggle our security information using a thread-local variable (default behavior) during each single request.

Anonymous access

Before we get to business, let us see how anonymous access works first. For that assume that these are our first request and we didn’t authenticate before. In the following sequence diagrams, grey stuff is from Spring, rest is ours.

anonymous-access-allowed

As any other model, this one is not complete or exact. Our filter is part of Spring Security chain and definitely is not called directly by browser. But in any case it’s the first moment we are interested in. Virtually every request goes through this filter (unless it avoids part of the application secured Spring Security completely). If we are accessing something available for unauthenticated user, we get what we want.

Second scenario tries to access something protected. This will not get to our Spring MVC controller:

anonymous-access-denied

It actually gets all the way to its proxy (in our case CGLib based, because our Controller does not implement any interface) and there an implementation of AccessDecisionManager finds out that anonymous user can’t access the method and AccessDeniedException is thrown. This is caught by ExceptionTranslationFilter (part of Spring Security chain) which calls authentication entry point for this kind of exception. Normal applications use the entry point it to redirect to a login screen. We don’t want to do that, but we need to implement it, so it sets the HTTP response status (401).

It’s very easy to debug it all and it’s very nice to browse through Spring code. Maybe Spring got big and complex (well it does a lot of things now), but their code is on the positive side of quality spectrum – understandable and well documented.

Login, login! Login this lap!

(Sorry, F1 race today, you know.) Four things may be happening in our application. You may be anonymous, you may be authenticated already, you’re logging in, or logging out. My implementation tries not to mix things together much, you should do just one of these things in a single request. Let’s log in to get authenticated. Login request can continue to the REST resource and return data, but I chose otherwise. This can be reimplemented of course – TokenAuthenticationFilter#checkLogin would call doNotContinueWithRequestProcessing only if the response is not 200. But currently it works this way. Here is the diagram:

login

If our filter finds information that looks like login (and it must be POST), it will pass username/password to AuthenticationService. This is still our part of solution and glues the filter with the rest of Spring Security. It calls Springs AuthenticationManager, which in turns calls our implementation of UserDetailsService, which provides username and password (in our case plain, not a good solution of course). Not to plague the diagram with stuff, I skipped Spring’s PasswordEncoder which helps authentication manager to decide if we can go on. If we can, we get back to our security service, which populates Spring’s SecurityContextHolder and now is the time to get the token.

For this we have separate component – TokenManager – which creates and stores the token for the user. Currently only one token per user is supported, but you can implement your own approach here. Actually if you reimplement AuthenticationService considerably, there may be nothing to call TokenManager. There’s a lot of freedom here, but I think TokenManager is the place where most of the customization can go into. How to create the tokens? How to store them? How to check them? Or expire them? However you want to answer these questions, TokenManager is your guy. You still may need to adjust authentication service or filter – for instance to add some HTTP related information (IP address?) into token.

Long story short? If everything is alright, HTTP response returns status 200 and the header X-Auth-Token contains the token next requests should use to prove who you are.

Authenticated request

Here we don’t care what HTTP method is used. After login, this should be easy to understand:

authenticated-access

You already know all the players, here we just first check whether provided token is indeed one of those we know – and if so, we populate SecurityContextHolder. In case of 401, we don’t even bother calling the rest of the chain. The rest (cases 200 and 403) is in Spring’s hands.

Hence we can rush towards…

Logout

Logout should invalidate user’s sess… ehm, token, obviously. That implies valid token is provided. We also insist on POST and require specific URL. We could also request logout with another HTTP header, or with “logout” mentioned in X-Auth-Token, etc. Here it is:

logout

And that’s it really!

Conclusion

You could see all the important players on the diagrams, some of them are our classes, some of them are part of Spring Security “auto-magic”. I’m sure even XML configuration is much clearer now. There is great deal of freedom here – you may bypass Spring Security authentication manager altogether, for instance – don’t know why, but there may be reasons.

I’m not done yet. Later we’ll need to integrate this with some reliable Windows Domain SSO authentication (so far we count on Waffle), not to mention with the rest of the application.

That “demo app” is a mix of XML configuration and annotations, so check those out, check the comments, README, etc. I really tried different things just to find out how it all works (like that mandatory ROLE_ prefix!) and I’m still probably just skimming the surface. But still better than two weeks ago. :-)

And that concludes my post and my first campaign in this war.

Crippling IT revolutions

Long time ago computers were slow, UI was primitive (say Windows) and there was a lot to learn. Now all is about the end of PC era, tablets and absolute disregard for the voice of users. And still you have to learn a lot as a user. What I miss quite a lot in technology is evolutionary design, something getting just better and better. Refined. I’m not a Mac user, maybe the situation there is different… I don’t know. Maybe it’s market pressure.

It’s not all bad. I’m personally done with HTC Android phones (because of revolutionary bugs), but my wife’s Samsung (cheaper than both HTCs) seems OK. And Nexus tablet isn’t bad either. But then there are simple things I believe should work and they don’t.

Online too many times at once

For instance, you log in to your Google account on the tablet, then your wife uses it with her account and week later a friend of yours asks you why you never answer him on Skype even though you are green all the time. Skype? Online all the time?! No way… and then you get it. Skype installed on Android tablet where you are not actually active for a week. Where are any reasonable defaults? Where are all the years of experience with these communication programs, chats and all?

You may argue I should set it all properly – but… It’s extremely complicated to manage various communication accounts. Their settings and policies change all the time, UI even more so. Something is in the cloud, something in your local settings. Different on each computer. And something is somehow combined. Products come and go. Some communication options are out of your control – on my HTC Wildfire I cannot disable Google Talk when I want to use Google account (there are actually way too many things that can’t be disabled for such a slow phone). But I never want to chat on a phone!

Remember me… really!

Talking about Google – I’m logged in all the time, yet it forgets my prefered language every couple of weeks, or days even (forces me to use my native Slovak, while I prefer English for professional reasons). Every time I set it properly in their settings and after a while it’s gone. How can we set things properly with products like this? Every second day (or more often) they ask me about Cookies. I’m OK with Cookies on trusted services (well… trusted… I just feel unimportant enough not to care about NSA’s knowledge about me :-)). Why I have to confirm this more than once in a… week? Month would be OK, a year ideal.

Keyboard innovations?

And then there are new notebook trends, so let’s skip to HW for a while. I bought Lenovo G500 for my wife. It seemed OK. But then you learn things you’d never expect – like that F1-12 keys must be pressed with Fn key, because their default functions are inverted (Fn actions instead of F1-12) without any option to flip this stupid idea off! The same happened even on ThinkPad S531, but there you have an option to lock Fn key (press Fn+Esc). So you can use ThinkPad professionally, but G500 is just a silly toy really! Try to use IntelliJ IDEA or any IDE for that matter. Try to press Ctrl+Alt+Shift+F7… and add Fn to it. Not impossible, but really silly. Luckily external keyboard works just fine.

Let’s talk about ThinkPad S531 a bit more. It could have been great computer actually. I don’t like Fn in the corner, but hey – it’s ThinkPad, IBM started it, get used to it. But why I have to get used to the new touchpad without physical buttons? Maybe it would work with Mac, but on PC where you need even three buttons sometimes…? Most of the time I indeed use external mouse, but when I’m on the move, I still want to have reasonably good experience using the notebook as is. Here it is very limited. I’m more often than not unable to press right “button” without accidentally moving the cursor. This is no revolution or evolution – it’s plain step backwards.

Ergonomy of other keys could also be questioned. Actually I was extremely pleased with layout of PgUp/Dn, End, Home and the rest on HP ProBooks. And I’m far from HP lover. But having Page Up/Down in the upper right corner was easy to find and very easy to use. Lenovo put quite useless Explorer key there and Home/End are buried in the upper row. Talking about these keys… most of them can be redefined, but Lenovo put Screen Lock key just above numpad as well. Just in case you are dumb or what… what is wrong with Win+L? This can’t be redefined, because – so it seems – it is hardwired to Win+L! Bravo…

Rather delete me as you can’t really disable me

And then there is Windows 8. Point one actually. Screw Metro, we’ve all heard tons about it already. But then there are those small things. Try Narrator for instance! Just press Win+Enter out of curiosity. I felt like disabled (no offence) immediately – because I was not able to turn it off. I had to Google it. Mute shortcut came handy in the meantime. Many people obviously want to disable these accessibility features – but there is no easy way. No single switch. Microsoft! Hear us! (Maybe they need Narrator for our complaints too.) Solutions? Delete narrator.exe for instance. Or disable its executable in Registry. (All provided by StackOverflow, Microsoft offers no definitive solution.) You gotta be kidding me, right?

Get dumb with me

Everything seems to be dumbed-down lately – but in the most wrong way. More features that are hardly understood by my mum anyway – and too few options for professionals. Not talking only about programmers here, this must annoy most of power users of any kind. And then there are other Google searches I went through during my first two days with Windows 8. And many of them were very close at the top of the suggested list before I even started writing last words! Like “windows 8 touch keyboard” finished with “keeps coming back”, or “windows 8 wifi” with “forgets password” (suggested on 6th place). Why do we have to keep solving annoying stuff instead of doing our job?

Sure, some things may be caused by Lenovo drivers… so what?

Any positives compared to Windows 7? Maybe under cover (which is expected), but UI goes in the wrong way. Ugly, thick window borders that can’t be easily customized. And when you get happy that you can easily set the background for the welcome screen, you find out that there is also this uber-ugly login screen with the most ugly metro violet ever (Sun’s enterprise violet was so nice compared to this. :-))

Well, rant over, next time I’ll try to solve something with Docker and Wildfly – and that seems to be much more promising direction of evolution.

Maschine 2.0 Newbie Review

It has been some time since I upgraded my Maschine to 2.0. Not a big win for me when I think about it, but you know how it is – old Maschine will hardly have any support and – probably the biggest reason – I wanted to support Native Instruments and maybe get some more sound content in the process.

I used Maschine 1.x with my Maschine Mikro (Mk1) to create a few songs – or mostly just drum/bass lines for songs that we could perform live. It was alright and I liked that I needed to interact only with the controller on stage.

Now I tried to use Maschine 2.0 expecting some improvements over the previous software version. I’m sure many people got what they wanted, but for me Maschine 2.0 is more like a facelift – without bringing anything essential. Kinda like “we have to come up with something new” stuff. This is probably not fair, but I just use basic things and I feel that way.

I don’t expect things to always go my way. I have ideas and try to communicate them on forums of my favourite products, not to mention many bug reports for things like IntelliJ IDEA that even got fixed. ;-) One simply cannot have it all. But there are a few things that are kinda striking.

I use Large layout for instance and let’s take a look, how it looks by default:

First the “red problems”: So the Arranger (upper part) does not display all 8 groups you have (at least by default), and Pattern Editor has plenty of free space for more sounds than necessary. Of course you can use this space in the part with Piano roll…

However, the biggest point here is – even though you can change the layout (use the section corner marked on the right of the screenshot) there seems to be no way how to save it. So even if you change it, the next time it’s gone.

My other issue was with zooming. You can only zoom on the zooming scroll bars (horizontal ones are marked with blue, but the same goes for vertical ones). Now imagine you want to fix a particular event with your mouse. To zoom to any reasonable level you have to go away from the event (that is already probably selected) and meddle with the scroll bar, pressing the mouse button, moving the mouse up/down to zoom – and also to the left/right in order to keep the event in the view. Now imagine using just Ctrl+mouse wheel right on the spot (or Ctrl+Shift for vertical zoom which is less needed in most cases). Wouldn’t that be great?

Generally many things in Maschine UI are made in a way that is completely counterintuitive – the only way is to learn the stuff and keep using it, because otherwise you have to refresh it every time before you occasionally use the Maschine software (my case).

When I compare this with Reaper for instance, that is a true power tool where:

  • you see keyboard shortcuts next to the action in any menu (main, contextual) – this is true for main menu in Maschine as well, but that is just too little
  • you can assign nearly whatever to whatever in their Actions window – not to mention you can use it as a quick reference and find the shortcut for an action there too
  • UI always loads how I left it
  • there are tooltips for buttons, often even with status information (for instance: Metronome disabled) – tooltips would be a big help for any starting/intermediate/occasional user of Maschine

We may argue that focus in Maschine is on another thing (partially true), that they don’t want to spoil it with too many DAW-like features (agreed, mouse zoom is not colliding with anything in Maschine though), and that you should mostly use their hardware. The last thing is valid for things like live productions (and more of course), but one way or the other – if you prepare something in Maschine for later use, you may need to edit it. And that is much easier with UI and mouse.

To sum it up: Maschine UI is different from standard even when not necessary, lacking tooltips completely, there is no in-place help with keyboard shortcuts, few contextual menus (no wonder when right-click deletes stuff, double click would probably did just as good), it doesn’t save the UI layout, zoom is awkward and I’m not going into shortcut customization.

I know that UI is just an addition to the hardware (though absolutely necessary) and personally I can pardon that you can’t change keyboard shortcuts. But many of these things are kinda easy to fix (tooltips?) and they would help a long way – especially users new to NI.

Maschine sure is a lot of fun anyway, but a little bit more seriousness to its DAW aspects wouldn’t hurt at all.

Follow

Get every new post delivered to your Inbox.

Join 222 other followers