Java 8 on OS X Yosemite

I downloaded a recent copy of IntelliJ, only to discover when I went to open it, OS  Yosemite indicated I had no version of Java installed, and that I’d need to install an old version. The “More Info…” button took me to this page:  http://support.apple.com/kb/DL1572

…which didn’t load.  (UPDATE: This fixed the load issue.) Similar detailed install directions also ended up at the same broken page.

So, I attempted to download Java 8 directly from Oracle and  install install it.  The install worked fine, but IntelliJ 14 still did not open.  Same error message.

Here’s how I solved it.  Hop into terminal and do this:

$ cd "/Applications/IntelliJ IDEA 14.app/Contents"
$ cp Info.plist Info.plist-orig
   
$ vi Info.plist    # ... any text editor will do

Find the line that says 1.6* and change it to 1.8*.  Save your file, and now go open IntelliJ as normal.

This causes IntelliJ 14 to use Java JDK 8, and all is right with the world.

Where’s my JDK?

Caught in the Java depreciation battle under OS 10.6 and can’t find where the Java Development Kit (JDK) now resides? Here’s a command that will tell you, allowing you to still use InteliJ and other IDEs on OS X.

There’s a lot going on with Java at the moment. Oracle acquires Sun, putting the language in squarely in hands that don’t inspire trust; the same thing happened with MySQL. Meanwhile, the Apache Software Foundation quits the Java SE/EE Executive Committee. And now Apple deprecates Java, and the reason doesn’t appear to be what you’d think.

Starting with OS X 10.6.3 update, developers got caught in the back lash. Things moved on the file system.

Upgrading IntelliJ, the IDE was asking me where my JDK was, as it certainly wasn’t where the software, or I, thought it should be.

You won’t find the location using /Applications/Utilities/Java Preferences.app.

But you can find it with some digging. Thanks to this developer release note from Apple, the following command from Terminal will spew out some XML.

$ /usr/libexec/java_home –xml

Find the dictionary section that has ‘x86_64’ in it, and you’ll find an entry that has a ‘JVMHomePath’ with something like:

/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

You want to provide this full path to the IDE as where the JDK lives.

It’s worth pointing out that Apple recommends that if you install any 3rd party JVMs they should be installed in /Library/Java/JavaVirtualMachines or ~/Library/Java/JavaVirtualMachines.

Reasonable Trial Durations: 30/30/30

I’ve come up with a way for trial software to be fair and recover lost sales opportunities. The secret: 30/30/30.

30/30/30While doing Java development, I was looking for a new IDE for Windows. Naturally, my hunt ended with IntelliJ, with Eclipse and NetBeans close on its heels.

What started the whole chain of thought for me, though, was IntelliJ’s trial period. Frankly, I really respect a company that has enough faith in their products that they let you use them, unencumbered, for a month in order to make an informed purchasing decision.

Oddly enough, though, it wasn’t enough. Allow me to explain.

The purpose behind a trial period is to allow end users to “log enough flight time” with the product that they know whether or not it meets their needs.

And here’s the problem. I have an existing code base of inter-related projects that I need to import into the IDE. And, since this is for work, my schedule is fairly swamped. I can only come up for air to do an evaluation once every week or two just for an hour or so.

What inevitably happens is this: I install the software, validate it installs, then a week or so later, I try to import; it fails, so I table the project until I have more time. A week or two goes by, and I try again, getting closer. Then, when I come up for air and try to get a bit further, the evaluation period is over. I’ve realistically had about less than three hours using the software, and none of it in the IDE writing code.

This happened to me last year as well.

And, what’s the natural conclusion at this point? I don’t know if it will meet my needs or not. Thus, a purchase doesn’t happen.

From marketing’s perspective, they think that the following scenario is the norm: a user downloads the project, tries creating a project, slings a bit of code, gets married to the IDE, and is willing to pay to keep the experience. In fact, I’ve done just this, and I really love IntelliJ.

But, no matter how much love I have for the product, if I can’t move our corporate applications into it from an existing source base, I can’t justify the site-wide purchase. End of story.

Oh sure, I could talk with the kind folks at JetBrains and ask for an extension, and I’m sure they’d give me one.

But that isn’t the point.

Being a software provider myself, I see this as a generic problem. What if I want to produce trial software that’s fair. I can’t have my customers not being able to make a well informed decision for running out of time.

Here’s my solution… 30 days, 30 invocations, 30 hours – Whichever Comes Last

Here’s how it works:

  • You’re guaranteed at least a month of physical time.
  • You’re guaranteed at least 30 invocations.
  • You’re guaranteed at least 30 hours.
  • When all three of the above goals are hit, stop the trial.

Implementing this isn’t be hard at all. It’s also quite fair and balanced.

If you are doing real work, making use of the application for 30 days, then you’re going to quickly chew through the 30 invocations and 30 hours.

If you have just haven’t even tried the software enough, you get 30 attempts.

Finally, the 30 hour rule recognizes if you haven’t had time to actually experience the software.

I’d like to see vendors start taking this approach. It’s a good one, too. It would certainly result in more sales.

Hibernate: Duplicate Mapping and Imports

<GEEK BLOG ENTRY>
I ran into a very frustrating problem this evening, causing me to stay much later than I had intended, and to miss out on some fun socializing event that I was looking forward to. Unfortunately, there was little to no useful information on the Internet as Google was coming up with few and useless results.

I hope this post saves some poor soul from the same fate.

The Problem


I’m using the Hibernate library for persistence with a JBoss EJB using JPA. My code is sprinkled with annotations, my hibernate.cfg.xml file is clean, and I have no *.hbm.xml files. My code compiles. And it runs.

However.

When I try to access something that uses the Hibernate library, I get an odd message about “Duplicate Collection Role Mapping“.

The class in question contained a Set interface and a HashSet implementation for a member.

So, I commented out this container and tried again, hoping to simplify the problem.

This time I was greeted with a “[Mappings] duplicate import” and a “DuplicateMappingException: Duplicate class/entity mapping” set of error messages.

The only related web pages was a handful of archive with people asking similar questions in various online forums.

Almost always these fell into one of three responses:

  1. You’ve got a problem with the mapping element in your hibernate config file.
  2. You’ve got annotations and and class.hbm.xml file doing something wrong.
  3. This is an old bug in JBoss.

None of the symptoms existed in my case.

Here’s How I Solved It


Turns out that Hibernate makes the recommendation that you build a HibernateUtil helper class. Inside it, you’re supposed to make a singleton of the SessionFactory (and in the case of JBoss, you should use JNDI).

A co-worker had refactored the AnnotationConfiguration() to store a single copy, however, the routine that returned it happened to call .configure() on it before returning it each time. An honest mistake, which got integrated silently into my code when I pulled the latest version from version control.

Because .configure() was being called twice, to Hibernate it did look as if I had duplicate mapping directives in my hibernate config file.

Correcting the HibernateUtil method, which handled setting up and returning the AnnotationConfiguration solved the problem.

</GEEK BLOG ENTRY>

Hibernate: No Persistance Provider

While working through a code sample in Java Persistence with Hibernate, I ran into a problem where Hibernate was reporting No Persistence Provider. Solved the problem, and it wasn’t moving the persistence.xml file as you’d normally find on the web as the solution.

I’ve been spending a lot of time with Hibernate, an ORM persistence manager.

After ripping Pro Hibernate 3 a new one with a scathing review, I finally have concluded that the best book on Hibernate is Java Persistence with Hibernate, which is revised edition of Hibernate In Action, though you’ll still need to reference the ERRATA for Java Persistence with Hibernate on occasion.

In the middle of page 76 it was time to go build my sample application, and all I got was a strange message that said: javax.persistence.PersistenceException: No Persistence provider for EntityManager named helloworld


Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named helloworld
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)

Most of the discussions on the Web lead to the conclusion that the file persistence.xml is missing, or if it isn’t, it hasn’t been placed in the META-INF directory. In my case it was present, it was in the right place, and it was correct. What gives? Seems other people were having this problem as well.

The Solution
Thanks to a szermierz‘s entry on the introductory page An Introduction to Java Persistence for Client-Side Developers, which is actually a great article itself, it got me to question what libraries I had in my classpath, and whether or not that list was complete.

Turns out there was one file he listed that I didn’t have: hibernate-entitymanager.jar.

Looks important, eh?


I easily found a copy in the Hibernate Extensions at HibernateExt\tools\lib\testlibs.
There was also a copy in the Hibernate Tools at HibernateTools-3.2.0b9a\plugins\org.hibernate.exlipse_3.2.0.beta9a\lib\annotations.

Once I placed a copy in there, things worked great. So it’s not just the property file, but the .jar file that needs it.

Unused local variables, a gotcha that’ll getcha

Removing unused local variables from your programs is actually quite safe, makes your code more readable, and helps get faster compiler times, and can even help produce a tighter, faster, more optimized executable. However, there’s one thing you really need to watch out for…

Recently I attended the No Fluff Just Stuff conference again and learned about a free, fantastic static code analyzer for Java, called PMD. It can use be used standalone or even integrated into many popular IDEs like NetBeans or Eclipse. For the curious, I’d tell you what PMD stands for, but no one really knows; worse yet, I can’t stop myself from typing PDM.

PMD has a nifty rule that allows it to locate Unused Local Variables.

Very quickly I was able to walk through our entire code base, identify things that were assigned to, and subsequently not used, and remove them.

Gotcha #0
The first major hit of the day is that you’ll want to do a Clean on your project before you start. Believe it or not, some project building steps can build intermediate .java, files from your master source code. Problem is, if they appear anywhere inside your project’s directory structure when PMD is making the sweep, they get analyzed to. And you don’t want that.

Gotcha #1
It turns out that there’s a reverse ripple effect in performing this kind of code cleanup and operation. After you’ve removed code, you’ll want to make sure you perform subsequent passes until all concerns are removed.

Take for instance this trivial case:
  B = A;
  C = B;
  // C is unused!

What happens is that once you remove C, it turns out B may no longer be used. Remove B, and it’s even possible A may no longer be used either.

Additionally, this can eventually lead to additional Unused Imports, which dealing with those can also decrease build time.

Gotcha #2 — The Real Evil
Normally, this kind of code clean up is absolutely harmless, although there’s one error of omission that a developer can make which will create problems and cause a silent failure.

Here’s a case where a static code analyzer recommends removing a very important line of code:

boolean doSomething(int x) {
  // Do something very important with x
  return result;
}

...
  boolean result = doSomething( x ); // Do Something Important
  // result not used
...

If the return value from a method isn’t used, then the static analyzer will assume the method doesn’t need to be called, and it will recommend commenting out the line — causing your program to silently break.

This is not a error on the part of the tool!

The error was actually that of the developer for not checking the return results of the method.

To correct the problem with the source code, the developer has three options:

  1. Change the method signature to be of type void.
  2. Throw an exception from the method.
  3. Check the return value of the called method.

Otherwise, the real error is that the method may attempt to do something, fail, and communicate back to the caller than something went wrong, but the caller blindly trusts that things are okay.

If you’re not going to check a return value, you shouldn’t be incurring the overhead of sending one. If the library writer provided one for a reason, then you should be using it.

Conclusion
When a code analyzer makes a recommendation, ask yourself what implied rules about your code the analyzer is assuming. Rather than blaming the tool, the better solution is fixing the source.

It may be best to comment out, rather than deleting, code that initially seems superfluous.

Finally, after a massive code sweep, run those unit tests.

Programming Library Conventions

Java: Readers and Writers work with Unicode Characters, while Input and Output work with raw bytes.

A side study of mine is how developers write (and organize) libraries and then [inadequately] document them.

Consistency is a good thing, and while I’ve never seen the following fact explicitly pointed out, it does represent some extra thought on the part of the Java library authors.

With the realization that applications are not just for USA English speakers, Unicode support is becoming mandatory. Standard ASCII bytes allows for 256 characters, but Unicode supports everything, including foreign characters.

Java’s strings use Unicode characters, not bytes, although we all know a Unicode character is represented by a sequence of one or more bytes. This is why the storage size of the representation is not necessarily the same as the string’s length.

With the Java libraries, anything that talks about Readers and Writers is working with content in terms of Characters.

Anything that talks about Input and Output is working with content in terms of raw bytes.

Knowing that is how the library is sliced up makes it much easier to find the routine you’re looking for.

Java EE in a nutshell for total newbies

Someone just jumping into Java may look at the SDK and the EE and wonder why they aren’t included together or why one version seems always behind the times. This article explains to the Java newbie what J2EE (or now Java EE 5) really is in terms a procedural programmer might understand.

One of the biggest hurdles in getting a procedural developer to even try an object-oriented language is to break a bunch of misconceptions. Perhaps the largest one has to do with language syntax. When a procedural person sees something that looks like a structure with code in it, they instantly think that each structure “carries” its own copy of the code around with it — which is clearly inefficient.

Once you explain that, no, there is only one place the code exists, and that the notation is defining scope, not structure, it becomes obvious how the compiler is accomplishing its magic. In fact, it’s quite trivial, impressive, and elegant.

In some ways, I wish someone had explained to me long ago what was up with selecting a Java environment, because Java loves to rename itself, bust its environments into pieces, invent new terminology for old things, and in general make a whole confusing mess to anyone who didn’t come along for the ride since day one. I’m about to explain to non-Java newbies just what J2EE / Java EE is in a simple matter you could explain to your grandmother. Assuming, of course, your grandmother wrote code.

If you hop over to the java site and poke around, you’ll see on the right hand side three things: the JRE, the SDK, and something called EE.

Let’s recap. JRE is the runtime environment, it’s for when you want to run programs, but have no need to compile them. The JDK (Java Development Kit) got renamed to the SDK (Software Development Kit) when more than just the Java compiler got packaged with it. Java, Java 2, and Java 5 are all the result of marketing names, having some relationship to the actual version number scheme: v1.2 is Java 2, but so is v1.3, v1.4. Java 5 is v1.5. Thanks Sun, this isn’t helping.

But what is EE, the Enterprise Edition? What does Enterprise mean? What is business logic? Why is it different than the SDK? Why isn’t it included with the JDK? What’s up with a client piece and a server piece? Why is it always seemingly a version or so behind the SDK? And, why, oh why, can’t Sun just give me one huge thing to download with everything in it?!?

To date, I’ve seen no one give clear cut answers to the above. And I’m about to. And the reason you don’t have those answers is because if you’re asking those questions, then you’ve got some serious misconceptions about what’s going on. Don’t blame yourself though, often people who want to be part of something exclusive make things seem more complicated than it really is and then disguise that fact with strange terminology. All is about to be clear.

The primary misconception is that the SDK is what you use to develop client applications, and that the EE version is what you use to develop server applications. Now anyone who’s done any socket programming will totally roll their eyes at the fact that the library has been split depending on which side initiated the connection, and they’ll do it in much the same way as someone who looks at a object oriented class does when they erroneously think code is being put in a structure.

What’s happened is that the terms client and server have been changed out from under you without warning. And, happily, the SDK is capable of doing both the client and server side of a socket connection. That’s not what EE is about.

J2EE (the Java 2 version) and Java EE 5 (the Java 5 version) are nothing more than specifications. That’s right, concepts on paper.

Let’s go back for just a second and look at some of those other fancy words.
Enterprise = a service or application should be scalable and distributable
Business Logic = code …that’s right… just code, like you’ve always written

Now you’re smart, you could write a framework for your application that would use threads, thread pools, data marshaling between systems, load balancers, and so forth. But that wouldn’t be getting the real work done, that’s just the infrastructure. Let’s face it, if you use C++ you use the Standard Template Libraries; if you do encryption, you don’t roll your own data structures and algorithms. Why should you? Domain experts with tons of field experience have carefully crafted highly optimized and well tested code for you. There’s no reason to re-invent the wheel, especially when there are people dedicated to building, maintaining, and improving the best wheels out there.

An application server is a running environment that dynamically loads classes, and provides scalable and distributable services laid out in the specification.

Java Enterprise Edition is the set of library classes that converse with an implementation of an application server that is compliant. In short, it’s programming by contract, just like everything else. Because there are several specification versions, there are several EE environments. Because EE is a large set of additional classes, you don’t need them if you are not running an application server that you need to talk to. Grabbing the Java EE will get you the SDK – all of it.

Now, here’s the catch. Because more people use the SDK than the EE, you’ll see patches and minor version updates for the SDK before you see that SDK pre-bundled with the Enterprise Edition. Nothing stops you from grabbing EE and snagging the latest patched SDK.

So, in order to run the Java enterprise environment, you need four things: 1) The compiler and tools of the SDK. 2) An application server like JBoss or the Sun Java System Application Server. 3) The Java EE application interfaces that are conforming to the application server you intend on running. 4) A clear understanding the services your application provides in addition to how to configure, start, stop, and deploy Java code that you write to it.

NetBeans, Suns interactive development environment (IDE), has a bundle that includes the IDE, the SDK, the EE, an application server (JBoss), and will install it and configure it for you.

So, to summarize: Java EE are additional classes that let you converse with an application server, which is a separate program that is compliant to a Java EE specification. The majority of people don’t use enterprise services for regular programs, and those that do need to have a class library that matches the application server they’ve elected to use — as such, it is not bloat or complexity that keeps it out of the JDK, but that putting one in can be problematic if there is a mismatch with the ‘server’ end of things.

Curious now as to what Java EE provides?

Well, it handles .JSP pages (like PHP allows scripting in web pages, instead the language used is Java). It handles Servlets (programs that respond to POST and GET requests), which is actually what a .JSP turns into if you think about it. It handles JavaBeans (classes with agreed upon properties, called interfaces, that let them be manipulated by a graphical IDE); it handles Enterprise JavaBeans that allow your code’s classes to run in a distributed manner — and, yes, it was horrible to name it so similar. It has naming services to find your code, no matter which machine it’s on. It can handle concurrency, scalability, transactions, logging, message queues, security policies, database connectivity and pooling, persistence and mapping of objects to relational databases, and so forth. …everything you could write yourself, but benefit from not having to.

Subversion: Obstruction and NetBeans

Using NetBeans, I ran into a problem with subversion, getting a mysterious obstruction error message. Here’s what’s going on, and how to fix it. Java developers using subversion need to know about this; it’ll save you from ripping your hair out.

Had an interesting case come up, as I’m using JBoss 4.0.4 GA with NetBeans 5.5 Beta 2, which effectively gives me a J2EE environment in which I can run my Enterprise JavaBeans, which happen to be using the EJB3 standard.

The problem that I ran into was when checking my source code into Subversion, as I was getting an obstruction error message during an SVN Commit. When asked to perform a Clean Up, that didn’t help rectify the problem.

Here’s what was going on, and how to fix it.

Subversion stores in the versioned directories a hidden directory of its own called .svn which is used to record the meta-data of what’s in that folder. Before you can check in anything to the repository, you must be up to date with it. Subversion doesn’t want you, or anyone else, to lose data, especially during an update.

Normally with development environments like VisualStudio, a set of directories is created (such as obj, bin, Debug, and Release); these are directories you may want to preserve the directory structure of in version control, but not the contents of those directories. In general, compiler auto-generated content or transient files don’t belong in version control, as these files are usually binary and often big, wasting space.

NetBeans creates a build and dist directories for Java projects. And, while it may seem safe to check these into subversion, it is not.

If you were to check in the build directory, even if you ignored the contents, subversion has to keep track of what’s going on and created its hidden .svn directory inside it.

However, when NetBeans does a Clean and Rebuild, instead of erasing the directory’s contents, it deletes the whole directory and recreates it. Anything inside that directory is lost forever, including the .svn directory.

Now when you go to do a Subversion Check In, it sees the directory exists, but it doesn’t see its .svn file. Subversion thinks you accidently deleted its directory and recreated another directory with new content in it by the same name! Hence, you’ve obscured it.

Clean Up is going to fail as well, as there’s no .svn directory to twiddle. You’re at a standstill until you correct the problem.

Doing so is easy.

  1. Get rid of the offending directory – delete it, move it, whatever.
  2. Perform a svn update to get yourself in sync with what’s in version control.
  3. Right click and do a SVN Delete… on the offending files and directories.
  4. Perform a commit, which saves the state that those do not belong in version control.
  5. Open your development environment and do a Clean / Build, recreating the problematic directories – not to worry, they are not in version control
  6. Perform another commit, however this time select all the files and directories that don’t belong and ignore them (right click, it’s in the pop-up); repeat until you have the smallest set of top level directories.
  7. Let the commit happen, recording the fact you do not want version those directories in the future.

At this point you should be good. Subversion won’t save them, and NetBeans will delete and recreate them without stomping on Subversion’s meta data.

Unable to locate TOOLS.JAR

Got a message that Ant couldn’t locate tools.jar, and for a second it confused me. Turns out I had just upgraded Java and hadn’t updated the JAVA_HOME environment variable. In the process, found a nifty little guide about how to set up Ant for new users. Very well written.

Was playing with ant today and started getting a message saying it was unable to locate tools.jar, which normally sits in Java’s lib directory.

Silly me. I had changed java versions recently and needed to update my JAVA_HOME environment variable.

Here’s an excellent resource for setting up ant if you’ve never done so: http://www.j2x.ca/developer/other_docs/ant_beginner_tidy.php