Milen has posted 1 posts at DZone. You can read more from them at their website. View Full User Profile

Milen Petrov: Why NetBeans IDE is Great for Teaching Java

05.24.2014
| 2120 views |
  • submit to reddit

We've now met several teachers using NetBeans IDE in the classroom: Michiel Noback from Hanze University of Applied Sciences, in Groningen, the Netherlands, Zoran Sevarac from the University of Belgrade in SerbiaPieter van den Hombergh from Fontys University of Applied Sciences in Venlo, the Netherlands, Tushar Joshi from Nagpur, India and Johannes Weigend from the University of Applies Sciences in Rosenheim, Germany.

Meanwhile Ken Fogel, from Dawson College in Montreal, Canada, has explained how to get started with NetBeans in the classroom. Next, let's travel to Sofia in Bulgaria, and meet Milen Petrov. -- NetBeans Team

My name is Milen Petrov and I work in the Department of Software Engineering at Faculty of Mathematics and Informatics (Sofia University, Bulgaria). 

"Here we provide knowledge with quality which will last forever - warranty – one year as usual!

As a teacher and researcher, I use NetBeans IDE in different ways for Java and web programming, as well as for teaching programming-related courses. In this article, I will highlight my favorite NetBeans IDE features in the context of a typical use case in software development, that is, internationalization. Features such as block selection, shown in the screenshot below, will be highlighted along the way.

I use NetBeans IDE in the classroom for two purposes, namely, to demonstrate:

  1. How fast you can go wrong in writing software if you don’t really understand basic (and not so only basic) concepts and are not able to explain/write it on a sheet of paper or in a simple text editor like Notepad (or ++ if you will).
  2. How fast and enjoyable can programming be AFTER you know what you are really doing.

In NetBeans IDE I like very much the following:

  • extremely fast GUI prototyping
  • nice source code formatting
  • source code generators
  • code re-factoring
  • different wizards
  • helper tools

The above are just to name a few, and last but not least, I really like the many excellent online resources, tutorials, videos, and presentations from the official NetBeans web site as well as from many community blogs, which are handy when you're trying to expand the vision of learners on a given subject (which is often out of the scope of a specific course) and provides a basis for continuous self directed learning. And thus this prevents learners from staying stuck on a particular subject.

Below I will go through the features outlined above. And as a use case, I will use internationalization – as one of the features in Java since the very beginning this is one of the significant success factors (in my opinion) for the Java language as a whole.

Here I will present how you can use tools in NetBeans IDE to internationalize web content in JavaEE and JSF2+ particularly. There are many useful resources on the web on this topic, but still someone might find the information below to be helpful.

Internationalization

In software development, the concept of internationalization (for short "i18n") consists of, in general, the support for the same user experience for customers using different language and country-related information. Related to this are visual implication on things such as language, country name and code, currency, time presentation, and decimal points.

One possible way to change the language of an application, without modification and rebuilding of the source code, is through packaging and redistribution using the class ResourceBundle. In this approach, we need to create so-called resource files. A resource file contains lists of String resources, also known as "messages". 

Messages are stored in a resource file in the following format:
key=value

In the application, the "key" is used to access the corresponding text, that is, the "value".

It is also possible to customize messages with parameters, as shown below:

buttonLabel=Back

welcomeMessage=Welcome, {0}

Naming Conventions for Keys

It is recommended to use naming conventions for resources. In relatively big projects it is a good idea to have a prefix per module or per the type of message. 

I meet several styles in typing names of keys. There are different possibilities and here is the list possible notations for name of the keys:

  • snake notation (snake_case) 
    • example: message_button=Heaveno dear!
  • dot notation (dot.notation) 
    • example: message.button=Heaveno dear!
  • camel case (CamelCase)
    • example: MessageButton=Heaveno dear!
  • pascal case (pascalCase). 
    • example: messageButton=Heaveno dear!
Another important 'rule' is to have order of the messages. There is possible to name resources by module or by type, for example:
  • module-name_key module, the name of the message can be usermgmt_button_login=Login
  • if is by type buttons_back_user=Back
Using naming convention in resource keys for example helps when you are on production server. It is quite rare to have nice graphical tools to rescue. Then ordering messages by convention can help. In the article below i will show how you can easy manage messages with NetBeans.

Naming Conventions of Language Resources

For each written language, we have a separate text file with extension .properties. There are core language file and a set of specific for each language file called Resource Bundle.

Text files for different physical languages follow a convention - adding a suffix which corresponds to the language, country and variation/slang, for example: 

  • Bundle_bg_BG_WIN.properties

In the example - the name of bundle is 'Bundle', the language is bg (bulgarian) in BG (Bulgaria country), and WIN comes from windows.

Java platform makes cascade look for message by key. If there is no message with specified key in file Bundle_bg_BG_WIN.properties, looks for key in upper level file - Bundle_bg_BG.properties; if still not found looks for key in Bungdle_bg.properties, and then in Bungle.properties (which should be language neutral).

The "variant" is characteristic, specific for the client. Depending on the language settings, there is selected appropriate file with resources (see fig 1. below):

Fig. 1 Basic language resources (bg, en, es, fr and language neutral)

Fig. 2 Language resources with files for country and variant (bg_BG – Bulgarian language in Bulgaria; bg_BG_WIN – the same as bg_BG, but for windows platform specialization)

JSF2+ Internationalization Simple Example

Internationalization in web applications is potentially even more important than in any other type of applications. Let's look at the steps of how to create a working JSF2+ web application with support for different languages.

Firstly, add the supported languages in "faces-config.xml" - as is shown on source code (fig. 3) below. Here the supported locales are bg - Bulgarian, en - English, nl - Dutch, fr - France and al - Albanian. You can add as many languages as you wish but can start initially with support for one or two languages only.
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <application>
        <locale-config>
            <default-locale>bg</default-locale>
            <supported-locale>en</supported-locale>
            <supported-locale>es</supported-locale>
            <supported-locale>nl</supported-locale>
            <supported-locale>fr</supported-locale>
            <supported-locale>al</supported-locale>
        </locale-config>
        <resource-bundle>
            <base-name>Bundle</base-name>
            <var>i18n</var>
        </resource-bundle>
    </application>
</faces-config>

Fig. 3 Source code for configuration file (faces-config.xml)

A great (and relatively new) feature in NetBeans IDE is the ability to edit in "column" or "block" mode. To use it, you can copy the source code above (in fig.3), paste it in the file <project_root>/WEB-INF/faces-config.xml. Then enable column edit mode (keyboard shortcut is: CTRL+SHIFT+R or select  icon  ).

The result is shown in the image below (fig.4) and is common case when you paste source code from the internet with line numbers and no way to get clean source code - which can be happen. Of course source file should have proper indentation to use column edit mode for fixing a source code.

Fig. 4 Column mode editing (keyboard shortcut: CTRL+SHIFT+R)

Select the first columns with empty spaces and line numbers and then press DEL on keyboard. You can see the result in fig. 5, below.

Fig. 5 Result in NetBeans (WEB-INF/faces-config.xml)

Next step in our example is to create your "index.xhtml" page (see the source code in fig. 6 below), and try to apply the same technique again.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <head>
        <title>
            <h:outputText value="#{i18n['index.title']}"/>
        </title>
    </head>
    <f:loadBundle basename="UIResources" var="i18n"/>
    <body>
        <f:view locale="en">
          <p>Heaven-o my friend!</p>
          <h:outputText value="#{i18n['index.helloworld']}" />
          <h:outputLink id ="link01" value="#{i18n['index.link']}" >
           <h:outputText value="#{i18n['index.linkdescription']}" />
          </h:outputLink>
        </f:view>
    </body>
</html>
Fig. 6 Internationalized page with resources in i18n

Take note of the line where the resource bundle is mapped to a page variable:

<f:loadBundle basename="UIResources" var="i18n"/>

You can see the result in the editor, where you have convenient auto-completion. If you type #{} – you receive a list with available components.

Fig. 7 Result source code in NetBeans editor

NetBeans IDE and Resource Locations

It is important to organize your files in a logical structure. In fig. 8 below, you can see the location of the "faces-config.xml", "web.xml" (in WEB-INF), "images" (depends on configuration – here it is located in resources/images/*.png), and "property files" (should be located in source packages – depends on configuration):

Fig. 8 Web Project Structure in NetBeans

Edit all Resource Strings at Once in NetBeans

There is a convenient editor in NetBeans, where you can open side by side all resource files and check for missing translations. This can be done from the Open menu when you right-click on a bundle (see on fig. 9, below).

Fig. 9 Open for editing multiple strings at once in NetBeans

You now have a handy editor which can be used to edit several language files at once and to check if there are missing translations, which is normally a task that is not trivial to perform manually (fig. 10).

Fig. 10 Edit all text resources (property files) at once in NetBeans 

Notice also, back in the source code from fig.4, that resources can be changed:

<f:view locale="en">

Instead of English "en", you can put "bg" there, or any other of the supported locales.

Then run project.

If you change "en" to "bg", for example – and you refresh the page in the browser – you will see the page translated in Bulgarian (or at least see that the pages uses the Bulgarian language resource files).

Here is a result screenshot (fig. 11):

Fig. 11. Result page in bg locale.

Icons used can be found in [1] in reference section at the bottom of  article.

Here are several improvements to the scenario described above.

Change Language Dynamically

Firstly, use request parameters for language locales. It is not very convenient to change manually the language, so here are two other ways to achieve the same.

You can read language parameters from the page URL. Change line 15 as follows:

<f:view locale="#param.lang">

In order to pass parameters through the URL, see the following standard approach:

http://localhost:8084/i18n_lab05/faces/index.xhtml?lang=en (English language)

http://localhost:8084/i18n_lab05/faces/index.xhtml?lang=en_US (English language in US)

http://localhost:8084/i18n_lab05/faces/index.xhtml?lang=bg (Bulgarian language)

Alternative syntax can be:  http://localhost:8084/i18n_lab05/?lang=bg 

Message parameters

Secondly, you can use parameters to configure final message.

In order to add configurable messages with parameters, you can modify the body of the JSF page, as shown in fig.12 below:

<body>
  <p>Heaven o-my friend!</p>
  <br/>
  <h:outputText value="#{i18n['index.helloworld']}" /><br/>
  <h:outputLink id="link01" value="#{i18n['index.link']}">
  <h:outputText value="#{i18n['index.linkdescription']}" />
  </h:outputLink><br/><br/>
  <h:outputFormat value="#{i18n['formattedMessage']}">
     <f:param value="Milen"/>
     <f:param value="555-666"/>
  </h:outputFormat><br/><br/>
  <h:graphicImage value="#{i18n['imagePath']}"   />
</body>

Fig. 12 Formatted messages with parameters and access to images

Loading More than One Resource Bundle

It is possible to manually load different bundles in JSF pages (see the code below):

<f:loadBundle basename="BundleLocal" var="i18n_1" />
<body>
<h1><h:outputText value="#{i18n_1['page1.heaveno']}" /></h1>

The idea here is to have separate resource files for specific modules or functionality.

Conclusions and Further Extensions

The application and steps presented here are simple, but they show an important process and the steps of facilitating internationalization in Java web applications in the NetBeans environment. Many of these solutions are not NetBeans-specific, but still NetBeans IDE speeds up development and helps in editing, deployment, and testing of these aspects of Java web applications.

A possible extension of the application is to let the language be saved in a session or database, parsed/received trough HTTP header; while other enhancements might be to change the language through AJAX requests, as well as to provide support for better navigation. But these are other stories for another time!

Resources

[1] Open Icon Library, http://openiconlibrary.sourceforge.net/, last visited 2014-02-07

Published at DZone with permission of its author, Milen Petrov.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)