Fixing WebContent Problems in Eclipse

By default, a ‘Dynamic Web Application’ project in Eclipse will put the non-code resources (pages, WEB-INF, META-INF, etc.) in a folder under the project called WebContent.

Exporting .war files or publishing to a server works just fine, as Eclipse knows what WebContent represents, and what should be done in order to deploy it.

The trouble comes when you want to create a new WebContent folder (which you might want to do if you’re going to start using Maven as a build tool on an existing project – Eclipse no longer knows where the resources are and your exports stop working.

If you end up in this situation, you can fix it if you know where in the Eclipse config the declaration of WebContent is. Problematic if you deleted the old WebContent folder already as the declaration gets tidied up (by my experience anyway).

The fix is very simple. Say you want to declare /src/main/webapp as your new WebContent folder
1. Open the .settings folder under the project (if you can’t see it in the Project Explorer view, use the Navigator view)

2. Open the file org.eclipse.wst.common.component

3. In the wb-module tag, add a new entry as follows:


Here’s an example of a basic file to put that into context.



    
        
        
        
        
    

No Building Web Applications

I tried the first couple of weeks of the Building Web Applications, but I won’t be continuing with the module.

I was hoping that there’d be some deep insight into the pros and cons of the Java web applications and the JSF framework and RESTful Web Services, but it was pretty clear that we weren’t going to cover enough ground to make the course worthwhile. There’s also some pretty idiosyncratic approaches to writing Java code going on too, so it was all a bit strange.

I could have carried on through the module as it should have been easy to get a good grade but then I’m doing the course for the challenge and opportunities to learn more than for the letters after my name. It’d be a shame to lose out on learning something else.

The software engineering modules have been a little disappointing, to be honest – where I found the Computer Science modules assumed a challenging knowledge of maths and computing, the software engineering modules seem to assume little or no prior knowledge. Maybe that’s just my perception, having been working on-and-off in software development for the past 4-5 years.

On the bright side, I did get a lead on what looks like an excellent book to get stuck into JSF 1.2 in Core JavaServer Faces by Geary and Horstmann.

That means that I just need to revise the Patterns for e-Business course foe this set of exams. In Autumn I’ll continue with Computer Science modules and it’ll be once more unto the breach with the whole logic thing, so I’ve pulled a couple of books out of the library to get started with that again.

Studying for SCJP?

I was recently quizzed about prep for the Sun Certified Java Programmer exam, so here’s a quick rundown of the resources I found useful and tips I picked up when I was studying for SCJP 5. All in, it cost me around £200 and took just under four months. I can recommend the following resources:

  • SCJP 5 Study Guide by Kathy Sierra and Bert Bates. Choose the book for the certification version you’re going for. Work through every chapter and make sure you understand every concept and gain some familiarity with the APIs. I found flash-cards (little cards, questions on one side, answers on the other) invaluable for really burning some of the more difficult to remember stuff. As I didn’t have a programming or Computer Science background, I learnt more about Object-Oriented concepts and programming in the first three chapters of this book than I did from anywhere else.
  • javaranch.com SCJP FAQ for the latest thoughts info on certification, and the SCJP Certification Forum, in which you’ll start by asking questions and wind up answering the questions of others as you get lined up for the exam. The FAQ is also a good place to check what the recent exam takers are saying about the exam and the study materials. You can also use the Rules Roundups to get a feel for answering questions, although they’re pretty easy compared to the exam.
  • Mock exams. When you think you’re nearly ready for the exam, grab a pack of mock tests (I used whizlabs). I certainly wasn’t as ready as I thought I was! Do them properly – set aside at least an hour and try and work as if under exam conditions – you also get used the format of the exams and there’s a few tricky corner cases in the mock exams I did that are worth knowing about.
  • Sign up for your exam at prometric.com. I signed up for the exam as soon as I’d finished reading the Study Guide, because I’m fundamentally lazy and needed the impending deadline! If you do the same, you might want to give yourself a month or two between booking and exam day to do those mocks and deal with any gaps in your knowledge they throw up.

I’ve also got a couple of tips on techniques to use for answering some of the tricker exam questions – that can also come in useful when writing and debugging code.

First up, the exam will often have a code sample and ask you to choose from a number of options. ‘Does not Compile’ is almost always an option, and it kept catching me out at first. The way I dealt with it was to run through the sample twice – first as the compiler, looking for those errors that would prevent the code compiling in the first place. Only if that first check didn’t throw up any problems do you need to imagine the behaviour of the code as it runs and look for exceptions and results.

Second, come up with some way of sketching the changing references to objects as you work through a code sample. This’ll help you catch subtle re-assignments you might miss working it through mentally.

It’ll take up your time. I was probably spending about 5-10 hours a week learning, revising and writing code for those four months – that counts when you’re working full time. It’s worth it though, particularly if you’re an inexperienced Java programmer. It’ll make you aware of some of the principles and practises you should be thinking about and it’ll give you something of a guided tour of the core Java APIs.

If you going to go for this cert, good luck!

Pattern-Based Software Dev – Day 5

Day 5 was largely a revision day in the lecture and continuing with coursework in the labs.

As I’m not based in Manchester, we’ve had to make alternative arrangements to submit the coursework. The spec asks for submission on paper, with a cover sheet signed by the team members. I find this a little strange, given that this is Computer Science course. It’s also extremely inconvenient for me, as I don’t live in Manchester and I work full time. As such, we’ve made alternative arrangements and I’ll e-mail a copy of the report in lieu of my signature.

It’s been a funny course. Looking forward to reviewing this material, if you’re interested the e-Business patterns site is on developerworks.

When Eclipse Plugins Don’t

Quick Version

If, after ‘installing’ a plugin for Eclipse 3.4 it’s not visible in Preferences or in context menus, check that your user account has permissions to write into the appropriate Eclipse directories – because Eclipse doesn’t warn you.

Preamble

For those who don’t know, Eclipse is an IDE heavily used for Java development. Like anything else, it’s a delicate balance of awesome and suckage, and today I got caught out by a pinch of suckage.

It’s a plugin-based platform, which means that anyone can write a piece of software that ‘plugs-in’ to Eclipse to extend or enhance the functionality. It’s a great approach, allowing me to tailor my own installation to my needs. Having recently re-installed Ubuntu Linux, earlier today I was trying to set up my plugins without success.

The Problem

I set up the m2eclipse update site as described in the documentation (pretty standard fare… Help > Install New Software…, paste in the update site URL and choose components to install) but after ‘installation’ was completed there was no sign of the plugin. There should have been new options appearing all over Eclipse, but no. Tumbleweed.

Tried installing the next plugin on my list… Subclipse. Same story. So not a problem with a plugin…

The Solution

…and then it dawned on me. I’d installed Eclipse into /opt, which is all locked down to root, with administrative privileges. Schoolboy error – no permissions for the plugin files to actually be installed under the authority of my user account, which is the context that Eclipse normally runs.

A quick chown to root:admin for the /opt/eclipse directory (rather heavy handed – I should probably have worked out which directories I needed write access to, but I was out of patience), ‘uninstalled’ the plugin in the Eclipse, tried the install again and then I was back in business.

I’m really surprised that Eclipse doesn’t complain when it’s ‘installing’ a plugin in directories to which it has no access. I may not be the sharpest tool in the box, but I’m fairly sure that permissions problems happen to other people too. I might go so far as to find out where you feed back to the Eclipse development community for once. Anyways, this post will help remind me next time I get this wrong, it might help someone out, and if nothing else you might be mildly entertained by my ineptitude.

Perl is slower and faster than Java

Bit of a random one coming up…

I needed to get an measure of the difference in performance between Perl and Java for a simple client application, so I wrote the traditional ‘Hello World’ app in both and ran a bunch of executions averaging over the time from start to end of execution. The net result:

Perl is around 34 times faster than Java.

Really? I thought Java was supposed to be fast? In fact, Dhananjay Nene talked about how comparatively fast a selection of languages – including Java – were on his blog, and cwilbur ‘s comments suggest that in that experiment:

Java is around 100 times faster than Perl.

So how can these two conflicting results both be true? I’m sure you’ve already figured it out, but I’m going to tell you anyway.

Java code takes hundreds of milliseconds to start up, because Java code runs in the Java Virtual Machine which needs a little time to get itself ready before your code can run. Once it’s up, however, you can get performance close to (or even better than, in reality) that of typical C++. [edit – originally no supporting evidence was offered. My sources for this statement on Java vs. C++ are resources like http://scribblethink.org/Computer/javaCbenchmark.html like https://www.theserverside.com/opinion/Is-Java-slow-Compared-to-C-its-faster-than-you-think. Personally, I have very limited hobbyist experience of C and C++ many years out of date now]

On the other hand, Perl doesn’t need that environment and so can start faster but trades off more overhead at runtime, meaning slower running performance.

Just goes to show, application performance is another area where there’s no one right answer – it’s about choosing the right tool for the job – I don’t think there’s any way round these performance characteristics without cheating.

Stackoverflow Blog Podcast

Back in September, I blogged about how I’ve become a podcast addict. I said I’d follow up with short posts on the podcasts I listen to and why I give some of the precious little time I have to listen to them. I look forward to the stackoverflow blog podcast each week, so here’s why.

blog.stackoverflow.comThe Feed

Joel Spolsky (joelonsoftware.com, Fog Creek) and Jeff Atwood (codinghorror.com) started up the stackoverflow.com programmer’s Question and Answer site in 2008 and they’ve been running a podcast in which they talk about the site, the community that’s built up around it, software development and whatever else they feel like talking about.

Topics and Focus

The Stackoverflow.com Site

The design of the site and the decisions that the team made back then, and how those decisions have played out from the private beta to a site with over a million pageviews per day. I’ve not seen anywhere else you can get this kind of insight into a real project.

The Stackoverflow Community

From the initial programmer’s site, there’s now serverfault.com (sysadmin Q and A), superuser.com (for the family’s computer expert), meta.stackoverflow.com (Q and A about Q and A), careers.stackoverflow.com (jobs and careers stuff), and stackexchange.com (hosted stackoverflow engine providing Q and A site hosting on a paid-for basis), so there’s a lot of discussion about building and serving communities online.

Interviews

Over the past few months, there have been more episodes with software luminaries from outside the stackoverflow team, talking about what they do and their views on the sites.

The Transcript Wiki

Pretty much every word in every episode has been transcribed by listeners (there’s that community thing in action again), which means that the content can be accessed by search engines and people with impaired hearing.

Frequency

Weekly, only a couple of missed weeks over the life of the podcast.

Audio Quality

Always excellent, very clear and easy to listen to.

What’s Not So Good

Might be tricky to get into if you haven’t been following it, as I think there are a few recurring topics and in-jokes. I don’t think there’s much of that though, so I’d listen to a couple of episodes to give it a go if you’re interested in the topics.

Well, I think that about sums it up, cheers!

Why Java?

I was recently asked, why Java? It’s a great question – exactly why do I choose to learn the Java language?

I gave it some thought and I’ll share what I considered. I’m certainly not saying that what follows is a justification of the Java language in any general context, nor am I any kind of expert. This is just my view, given my circumstances.

It’s Free!

If you want to learn a language you don’t want to be laying out pots of cash up front. It’s likely you’ve got a Java Virtual Machine on your computer right now, and obtaining a development kit to get you started writing software is free and straightforward. Win.

The Java Virtual Machine

You never know when you might need to run that little app you wrote on a Windows host, or a different flavour of UNIX, or even a big ol’ IBM mainframe system – it’s nice to have some confidence that it’s just going to work.

Now, the JVM runs on any platform I can think of. Perhaps in the early days, there was some divergence in different platform implementations of Java (having felt the pain of the slight non-standard nature of the Micro$oft JVM in IE some time ago!) which somewhat hampered the cross-platform claim, these days there’s a suite of compliance tests that a JVM implementation must pass to brand itself Java compatible. That means that I don’t have to worry too much about cross-platform compatibility.

The JVM supports more than just the Java language. Jython, JRuby, Scala, JavaFX, Groovy, Fortress, Clojure… the list is getting ever longer, and there’s even a JVM Languages Summit. So, if you’re using the Java language and find a problem that better solved in another language, it’s perhaps not such a huge leap to get your Java code and your new JRuby code working together. Tim Bray wrote up some nice notes on the language summit here if you’re looking for a little more.

The other trick about the JVM is that your code gets better without you changing it. As new JVMs are released, they include the latest, hottest optimizations that take the software you write and give it go-faster stripes.

Tools and Platforms

Tool support for the Java language is extensive enough that there is generally a choice – for example, there is a choice of many Integrated Development Environments (Eclipse, NetBeans, IntelliJ IDEA to name but three) in which to write your software.

If you’re building ‘Enterprise’ software (whatever that really means!) you have a choice of application servers (WebSphere, JBoss, Jetty, Tomcat, GlassFish…) that all implement the Java Enterprise Edition specification in whole or in part (for example, the open source Tomcat application server supports a stripped-down subset of the spec) you know that any of the application servers should run your software.

With all these things the choices mean that I can choose the implementation with the right strengths and at the right price point for the project in hand.

Learning

Java’s got a lot going for it as a learning language – it seems to be on the syllabus for most computer science degrees. There’s a wealth of online material available for free, including Sun’s own learning trails and Sang Shin’s excellent javapassion.com learning site.

I know that the question of value in professional certification seems to polarize opinion, but there certainly is a certification trail in the Java language that’s not trivial to achieve.

The cost of achieving these certifications is financially quite insignificant, but (certainly for me – I’m sure there’s folks that find this stuff easier) demands a significant amount of time and commitment. The objectives and exam questions are put together by teams of Sun engineers, Java developers and Java instructors, orchestrated by Sun. (Thanks to Bert Bates and javaranch.com for that info!)

Having done a couple of certs myself, I found them to be a very useful useful guided tour of the language and its extensions. I found plenty of useful features and techniques whilst studying that have since steered me clear of errors and wasted time.

The JCP and Standards

New APIs for the Java language happen through the JCP, or Java Community Process. Everyone from from individuals to the largest IT players (IBM, Cisco Systems, Nokia – the members are listed here) are involved, and new standards happen in a publicly visible process of proposal and review.

Don’t believe me? Here’s the latest Java Enterprise Edition spec. See those JSR numbers? They’re the specifications that have been developed, reviewed and approved as part of the JCP.

Libraries

There’s sometimes so much choice of open source Java libraries, it’s hard to know what to choose for a given problem. The Apache Software Foundation hosts loads of open source Java projects, as does Google Code and java.net.

Not that every library is a piece of awesome… but many are. Having lots of choice increases the chances there’ll be something out there that’s already been built and tested and fits the bill. The libraries and APIs I have to use with my language of choice to get things done make a big impact to my productivity.

What – No Discussion of Technical Stuff?

Nope. I reckon it’s rather pointless to try and discuss differences between the capabilities of one language versus another. Anything computable can be computed in any Turing-complete language, which I think covers any language you might seriously approach as a general purpose problem solving platform.

So it’s not about what can or can’t be done – it’s really about what language I can be most effective and productive in. The biggest productivity killer in Java seems to be the boilerplate code necessary to do simple things, but over the last couple of years, strides forward have been made with annotations, for example, to reduce the boilerplate problem.

That’s All Folks

That’s about it, really. There’s plenty of other languages that can lay claim to some of the points I’ve made, but few that can claim them all.

There are other languages I choose for specific jobs (JavaScript for client-side behaviour in web browsers, PERL for sysadmin-type scripts) but my day to day workhorse, and the focus of my learning attention, is Java. For now, at least.

If I’ve missed anything or you disagree, feel free to drop me a comment!

Getting Started with Web Services

You may not know this, but all you need to get started using web services is a web browser. You might have never heard of web services, or assumed it’s too complicated, or maybe you tried it before but had a painful experience – it’s always possible for poor design or implementation to make simple things difficult.

Well, consuming half-decent web services isn’t necessarily difficult. Bear with me for the next 30 seconds of your life and I’ll show you some examples of easy, useful web services APIs.

It’s also probably worth noting that different browsers can behave differently, and I’ve done this stuff in Firefox 3. If the links below don’t work, copy-pasting the link into your browser address bar and hitting return should do the trick.

The Google Maps API

You can use the Google Maps API to turn a postcode into a latitude and longitude. Try it with this link.

http://maps.google.com/maps/geo?q=S51AB+uk&output=csv

Output in your browser:

200,5,53.4332097,-1.4436139

The first and second numbers are related to the query, the second two are the latitude and longitude of the UK postcode ‘S5 1AB’. You can change the postcode and country in your browser address bar – hit return to submit the new address details.

It’s a neat example, because it’s a very simple query and response.

Yahoo Finance

Now, let’s check the stock portfolio.

http://quote.yahoo.com/d/quotes.csv?s=MSFT&f=sl

The output of this one comes back as a Comma Separated Values document, same as the Google Maps example, but it is set up to save the values into a file instead of displaying it on your browser. If you open the file:

"MSFT",23.692,"8/14/2009","4:00pm",+0.072,23.62,23.80,23.51,46331960

So the stock price for Microsoft Corporation was 23.692 at Friday’s close.

Twitter

Next up, twitter. If you’ve never heard of twitter, welcome to Earth. Let’s grab my public timeline.

http://twitter.com/statuses/user_timeline/brabster.xml

The output this time is a little more funky – because what we’ve just requested is much more complex than just a latitude and longitude. You’ll get an XML document back, which is a machine-friendly way of storing complex data. Not so nice for people to look at though, but hey.



  Tue Sep 01 19:07:07 +0000 2009
  3694475261
  @cazm: hate that - if I don't know how come something's fixed I worry about when it's gonna break next!
  <a href="http://sourceforge.net/projects/twitux" rel="nofollow">twitux</a>

  false

  ...

Summary

Mixing and matching the functionality this stuff exposes creates mashups.

Whilst a browser provides a really easy way for us to explore these services, the trick is that it’s easy to write software that invokes services like these and then uses the information in the response, in fact in many languages invoking a service like those above and capturing the response can be done in a single short line of code.

Often, traditional websites that produce nicely human-readable, formatted pages like this one are actually working with APIs like those above behind the scenes.

There’s a whole world of web services APIs out there to play with, for free – and more are coming along all the time.

(Note – these examples will almost certainly break, given enough time, as the services evolve. If you try one and it doesn’t work, please leave me a comment and I’ll get it fixed.)

When Disabling DNS Caching Doesn’t

If you’re going to fiddle with networkaddress.cache.ttl, do it before you touch the network.

I was using the java.net.InetAddress class to resolve IP addresses from DNS names the other day.

I wanted to test my code by manipulating my local system’s ‘hosts’ file, to quickly simulate moving IP addresses around behind a DNS name, so I also set disabled caching the resolved addresses from one call to the next by programmatically setting the networkaddress.cache.ttl Security property to ‘0’. According to the javadocs,

The value [assigned to networkaddress.cache.ttl] is specified as as integer to indicate the number of seconds to cache the successful lookup.

which is true, and everything was peachy – my hosts file changes were immediately picked up.

At first.

I continued to build my code and all of a sudden, the caching came back and the changes I was making in my hosts file were ignored.

By backtracking my changes, I worked out that the breaking change happened when I executed a network call which involved name resolution BEFORE I disabled the cache.

I moved the setting of the property to happen before I touched the network et voila – everything peachy again.

This (feature|problem|bug) is documented in a couple of places when you know what you’re looking for, like here.

And here’s a simple code demo of it in action:

public static void main(String[] args) throws Exception {
  String name = "google.com";

  //lookup(name);

  Security.setProperty("networkaddress.cache.ttl", "0");
  while (true) {
    lookup("google.com");
    Thread.sleep(1000);
  }

  public static void lookup(String name) throws Exception {
    System.out.println(name + ":" + InetAddress.getByName(name).getHostAddress());
  }
}

Running the sample above as-is:
google.com:74.125.127.100
google.com:74.125.67.100
google.com:74.125.127.100
google.com:74.125.67.100
google.com:74.125.127.100

But uncomment the first call to lookup(), and
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100
google.com:74.125.45.100

Cheers,