Archive

Posts Tagged ‘Java’

Java 6 and Maven on Mac OS X Leopard

August 12, 2009 3 comments

This morning I was having problems with Java and Maven on my Mac. I had my JAVA_HOME set to /Library/Java/Home, which was pointing to Java 6. When I ran mvn -v, Maven told me it was pointing to Java 5. I couldn’t figure out what was wrong because running java -version showed me Java 6.

The solution, which I found in this post, was to set my JAVA_HOME to the actual place where Java is installed, which is something like:

/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home

This worked for me, but YMMV.

Advertisements
Tags: , ,

How to use Groovy without management finding out

November 20, 2008 5 comments

I hang out with Ruby guys and gals when I can. These folks are such a blessing to my brain. If you don’t have Ruby friends, find some. Google for “yourcity ruby brigade” to find a Ruby user group in your area.

I’ve often heard Ruby friends talk about utilities they wrote in Ruby that essentially generate boilerplate Java code, and I used to shudder at the thought.

I always figured “You have a great language that can do so many yummy things, why are you using it to write icky code!?”

I think I’m beginning to understand now: The icky language (sorry for the blasphemy, but yes, I mean Java) runs faster. It’s also more likely to be accepted by the governors in your projects. If you don’t know what I mean by governors, they’re the poor folks that take the heat and lose bonuses when stupid geeky experiments with unproven technologies ruin a project. These folks love the status quo. And bonuses. Your geeky technologies pose a threat to both.

Groovy noobs and doubters ask “How can I get management to approve using Groovy in my project?” Well, you can write Groovy scripts that no one needs to know about. Write scripts that generate Java code.

I’m not completely off my rocker.

Grails does some cool code generation to write Groovy views and controllers based on your tiny li’l POGO domain classes. It’s so awesome not to have to write boilerplate code or have to start everything from scratch. I can literally create an entire CRUD webapp in a couple minutes, even with a couple beers in me (which, for the record, only happens at home on my own time – I swear). Why code generation is awesome: Doing tedious code manually from scratch is like a coding limbo… never really touching heaven or hell but it passes the time.

Code generation good. Hulk like code generation. Tedious code make Hulk angry! Hulk smash!!!!!

Just to play around and set my first goal low, I challenged myself to write a Groovy script that creates a Java constructor. All my favorite IDEs do this for me already, but I’m not going to let practicality get in the way of fun… certainly not when I’m coding on my own time at home! Time to play!!!

class Person{
  private String firstName;
  private String lastName;
  private int age;
}

void constructor(Class clazz){
  def props = clazz.properties.declaredFields.findAll{
    // filter out the properties I do not want
    !it.toString().contains("static") &&
    !it.toString().contains("metaClass")
  }.collect{
    // I want the property type and name
    [it.type.toString().split()[-1].replaceAll('java.lang.',''), it.name]
  }
  // dump out the constructor!!! yay!!!
  print " public ${clazz.name}("
  print props.collect{"${it[0]} ${it[1]}"}.join(', ')
  println "){"
  props.each{ println " this.${it[1]} = ${it[1]};"}
  println " }"
}

 

constructor(Person)

All I have to do is paste in a new class definition like I did with the Person class and call my dandy new constructor() method, passing to it the name of my class. In Groovy I don’t have to say Person.getClass() or even Person.class – just plain ol’ Person is good enough.

My console dumps out:
  public Person(String firstName, String lastName, int age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

Not too shabby.

Keep in mind the DRY principle. Your first priority is to write Java code without any duplication. In most cases you can avoid duplication by simply following basic OO principles.

If, however, boilerplate code seems like a necessity, consider generating it.

The Executor Framework

November 8, 2008 7 comments

It’s great. It allows you to handle concurrency in Java (or Groovy) without directly using the Thread class.

I first heard about the executor framework in Effective Java (Second Edition) (Item 68: Prefer executors and tasks to threads) and became really interested in it, decided to investigate further, and gave a presentation on it for my coworkers.

The Executors class (new in Java 5) provides a bunch of static factory methods for creating executors. With an executor, you can submit a task (Runnable or Callable) that will be performed by that executor. Here’s an example:

ExecutorService executor =
    Executors.newSingleThreadExecutor();
executor.execute(runnable);
executor.shutdown();

As you can probably guess, this will create an executor which has a single thread. That thread will take the runnable and call its run() method. If the execute method is called multiple times, each runnable that’s passed in to the method will be placed on a queue. When the executor’s thread is available, it’ll pull the first runnable off the queue and run it. When that one finishes, it’ll grab the next one, and so on.

If a single thread isn’t enough, you can do the following:

ExecutorService executor = Executors.newFixedThreadPool(5);
for (Runnable runnable : runnables) {
    executor.execute(runnable);
}
executor.shutdown();

This would create a thread pool with 5 threads that can execute the runnables. Again, the execute method places each of the runnables on a queue, and whenever one of the 5 threads is available, it pulls the runnable off the queue and runs it. That’s it! It’s so simple.

If you want to schedule your tasks to run at certain intervals, you can do this:

ScheduledExecutorService executor =
    Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);
executor.shutdown();

This will submit a task to be executed every minute. The single thread in the executor will run the task right away, and then again every minute. The ‘0’ above indicates the initialDelay – that is, the number of units to wait before the first invocation of the runnable. The ‘1’ indicates the number of units between each invocation of the runnable. And, of course, TimeUnit.MINUTES indicates that the units for the ‘0’ an ‘1’ should be minutes.

If you’re using Groovy, it’s even easier because you don’t have to implement Runnable – you can just pass a closure to the executor (since Closure implements Runnable).

There’s no longer a reason to create threads directly in Java. The language now provides an easy way for you to run tasks in separate threads without having to micromanage them.

JavaOne Recap II

June 16, 2008 Leave a comment

This is part 2 of 2 of my experience at JavaOne 2008. In my first post, I wrote about coming features in the next versions of Java SE, EE and JSF. In this one, I’ll write about notes I took concerning JavaFX, Project Hydrazine, jMaki, NetBeans, and Scala.

JavaFX

JavaFX got a lot of attention by Sun this year and IDE support is supposed to be here now in Netbeans. I have to say though walking around the conference, the vibe was a little cynical and skeptical about JavaFX. Some of the negative comments I heard concerned the immaturity of IDE support, complaints about the syntax, and questions about competition from Silverlight and Flex.

Project Hydrazine

Project hydrazine seems to be Sun’s product in the whole cloud computing bandwagon. They talked about it, but didn’t really elaborate on it in any detail. The hydrazine marketing site is here.

jMaki

I heard a lot of buzz about this amongst the crowd. It sounded pretty cool. So yes, it’s yet another Javascript library to learn, but the difference is jMaki doesn’t try to re-invent the wheel, but uses multiple Javascript libraries to provide you with one interface to use the features of any of them. You could theoretically combine the features you like in dojo with the things you like in YUI and use only one, jMaki interface.

Netbeans

Netbeans was the IDE of choice for the Hands-On-Labs. I’ve never been a big fan of the Netbeans IDE’s in the past, because despite whatever features they might have had, it always seem rather slow and clucky to me. But it ran stellar during the labs. It had many of the same features I see in Eclipse and Intellij. It’s definitely on par with them. They showcased the javascript support at the conference. It was really good! Much better than I’ve seen in Intellij and Eclipse.

Scala

A lot of buzz around this. There was some unofficial talk about it as a possible replacement for the Java Language (i.e. Java 3). If you haven’t heard about Scala before, it’s a language with similar syntax to Java. It’s often described as both an Object Oriented and a Functional programming language.

JavaOne Recap

May 13, 2008 1 comment

I had the opportunity to attend Java One this year! What follows is part 1 of a 2 part post describing my experience and things I learned.

The Theme

Sun was really pushing JavaFX and Mobile device development this year, although I’ve heard that the mobile push is every year. Netbeans and Glassfish got a lot of attention. Scala was unofficially talked about by some as a potential Java 3 language candidate.

Topics of Interest

Some of the topics and news I found interesting are listed below.

Coming in Java EE 6

  • Reduction of the amount of XML you need to put in your deployment descriptor.
  • Support for annotations for your filters, servlets and listeners. My assumption is that this will facilitate the reduction in XML configuration you need to write. A great side affect of this should be when you want to use any of the numerous web MVC frameworks out there, you should only need to plop the jar in your classpath (WEB-INF/lib) folder and be up and running without the need for web.xml changes.
  • JAX-RS – An API for implementing restful WebServices.
  • Scripting is “going to be treated as a first class citizen” (Not sure what that means really).

Coming in Java SE 7

  • Concept of modules or superpackages to wrap your code for organization, versioning support, and better information hiding than private/protected scoping gives you. See JSR’s 277 and 294 for more information. (Perhaps Groovy could benefit from this :P )
  • Sun says Applets are coming back, that they’re able to shrink the JVM to around 4.5mb, and that the cold start-up time for Applets will be equally as fast (or slow ;) ) as a warm start.
  • One really cool feature they demonstrated of applets is that you can drag and drop them onto the desktop now while they’re running and they’ll run outside of the browser.

Coming in JSF 2.0

The following came from a talk from Ed Burns and another gentleman from Sun on JSF 2.0 where the first 30 minutes they talked a lot about how JSF adoption is steadily increasing and how they’ve listened to the community, understand the pain points, and will improve JSF in version 2.0 of the spec. Some of the specific improvements/changes mentioned were:

  • Better IDE support. (Not sure if this means they’ll release plugins for the major IDE’s or what)
  • Facelets will be part of the spec.
  • JSF Unit will better support testing.
  • Faces Trace will help testing.
  • Integration with Seam and Spring Web Flow. (Not sure how they mean and I haven’t used either of these, though I know the basic concept of what they are/do).
  • Will simplify custom component creation by reducing the number of artifacts you have to produce.

Mobile Device Programming

  • There were plenty of technical sessions on Mobile device API’s for communication, geolocation, etc., but most of the subject material of those were over my head so I haven’t summarized them here. I found those talks very enjoyable though.

Experience

I had a great time at Java One and would like to go back in a few years!

It’s not a conference to go to every year. I didn’t learn as much as I would have at a NFJS conference, but I got a broader range of information about the Java platform and where it’s heading and a great opportunity to meet others.

In part 2 of this post I’ll have notes on JavaFX, Project Hydrazine, jMaki, Netbeans and Scala.