Sunday Mar 08, 2015

Bach in NetBeans

Notice the "Play" and "Stop" buttons! All this is thanks to LilyPond. Yes, LilyPond generates MIDI files, as well as PDF files. Truly awesome. And the above actually works, I can generate and play Bach in NetBeans. 

The above was generated as described here:

A great resource:

Friday Mar 06, 2015

Rendering Music Notation in PDF Files on the Java Desktop

It turns out to be pretty tricky to render music notation in PDF files in a Java desktop application. The upper part of the image below shows what Apache PDFBox makes of my PDF with music notation, below that you see the correct rendering in Acrobat PDF Reader:

Here's the PDFBox code for the above:

InputStream inputStream;
    try {
        inputStream = FileUtil.toFileObject(pathToPDFFile).getInputStream();
        SwingController controller = new SwingController();
        SwingViewBuilder factory = new SwingViewBuilder(controller);
        JPanel viewerComponentPanel = factory.buildViewerPanel();
        add(viewerComponentPanel, BorderLayout.CENTER);
        controller.openDocument(inputStream, "", "");
    } catch (FileNotFoundException ex) {

Next, let's look at a JavaFX solution, provided by this blog entry:

Possibly I haven't used PDFBox or JPedal-technologies correctly and the problem isn't with these libraries but with my lack of understanding of how to apply them to this scenario. 

So, finally, not having found any other way of achieving my goal, I used LilyPondTool for JEdit:

The above is a PDF generated via LilyPond and rendered in NetBeans via an embedded "DockablePdfViewer", which is based on JPedal, which is also part of LilyPondTools. After adding LilyPondTools as a JAR to my project, as well as JEdit itself, together with quite a few other JARs, the only code I needed to provide myself, turned out to be the following, after a lot of trial and error, in my MultiViewElement:

jEdit.setProperty("options.lilytool.pdf.follow-caret", "true");
DockablePdfViewer dpv = new DockablePdfViewer();
add(dpv, BorderLayout.CENTER);

A couple of sneaky tricks were needed to circumvent JEdit's own protocol for finding images:

@ServiceProvider(service = URLStreamHandlerFactory.class)
public class JEditResourceStreamHandlerFactory implements URLStreamHandlerFactory {
    public URLStreamHandler createURLStreamHandler(String protocol) {
        if (protocol.equals("jeditresource")) {
            return new LilyPondToolHandler();
        return null;
    private static class LilyPondToolHandler extends URLStreamHandler {
        protected URLConnection openConnection(URL u) throws IOException {
            return new LilyPondConnection(u);
    private static class LilyPondConnectionextends URLConnection {
        private ByteArrayInputStream is = null;
        public LilyPondConnection(URL url) throws UnsupportedEncodingException {
            String file = url.getPath().replace("/LilyPondTool.jar!/", "");
            Image image = ImageUtilities.loadImage(file);
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write((RenderedImage) image, "png", os);
                is = new ByteArrayInputStream(os.toByteArray());
            } catch (IOException ex) {
        public void connect() throws IOException {
        public InputStream getInputStream() throws IOException {
            return is;

At the end of the day, I can now display music notation in PDF files in NetBeans IDE. The dependency graph is a bit too impressive though and a lighter solution would be preferable:

One other problem is that not all of the JARs shown above are in a Maven repo, i.e., I have them in my local repo only. 

Since PDF music notation files can be rendered via LilyPond, the basis for a complete LilyPond integration for NetBeans is not inconceivable.

I'm working on that here:

Thursday Mar 05, 2015

Free: Learn How To Use All 50 Java Keywords!

Kai Uwe Pel, who I met at NetBeans Day Netherlands recently, gave me a fantastic tip yesterday.

He told me about a great and free course that fills in any spaces you might have in your basic Java knowledge:

When you go there and log in, for free, you have access to a wonderful starting point or, possibly, a place where you can remind yourself of the basic principles of Java. It won't teach you object orientation and Java programming in general, as Huw Collingbourne's course does so well, but certainly it is excellent in covering the specific thing it covers.

Of course, NetBeans is used from beginning to end:

A fantastic free resource! Get started with it today.

Tuesday Mar 03, 2015

Learn Java, For Real, Thoroughly, With Huw and NetBeans IDE

The two tools you need when learning Java are Huw Collingbourne and NetBeans IDE. Watch this quick screencast on why this is the case:

For this week only, i.e., until Tuesday next week, there's a massive discount:

Once you buy the course (PayPal works brilliantly), you'll get this starting point with heaps of well structured lessons in bite size chunks:

You'll be a Java programmer before you're even aware of it!

Monday Mar 02, 2015

Transcript of "Free Open Source Tools" OTN Virtual Technology Session

The OTN Virtual Technology Sessions have now happened in two timezones, for the Americas and for EMEA. The final edition in the current series is for the APAC timezone, on March 4th, from 9:30 to 13.00 IST.

Read all about it here:

As you can see in the image above, while watching the pre-recorded screencasts, you can chat with moderators, who are generally the people involved in the making of the screencasts. I'm the one who made the screencast for "Free Open Source Tools for Maven, HTML5, IoT, and Java EE" and moderated the session. During the most recent one, for EMEA, there was quite some discussion, i.e., a lot of questions were asked while the screencast was being watched by quite a lot of people. Some wanted to see the transcript because a lot of info was shared. So, here it is! 

  • How much NetBeans costs? 
    It's free! Get it from -- free and open source.

  • Which plugin I need for using Maven in NetBeans? 
    Good question. No plugin needed. NetBeans natively supports Maven. No installation or configuration need.

  • What is "Internet of Things" doing here with JavaEE, Maven, and HTML5? I know internet is hugely connected with web applications but what is the specific reason here?
    Well, these are the key features of NetBeans -- it is a great tool for doing development for IoT, Java EE, Maven, and HTML5. That's why they're all included here, because NetBeans provides great tools for working with all of them, separately, or together.

  • It seems NetBeans is for more than just Java?
    Definitely! There's a special download bundle of NetBeans which is ONLY for doing HTML5 frontend development. All for free, which you can use together with or instead of Sublime or WebStorm. For free.

  • Your NetBeans looks faster and better than mine.
    That's because I'm using the "Dark Look and Feel Themes" plugin and because I have a very small version of NetBeans, which only contains HTML5 frontend tools, get it for free from

  • Everything you mentioned so far is for free. Which products do we have to license?
    Nothing to license. All free. :-) Nothing in or with NetBeans is for any money at all, no licensing, whatever, etc. Free.

  • Bower, Node.js, Angular... what's going on here?! NetBeans has support for all of these? Even test coverage for JavaScript files?
    Yup, you're right, NetBeans is great.

  • Where can we find out more about all of this?

  • At the bottom of your screen it seems you have a browser inside NetBeans?
    Yes, very useful feature -- an embedded browser. I use it all the time.

  • What about MongoDB? Does NetBeans support it?
    There's MongoDB plugins on the Plugin Portal:

  • Does NetBeans have a presence on social media?
    Yes! New tips and tricks every day at,, and many moves at the NetBeans YouTube channel.

  • Where are the NetBeans YouTube videos found?

  • Is NetBeans a good replacement for Eclipse?
    Definitely. The Maven integration in NetBeans is much better than in Eclipse. The HTML5 tools too. For Java EE, there's no better IDE than NetBeans. 

  • Is NetBeans fast?
    For me, it takes 9 seconds to start up the HTML5 distribution of NetBeans. No JDK required for this, only the JRE.

  • How much does the enterprise version of NetBeans cost?
    NetBeans is 100% free. If you ever find yourself giving anyone any money for NetBeans, you can be 100% that you're being ripped off. :-)

  • Can NetBeans be used as an infrastructure for applications, just like Eclipse RCP?
    Yes, definitely. NATO and Boeing and many other organizations use it exactly like that:

Sunday Mar 01, 2015

Why I Am Excited About JDK 8 Update 40

Doing JavaFX development? Take a look at the very clear performance enhancements in JDK 8 Update 40 ( by looking at a new EPUB plugin that's being worked on:

Saturday Feb 28, 2015

Handy HyperlinkProvider

NCX files are XML files with a specific file extension, "ncx", which are part of EPUB, and below you can see that when I hold down the Ctrl-key and move over a "src" attribute in an NCX file, a hyperlink appears, which when clicked opens the referenced file.

The hyperlink code is as follows:

@MimeRegistration(mimeType = "text/ncx+xml", service = HyperlinkProvider.class)
public class NcxHyperlinkProvider implements HyperlinkProvider {

    private static String SRC_IDENTIFIER = "src";
    private String identifier;
    private int targetStart;
    private int targetEnd;

    public boolean isHyperlinkPoint(Document doc, int offset) {
        return verifyState(doc, offset);

    public boolean verifyState(Document doc, int offset) {
        TokenHierarchy hi = TokenHierarchy.get(doc);
        TokenSequence<XMLTokenId> ts = hi.tokenSequence(XMLTokenId.language());
        Token<XMLTokenId> tok = ts.token();
        if (tok != null) {
            int tokOffset = ts.offset();
            switch ( {
                case VALUE:
                    while (ts.movePrevious()) {
                        Token<XMLTokenId> prev = ts.token();
                        switch ( {
                            case ARGUMENT:
                                if (SRC_IDENTIFIER.equals(prev.text().toString())) {
                                    identifier = tok.text().toString();
                                    targetStart = tokOffset;
                                    targetEnd = targetStart + tok.text().length();
                                    return true;
                            case OPERATOR:
                            case EOL:
                            case ERROR:
                            case WS:
                                return false;
                    return false;
            return false;
        return false;

    public int[] getHyperlinkSpan(Document document, int offset) {
        if (verifyState(document, offset)) {
            return new int[]{targetStart, targetEnd};
        } else {
            return null;

    public void performClickAction(Document doc, int offset) {
        identifier = identifier.replaceAll("\"", "");
        FileObject fo = Utilities.actionsGlobalContext().lookup(FileObject.class);
        String path = fo.getParent().getPath();
        File file = new File(path + "/" + identifier);
        if (file.exists() && file.isFile()) {
            try {
            } catch (DataObjectNotFoundException ex) {


All the code:

Friday Feb 27, 2015

From Eclipse to NetBeans

It's kind of hard to tell the difference between the snippets of code below. But they come from two different tools, one of them is NetBeans and the other is Eclipse. I think it's irrelevant to say which is which since the rendering of the font of each is excellent. I'd happily work with font rendered by either of the two different tools below.

By default, the coloring, and other styling, of font in NetBeans looks different to how it looks in Eclipse. That's easy to solve, assuming you find this to be a problem, via this excellent addition to NetBeans:

When switching from Eclipse to NetBeans, it certainly helps a lot if the project you're migrating uses Maven as its build system. Maven-based projects are automatically recognized by NetBeans. NetBeans understands that if a folder contains a 'pom.xml' file, it is a Maven project. Hence there's no import process needed. Instead, you can simply go to File | Open Project to open any folder containing a 'pom.xml' file into NetBeans as a Maven project.

Finally, you'll find this very useful, thanks to Benno Markiewicz, which lets you import Eclipse formatting files into NetBeans and use them to format your files:

Thursday Feb 26, 2015

YouTube: Format Multiple Files in NetBeans IDE

When lines of code in various kinds of files, whether of the same type or different types, are misaligned, you can reformat them (using the formatting rules you have defined in the Options window or the default ones you get out of the box from NetBeans) all at the same time. Whether or not you're using a project, i.e., you could be working with individual files in the Favorites window, reformatting multiple files is easily done. Watch this quick screencast to see how:

Wednesday Feb 25, 2015

Free Open Source Tools for Maven, HTML5, IoT, and Java EE

I took part in another edition of the OTN Virtual Technology Day today. It started with being invited to contribute a screencast to the event, which I made especially for this occasionenabling me to think afresh about what it is exactly that makes NetBeans special and so I focused on Maven, HTML5, Internet of Things, and Java EEand then I also moderated the sessions live, i.e., answered questions that attendees asked while attending the session.

A week or two ago, the event happened in the Americas timezone and today it was the turn for EMEA. From 10.00 to 14.30 today, attendees in the Java track heard from a range of speakers, including Tori Wieldt, Bruno Borges, and Gerrit Grunwald. The "Free Open Source Tools" session looked as follows, click to enlarge, and notice some of the cool questions that were asked while attendees watched the screencast: 

There were several other questions after the above were asked, all really great and enthusiastic. Very nice to get the kind of feedback I'm seeing at these events. 

One more chance for attending the series of screencasts that constitute OTN Virtual Tech Days is for the APAC timezone–on 4 March–from 9:30 to 13:30 IST. Looking forward to seeing even more attendees there! 

The agenda can be viewed here:

Tuesday Feb 24, 2015

From Sublime to NetBeans?

What if Sublime were to be less cool than you thought and what if NetBeans were to be faster than you've assumed it to be? Right-clicking on an HTML file on disk and then opening it into Sublime takes 1 second, while with NetBeans IDE 8.0.2, if you're using the small HTML5 & PHP distribution (which doesn't need the JDK, only the JRE) it takes 9 seconds. Is 8 seconds a very big deal? To me, it sounds like NetBeans is an IDE that is 8 seconds away from being as fast as an editor.

Sure, performance and speed is a lot more than startup time. It's also about how quickly and easily things open and how smoothly you can switch from one task to another. But even here NetBeans has made great strides over recent releases and there's useful plugins like the Sublime feature (in fact, on the NetBeans Plugin Portal there are currently 6 different Sublime plugins) and the One Click Open Sesame feature to make it even more editor-like. Below are two screenshots, on the left of each you see Sublime, on the right you see NetBeans. Click the images to enlarge them and, unless I'm very much mistaken, the difference between them is 8 seconds faster startup time for Sublime, versus heaps of integrated features (which surely are worth waiting 8 seconds for) in NetBeans.

If you haven't tried the small bundle of NetBeans, i.e., the bundle aimed specifically at frontend developers, i.e., the HTML5 & PHP bundle, go here to get it (all free):

One feature I really like in Sublime, and it is also in the JetBrains products, is the multicursor functionality. I.e., you can have more than one cursor, i.e., on multiple lines. Lets you select code in multiple lines and change them at the same time, like rectangular block selection but not limited to a block. Seems like an extremely cool feature to me. However, the question does arise how often one needs that feature versus, for example, code completion for AngularJS directives, with embedded AngularJS documentation, as well as cutting edge KnockoutJS features, and native integration with Git, Gulp, Grunt, Bower, Node.js, Cordova, SASS, LESS, Mocha, Karma, Protractor, and Selenium, as well as integration with the Chrome browser, a library of out-of-the-box samples, and heaps more.

If you're going to respond to this admittedly contentious blog entry, it would really help if you've recently, i.e., over the last 6 months, made heavy use of both Sublime and NetBeans.

Monday Feb 23, 2015

YouTube: Search Everywhere in NetBeans IDE

What do you do when you don't know how to do something in NetBeans IDE? Do you search through random menu items? Do you go to Google and StackOverflow and mailing lists? Do you search through tutorials? What do you do? In this short YouTube clip, you'll learn about a feature you probably didn't know about or might soon look at in a different way.

While making the above, I realized I need to work a bit more on the Key Promoter plugin since not everything of interest I do with the keyboard is currently shown in the toolbar, yet.

Sunday Feb 22, 2015

How to Quickly Create New Java Files

I was looking at the Quick Search field a few days ago with a programmer friend and we were also discussing the New File dialog and how clunky it is to find how to create new Java source files there. So I thought, why not integrate relevant templates from the New File dialog into the Quick Search field?

Here's the result, i.e., notice that when I type "java", I can see (for the first time thanks to this new plugin I created) various Java file templates are available which, when clicked below, cause the relevant New File dialog to appear, all filled out with the values of the currently selected project. If no project is selected, or a file within a project, a message appears informing you of that requirement, since Java files need to be created within projects.

Source code:

Saturday Feb 21, 2015

Greenfoot and NetBeans (Part 2)

Recently I wrote about Greenfoot and NetBeans. Since then, Michael Kölling and his team have been working hard on simplifying the steps of moving a Greenfoot project to NetBeans. I tried out his simplified instructions today, with a build of a new release of Greenfoot, and found that in the previous blog entry, step 4 and 5 are no longer needed.

When you want to open a Greenfoot project into NetBeans, start by using the "Java Project with Existing Sources" wizard (in the New Project wizard, Ctrl-Shift-N) to import the project. For example, the "lunarlander" project, which comes with Greenfoot, looks as follows in NetBeans:

As described in the previous blog entry, you need to put "bluejcore.jar" and "greenfoot.jar" on the classpath of the project, as you can see above.

Next, right-click the project and choose Properties. In the Run tab of the Project Properties dialog, define the following (click to enlarge the screenshot below):

As you can see in the screenshot above, you need to the working directory to the root folder of the project. And, as you can also see above, you need to run "greenfoot.export.GreenfootScenarioMain" with three arguments, with no commas between them:

  • Scenario name.
  • Name of the world class (just the name, no .class extension).
  • Path to the 'greenfoot-labels' file from the Greenfoot installation (lib/english/greenfoot/greenfoot-labels).

Following the above steps, there's no need to create a properties file, which was defined in the previous blog entry, i.e., if the "greenfoot-labels" file is available.

Then run the project and you should see that it works perfectly, no need to fiddle with images and resources either, they're now found automatically:

Friday Feb 20, 2015

Sublime Text and NetBeans

Here's Sublime:

And here's NetBeans:

It pays to have both these tools in your toolbox. Switching between them is no problem. You can have them open at the same time, changes made in one are picked up by the other immediately. NetBeans is certainly significantly more powerful and expressive, look for example at the difference between code completion above.

Note: A common stumbling block is that when front-end developers go to the NetBeans Downloads page, they download the "All" distribution. The smart move is to download the "HTML5 & PHP" distribution instead. It is significantly smaller and lighter. Whenever a front-end developer has mentioned that they find NetBeans to be heavy and resource intensive, it has turned out that the developer was not using the "HTML5 & PHP" distribution. They were either using "Java EE" or "All" instead, both of which are the wrong distribution if you're "only" doing front-end development.

A question you might have is what's the difference in the size on disk of these two tools. Well, let's turn the question around and ask what's the value of having a JavaScript debugger built into your tool for stepping your code? And what's the value of having Git, Mercurial, and Subversion integration and local versioning support built directly into it? Don't you need those tools, and many others just like it, baked into the tool you're using, i.e., tested and naturally fitting into your development tool? Then what's the relevance of one tool taking up more or less space on your disk if in exchange for slightly more disk space you get the tools that you're going to need to install anyway if you're going to use the other tool?

And what's the value of being able to do this:

And this:

And this:

In short, these two are great to use together for frontend development. Want to do some quick editing, use Sublime. Want to do some more comprehensive tasks, e.g., smoothly set up an AngularJS project from scratch and check it into your GitHub repo, in a matter of two or three clicks, and then deploy the app to Android, debugging and styling it live there? Use NetBeans.

Thursday Feb 19, 2015

Tools for Teachers: Key Promoter for NetBeans

I wanted to be able to see the key events I'm typing or pressing in NetBeans IDE. So I created the Key Promoter plugin for NetBeans IDE. Helpful for me, and anyone else, using NetBeans IDE to teach anything at all, or do demos in NetBeans IDE, because the students/audience, whoever they are, can see what you're doing. Seeing the keyboard shortcuts you're doing helps confirm to your audience, and even lets them quickly take note of what you're doing, also because often they won't hear exactly the key combination as you're using it and talking about other things at the same time.

For the first time, the color of the label can now be changed (directly in the toolbar and not in some small place in the Options window), which is handy when you switch between different color schemes, themes, and look and feels.

In the above screenshot, I could potentially be saying: "NetBeans IDE lets you select a block of code across lines when you press Ctrl-Shift-R, as I am doing right now, as you can see in the toolbar, after which a block of code can be selected and changed simultaneously."

Get it here:

Wednesday Feb 18, 2015

Listening to Key Events in NetBeans IDE

Here's how to detect whether the user has pressed Ctrl-Tab. Add the following code within a Runnable annotated with @OnStart, in the "run" method implementation:

KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
keyboardFocusManager.addKeyEventDispatcher(e -> {
  KeyEvent kev = (KeyEvent) e;
  if (kev.getModifiers() == InputEvent.CTRL_MASK && kev.getKeyCode() == KeyEvent.VK_TAB) {
       StatusDisplayer.getDefault().setStatusText("you pressed ctrl-tab");
  return false;

The import statements:

import java.awt.KeyboardFocusManager;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import org.openide.awt.StatusDisplayer;
import org.openide.modules.OnStart;

Monday Feb 16, 2015

Maven and JAXB in NetBeans IDE

Let's take a look at custom binding declarations for JAXB in the context of the Maven JAXB-2 plugin, with NetBeans IDE.

Background reading:

Here's a basic outline of a structure in Maven in NetBeans IDE with a schema file and a binding file:

The schema file, i.e., the 'demo.xsd' file above, is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs=""
           elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="DemoElement">
                <!-- Demo 1: Globalbindings - in this example
                    DemoGlobalBinding1 will be bound to a XMLGregorian (default)
                    while DemoGlobalBinding2 will be bound as a Calendar via
                <xs:element name="DemoGlobalBinding1" type="xs:date" minOccurs="0" />
                <xs:element name="DemoGlobalBinding2" type="xs:dateTime" minOccurs="0" />
                <!-- Demo 2:
                    From the restriction the integer bindings could fit into a
                    java Integer, but as a xs:integer is unbounded, it is by
                    default mapped to a BigDecimal.
                    This demo maps DemoIntegerBinding2 to Integer
                <xs:element name="DemoIntegerBinding1" minOccurs="0">
                        <xs:restriction base="xs:integer">
                            <xs:enumeration value="1" />
                            <xs:enumeration value="2" />
                            <xs:enumeration value="6" />
                            <xs:enumeration value="8" />
                <xs:element name="DemoIntegerBinding2" minOccurs="0">
                        <xs:restriction base="xs:integer">
                            <xs:enumeration value="1" />
                            <xs:enumeration value="2" />
                            <xs:enumeration value="6" />
                            <xs:enumeration value="8" />

The binding file, i.e., the 'demo.xjb' file above, is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings version="2.0"
        <!--    Commented out for demonstration    
    <jaxb:bindings schemaLocation="../wsdl/demo.xsd">
        <!-- by XSD the value range is limited to the integer range so map it there -->
        <jaxb:bindings  node="//xs:element[@name='DemoIntegerBinding2']/xs:simpleType">
            <jaxb:javaType name="Integer" />


Both the above come from NetBeans user Matthias Bläsing, who writes that he extracted the above example from a project at work. The example shows that customization via a JXB binding file has a place outside of SOAP-based web services. For exampe, REST with XML in a client-side project could be an example. The starting point is 'demo.xsd', a fictional XSD file. It contains two examples for customization, which have made Matthias' life considerably easier:

  • Example 1. The default xs:date and xs:dateTime mapping to XMLGregorianCalendar is ugly, so  you can map it to Calendar.
  • Example 2. BigInteger is nice if you need it, but you might want to work with an Integer or int instead.
While 'xjc' correctly recognises <xs:minInclusive> and <xs:maxInclusive>, it fails to do so with enumerations. The 'demo.xsd' file contains two examples of each, one is customized, one is not, so that one can see the difference in the same result class, while 'demo.jxb' contains the customizations.

Now let's use the above files. Start by adding this to your POM:


Build the application and you'll see this:

The content of

package com.mycompany.mavenproject1;

import java.util.Calendar;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class Adapter1 extends XmlAdapter {

    public Calendar unmarshal(String value) {
        return (javax.xml.bind.DatatypeConverter.parseDateTime(value));

    public String marshal(Calendar value) {
        if (value == null) {
            return null;
        return (javax.xml.bind.DatatypeConverter.printDateTime(value));


The content of

package com.mycompany.mavenproject1;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class Adapter2 extends XmlAdapter {

    public Integer unmarshal(String value) {
        return new Integer(value);

    public String marshal(Integer value) {
        if (value == null) {
            return null;
        return value.toString();


Sunday Feb 15, 2015

YouTube: Find Recent File & Recent Edit in NetBeans IDE

When working with many projects and files in NetBeans, it is useful to be able to open the most recently closed document and to jump the cursor to the place where the last change took place. Do you know how to do these things and which keyboard shortcuts are applicable? Spend 4 minutes learning about this!

If you're watching the above and wondering how the toolbar displays in red the current keyboard shortcut and other actions, get the latest version of the NetBeans Key Promoter here:

Saturday Feb 14, 2015

[ERROR] Two declarations cause a collision in the ObjectFactory class.

The error message in the title of this blog entry seems to be causing a lot of people in the world a lot of problems. In this blog entry, I hope to be able to reproduce the problem and solve it, once and for all, for everyone everywhere, using a great tool to support you in doing so, i.e., NetBeans IDE. 

Let's start with this WSDL, which is useful in this context since it lets us reproduce the problem and then solve it:

  1. Create a new Java SE application in NetBeans IDE, named 'MoebiusIntegration', or any other name you like:

    Now you should see this:

  2. Go to the New File dialog and choose Web Services | Web Service Client. Click Next. In the WSDL URL field, paste the URL above and nothing else, i.e., do not fill in any field other than the WSDL URL field.  

  3. Click Finish. After a few moments, files are generated into your project structure and the first thing you notice is this big dialog:

    When you look in the Projects window, you should see this set of folders and files:

    In the Output window (Ctrl-4), you should see the following:

  4. Right-click the project in the Projects window and choose Build. The Output window now shows the following:

  5. Take note of the fact that there are different kinds of errors here, not all visible in the screenshot above, and the first below being the title of this blog entry and one that is a problem for many people, apparently, when I look on Google:

    • [ERROR] Two declarations cause a collision in the ObjectFactory class.

    • [ERROR] A class/interface with the same name "moebiusintegration.Reclamation" is already in use. Use a class customization to resolve this conflict.

    • [ERROR] This error is caused because on Windows you cannot have both "" and "" in the same directory.

    • [ERROR] This error is caused because on Windows you cannot have both "" and "" in the same directory.

Hurray! We've reproduced several JAXB binding problems. Let's now focus on solving them.

The biggest problem in solving these kinds of problems is that you're now going to go to Google and etc. There's hundreds (thousands, maybe) of developers who have encountered these kinds of problems over the years, there are many different solutions, each depending on the specific conflicts in the specific WSDL file, hence each solution being relevant for a subset of problems only. For example, in some scenarios, the -XautoNameResolution flag is helpful, while in others it isn't. It simply depends on the kind of JAXB binding problem you're dealing with.

The best thing to do is to start here, in the official documentation:

When you put the error message into a search in the official documentation above, you'll see this:

When schemas contain similar looking element/type names, they can result in "Two declarations cause a collision in the ObjectFactory class" errors. To be more precise, for each of all types and many elements (exactly what elements get a factory and what doesn't is bit tricky to explain), XJC produces one method on the ObjectFactory class in the same package. The ObjectFactory class is created for each package that XJC generates some files into. The name of the method is derived from XML element/type names, and the error is reported if two elements/types try to generate the same method name."

The first solution given for the above problem, right below the paragraph above in the documentation, is this:

"If the collision is coming from two different schemas with different target namespaces, then you can easily avoid the collision by compiling them into different Java packages. To do this, use <schemabindings> customization on two schemas and specify the package name."

An awesome contributor to this discussion on the NetBeans users mailing list, where this has been discussed over the past weeks, is Matthias Bläsing. He provided a solution that includes the binding customization referred to above. I used that approach to make this YouTube screencast today:

However, though the above fixes the ObjectFactory problem, the end of the YouTube screencast ends with a bit of a hack where I search through various files and rewrite bits of names to other names, which could be handled more gracefully. Matthias Bläsing to the rescue again who tells me that my approach with the rewriting is probably going to be wrong in the end: "Depending on what you changed in the XSD, the result might compile, but not work, as the elements are not recognized on the receiving side. The approach via customization is that I don't change the data definition, but only its mapping to the Java side."

So, hurray, Matthias has provided a new binding file which solves all the problems simultaneously:

<?xml version="1.0" encoding="UTF-8"?>
<jxb:bindings version="1.0"
            <jxb:package name="" />
            <jxb:package name=""/>
            <jxb:package name=""/>
            <jxb:package name=""/>
                <jxb:typeName suffix="Type" /> 
                <jxb:elementName suffix="Element"/> 
            <jxb:package name=""/>
            <jxb:package name=""/>
        <jxb:bindings node="//xs:complexType[@name='PersistentObjectOfInt']">
            <jxb:class name="PersistentObjectOfInt2" />
        <jxb:bindings node="//xs:complexType[@name='PersistentObjectOfString']">
            <jxb:class name="PersistentObjectOfString2" />

Alternatively, download it here:

Download the above file and put it anywhere in your project, e.g., in the META-INF folder, where the 'jax-ws-catalog.xml' file is found. Name the file 'binding.xml' or whatever you like:

Select the file and press Alt-Shift-L, which copies the file's full path to the clipboard. In NetBeans IDE, right-click on the 'MoebiusIntegration' node within the 'Web Service References' node and choose 'Edit Web Service Attributes':

Next, when the dialog opens, click the 'WSDL Customization' tab, scroll all the way down to 'External Binding Files', click Add, read the helpful information, click Yes, press Ctrl-V to paste the clipboard content into the Open dialog, and click Open. You should now see this:

Click OK. Then Click OK again. After a few seconds of processing, you should now see this and be able to expand the node as shown below:

But that's not all! Guess what? Not only do you now have all the client code... and not only are all the JAXB binding problems solved... you can drag all those red-bulleted nodes you see above, which represent classes, into your own Java code. For example, this is what my main method looks like initially:

Now I put my mouse on 'AddHardwareServiceOrder', which is the first node underneath 'CustomBinding_IMoebusIntegration':

Then I drag the mouse anywhere within my own class and when I release the mouse I see this:

Also notice that everything throughout the project, generated code and everything else, compiled. In other words, I now have a solid starting point for interacting with a service made available by the WSDL with which I started.

In upcoming blog entries, I'll look more closely at the binding.xml file and explain, via explanations received from Matthias Bläsing, what the entries in it mean, how it is hooked into the build process (and also how it can be done via Maven instead of Ant) and help understand the binding file's content. For the moment, you can simply take it and then adapt it to your own needs. Hope the above helps all those people out there struggling with these specific binding problems with JAXB.


Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.


« April 2015