sign up! Channels Courses
 

Mr.Bool Editor - MrBool Space
RSS Mr.Bool Editor


20 last updates Mr.Bool Editor

Article - Whats New: We get to 1000 videos posted on the MrBool website

Today we get to 1000 videos posted on the MrBool website. Among them you can find videos about Java, .NET, Front-End Development, Databases, and others. All material with high quality and renowned authors in TI world.

This number is growing continuously. We are publishing several posts on a daily basis for you!

Good studies.

MrBool Team.

-->">
2/20/2013 3:51:00 PM





Article - Java Expressions - Introduction

Without a doubt, expressions are the main building blocks of a program. This is because there are so many different kinds of expressions that a majority of the source-code lines in a program end up being-you guessed it-expressions. There are expressions that result in numerical values. There are expressions that result in strings. There are simple expressions, complex expressions, and all manner of expressions in between.

In this post you'll learn not only more about those types of expressions, but also about logical expressions, which help a computer seem to be able to think and make choices. Along the way, you'll discover comparison and logical operators, which make logical expressions possible.

Types of Expressions

To put it simply, an expression is a line of code that can be reduced to a value or that assigns a value. For example, you know that the addition operator adds one expression to another, like this:

sum = expr1 + expr2;

In the preceding line, expr1 can be something as simple as the variable x or as complex as (4 + 5) * 2 * 5 / 7 + x / y. The same goes for expr2, of course. And, in fact, the first example containing expr1 and expr2 is an expression itself!

But no matter how complicated, all expressions can be classified into one of three main categories:

  • Numerical expressions combine numbers, variables, or constants using mathematical operators. An nexample is 2 + 3 / x.
  • Assignment expressions assign a value to a variable. An example is num = 3.
  • Logical expressions are unique in that they result in a value of true or false. An example is x

Expressions Within Expressions

Look at the following assignment expression:

num = (5 - x) * (2 + y);

This is an assignment expression because it assigns a value to the variable num. However, the stuff on either side of the equals sign contains these other expressions:

num
(5 - x) * (2 + y)

Both of the above lines are numerical expressions because they can be reduced to a numerical value (assuming that you know the values of num, x, and y.

But, wait a second-you're not done yet. You can still find more sub-expressions. Look at the multiplication operation. Can you see that it's multiplying two expressions together? Those two expressions look like this:

(5 - x)
(2 + y)

And the above simplified expressions contain yet more sub-expressions. Those expressions are:

5
x
2
y

Expressions are what programmers like to call recursive, meaning that the definition of an expression keeps coming back on itself. An expression contains expressions that contain other expressions, which themselves contain other expressions. How deep you can dig depends on the complexity of the original expression. But, as you saw demonstrated, even the relatively simple expression

num = (5 - x) *
(2 + y) has four levels of depth.

Comparison Operators

Now that you've dug into the secrets of expressions, it's time to learn about a new type of operator. So far, you've gotten some practice with mathematical operators, which enable you to build various types of numerical and assignment expressions. Another type of operator you can use to build expressions is the comparison operator. Comparison operators are used to create logical expressions, which, if you recall, result in a value of true or false. Table 1 lists the logical expressions used in Java programming. C and C++ programmers will find these operators very familiar.

Table 1 Java's Logical Operators.

Operators - Description

== - Equal to

> - Greater than

>= - Greater than or equal to

!= - Not equal to

Example: Using Comparison Operators

Just how do you use comparison operators? As their name suggests, you use them to compare two expressions, with the result of the comparison being either true or false. For example, look at this logical expression:

3 == 2 + 1

The result of the above expression is true because the == operator determines whether the expressions on either side are equal to each other. If you were to change the expression to 3 == 2 + 2 the result would be false. That is, 3 does not equal 4. However, the previous sentence suggests a way to rewrite the expression, like this:

3 != 2 + 2

This expression results in a value of true, because 3 does not equal 4. The other logical ...

Post view interrupted. To view full content, click here
10/24/2011 2:16:00 PM





Article - Writing a Simple Java Applet

The Simplest Java Applet

The Java programming language and libraries enable you to create applets that are as simple or as complex as you like. In fact, you can write the simplest Java applet in only a few lines of code, as shown in Listing 1.

Listing 1 MyApplet.java: The Simplest Java Applet.
import java.applet.*;
public class MyApplet extends Applet
{
}

The first line of Listing 1 tells the Java compiler that this applet will be using some or all of the classes defined in the applet package (the asterisk acts as a wildcard, just as in DOS file names). All of the basic capabilities of an applet are provided for in these classes, which is why you can create a usable applet with so few lines of code.
The second line of code declares a new class called MyApplet. This new class is declared as public so that the class can be accessed when the applet is run in a Web browser or in the Appletviewer application. If you fail to declare the applet class as public, the code will compile fine, but the applet will refuse to run. In other words, all applet classes must be public.
As you can see, you take advantage of object-oriented programming (OOP) inheritance to declare your applet class by subclassing Java's Applet class. This inheritance works exactly the same as when you created your own classes as you can see in the post "Classes in Java - Introduction and Practical Examples". The only difference is that Applet is a class that's included with the Java Developer's Kit (JDK), rather than a class you created yourself.
You can actually compile the applet shown in Listing 1. When you do, you'll have the MyApplet.class file, which is the byte-code file that can be executed by the Java system. To run the applet, just create an HTML document like the one shown in Listing 2. If you need a refresher course on using the tag, take a look in the post "Running Java Applets." If you were to run the MyApplet applet, however, you wouldn't see anything much in Appletviewer or in your Web browser.

Listing 2 MYAPPLET.htmL: MyApplet's HTML Document.
Applet Test Page

Applet Test Page

code="MyApplet.class"
width=250
height=250
name="MyApplet">

The Five Stages of an Applet's Life Cycle


Every Java applet you create inherits a set of default behaviors from the Applet class. In most cases, these default behaviors do nothing, unless you override some of Applet's methods in order to extend the applet's basic functionality. However, although a simple applet like MyApplet in Listing 1 doesn't seem to do much, a lot is going on in the background. Some of this activity is important to your understanding of applets, and some of it can stay out of sight and out of mind.
Part of what goes on in a simple applet is the execution of the applet's life cycle. There are five parts to this cycle, each of which has a matching method that you can overr
...
Post view interrupted. To view full content, click here
10/13/2011 11:11:00 AM





Article - How to use image and sound in an java applet

When programming in a language such a C++, displaying graphics and playing sounds can be famously difficult, thanks to the fact that these languages provide no direct support for handling these types of files. Even the Windows API, as immense as it is, provides little help when it comes to handling these graphical and aural chores. Java, on the other hand, was designed to make creating applets as easy as possible. For that reason, Java's classes handle almost all the difficulties associated with displaying images (commonly called bitmaps) and playing sounds.

Image Types

In the world of computers, there are many types of images, each of which is associated with a specific file format. These image types are usually identified by their file extensions, which include PCX, BMP, GIF, JPEG (or JPG), TIFF (or TIF), TGA, and more. Each of these file types was created by third-party software companies for use with their products, but many became popular enough to grow into standards. The PCX graphics file type, for example, began as the format for PC Paintbrush files, whereas BMP files are usually associated with the Windows graphical interface.

If you were writing your Internet applications using a more conventional language like C++, you could choose to support whatever image type was most convenient for your use. This is because you'd have to write all the file-loading code from scratch, anyway. Java, on the other hand, comes complete with classes that are capable of loading image files for you. This convenience comes with a small price, however, since Java can load only GIF and JPEG image file formats. In this article, you'll use GIF files, which are more common, although JPEG files are rapidly gaining a reputation, especially for high-resolution, true-color images.

Loading and Displaying an Image

The first step in displaying an image in your applet is to load the image from disk. To do this, you must create an object of Java's Image class. This is fairly easy to do; however, in order to do so, you need to create an URL object that holds the location of the graphics file. You could just type the image's URL directly into your Java source code. If you do this, however, you have to change and recompile the applet whenever you move the graphics file to a different directory on your disk. A better way to create the image's URL object is to call either the getDocumentBase() or getCodeBase() method. The former returns the URL of the directory from which the current HTML file was loaded, whereas the latter returns the URL of the directory from which the applet was run.

Example: Using the getDocumentBase() Method

As I said previously, the getDocumentBase() method returns the URL of the directory from which the HTML document was loaded. If you're storing your images in the same directory (or a subdirectory of that directory) as your HTML files, you'd want to use this method to obtain an URL for an image.

Suppose you have your HTML documents in a directory called PUBLIC and the image you want, called IMAGE.gif, is stored in a subdirectory of PUBLIC called IMAGES. A call to getDocumentBase() will get you the appropriate base URL. That call looks like this:

         URL url = getDocumentBase();

As you'll soon see, once you have the URL, you can load the file by using the URL along with the relative location of the image, which in this case would be IMAGES/IMAGE.gif. The full URL to the file would then be FILE:/C:/PUBLIC/IMAGES/IMAGE.gif. If you decided to move your public files to a directory called MYHOMEPAGE, the call to getDocumentBase() will give you the URL for that new directory, without your having to change the applet's source code. This new URL, once you included the relative location of the image file, would be FILE:/C:/MYHOMEPAGE/IMAGES/IMAGE.gif.

Example: Using the getCodeBase() Method

The getCodeBase() method works similarly to getDocumentBase(), except that it returns the URL of the directory from which the applet was loaded. If you're storing your images in the same directory (or a subdirectory of that directory) as your CLASS files, you'd want to call getCodeBase() to obtain an URL for an image.

Suppose you have your CLASS files in a directory called CLASSES and the image you want (still called IMAGE.gif) is stored in a subdirectory of CLASSES called IMAGES. A call to getCodeBase() will get you the base URL you need to load the image. That call looks like this:

         URL url = getCodeBase();

Again, once you have the URL, you can load the file by using the URL along with the relative location of the image, which would still be IMAGES/IMAGE.gif. The full URL to the file would then be FILE:/C:/CLASSES/IMAGES/IMAGE.gif.

Loading an Image

Once you have the image's base URL, you're ready to load the image and create the Image object. You can complete both of these tasks at the same time, by calling your applet's getImage() method, like this:

         Image image = getImage(baseURL, relLocation);

The getImage() method's two arguments are the URL returned by your call to getCodeBase() or getDocumentBase() and the relative location of the image. For example, assuming that you've stored your CLASS files in the directory C:\CLASSES and your images in the directory C:\CLASSES\IMAGES, you'd have a code that looks something like this:

         URL codeBase = getCodeBase();

         Image myImage = getImage(codeBase, "images/myimage.gif");

After Java has executed the above lines, your image is loaded into the computer's memory and ready to display.

Displaying an Image

Displaying the image is a simple matter of calling the Graphics object's drawImage() method, like this:

         g.drawImage(myImage, x, y, width, height, this);

This method's arguments are the image object to display, the X and Y coordinates at which to display the image, the width and height of the image, and the applet's this reference.

TIP

When you want to display an image with its normal width and height, you can call a simpler version of the drawImage() method, which leaves out the width and height arguments, like this: drawImage(image, x, y, this). This version of the method actually draws the image faster because it doesn't have to worry about reducing or expanding the image to the given width and height. It just blasts it on to the screen exactly as the image normally appears.

 

You may be wondering where you can get the width and the height of the image. As it turns out (no doubt thanks to careful consideration by Java's programmers over hundreds of cups of coffee), the Image class has two methods, getWidth() and getHeight(), that return the width and height of the image. The complete code for displaying the image, then, might look like this:

         int width = image.getWidth(this);

         int height = image.getHeight(this);

         g.drawImage(image, x, y, width, height, this);

As you can see, the getWidth() and getHeight() methods require a single argument, which is the applet's this reference.

Example: Displaying an Image in an Applet

You're now ready to write an applet that can display images. Listing 1 is the Java source code for an applet called ImageApplet that displays a small image using the techniques described previously in this article. Make sure the SNAKE.gif image is in the same directory as the ImageApplet.class file, since that's where the program expects to find it.

Listing 1 - ImageApplet.java: An Applet That Displays an Image.

import java.awt.*;

import java.applet.*;

import java.net.*;

public class ImageApplet extends Applet

{

      Image snake;

      public void init()

      {

              URL codeBase = getCodeBase();

              snake = getImage(codeBase, "snake.gif");

              resize(250, 250);

      }

      public void paint(Graphics g)

      {

              int width = snake.getWidth(this);

              int height = snake.getHeight(this);

              g.drawRect(52, 52, width+10, height+10);

      & ...

Post view interrupted. To view full content, click here
10/5/2011 4:58:00 PM





Article - Configurable Applets in Java

In this java tutorial, you get a look at configurable applets, which enable the applets user to modify how an applet looks and acts, all without having to change a line of Java code.

If you have questions about java applets, check out this free tutorial about java applets.

Most of the applets you've written so far have onething in common. Outside of the starting size of the applet, none of yourapplets are configurable. That is, the user can't configure the applet to fithis needs. In many cases, it doesn't make sense to give the user configurableoptions. But, just as often, someone who wants to use your applet in his ownhome page will want to make minor changes without having to change andrecompile the source code. In fact, the user probably won't even have access tothe source code.

Types of Users

Before you read further, it might be a good idea to define exactly what a user is. When it comes to applets, you could say that there are two kinds of users. The first kind is a net surfer who logs onto your home page and sees all the cool applets you've spent the last six months creating. Because this user is not installing your applets on his own Web pages, he's just a casual observer-he doesn't need access to the applet's parameters. In fact, if you want your Web pages to look right for different users, it just doesn't make sense to enable the surfer to configure an applet.

The other kind of user is the guy who found your applet on a server somewhere and wants to incorporate the applet into his own Web pages. Assuming that you've released your applet into the world for others to use, you want this type of user to find your applet to be as flexible as possible. However, you probably don't want to give this user your source code and expect him to make changes that require recompiling.

Hey, he could end up trashing the applet completely, right?

So, to make it easy for this user to modify the applet's appearance and functionality, you must build in support for parameters. To use these parameters, the user only needs to add a few lines to the HTML document that loads and runs the applet. For example, you may have written an applet that displays an awesome title on your home page. Now, you want to release the applet so that other netfolks can use it in their Web pages. However, these folks are going to want to display their own titles. So, you make the title string a parameter.

In this article, you'll not only learn how to support applet parameters, but you'll also learn how to make those parameters user-proof.

Parameters and Applets

When you want to use an applet that supports parameters, you must add the parameters and their values to the HTML document that loads and runs the applet. You do this using the tag, which has two parts. The NAME part of the tag specifies the parameter's name, and the VALUE part specifies the parameter's value. For example, suppose you want to provide a title parameter for that title applet you read about in the previous section. The parameter tag might look like this:

        

Here, the name of the parameter is title. The applet will use this name to identify the parameter. The value of the title parameter in the above line is the text string My first Home Page. The applet will retrieve this text string in order to display the title the user wants. A complete HTML document for the title applet might look something like Listing 1.

Listing1: Using a Parameter in an HTML Document.

Applet Test Page

Applet Test Page

code="TitleApplet.class"

width=250

height=150

name="TitleApplet">

     

As you can see, the tag is enclosed between the and tags, that is, the parameters are part of the applet's HTML code.

How does your applet retrieve the parameter at run time? An excellent question, and one for which I fortunately have the answer. To retrieve a parameter, you call the applet's getParameter() method, like this:

         String param = getParameter(name);

The getParameter() method takes a single argument, which is a string containing the name of the parameter for which you want the value. The method always returns a string to your applet. This string is, of course, the part of the PARAM tag that follows the VALUE=.

Example: Setting and Retrieving a Parameter's Value

Suppose that you've written an applet that displays a fancy greeting to the viewer.

The parameter is defined in the HTML document like this:

        

When the applet runs, it has to find out what greeting to display. So, in the applet's init() method is the following line:

         String str = getParameter("greeting");

Now that the applet has the text stored in the str variable, it can manipulate and display it any way it needs to.

Example: Using a Parameter in an Applet

Now that you know how to create HTML documents that set parameters, as well as how to obtain those parameters from within your applet, you'd probably like a real parameterized applet with which you can experiment. Listing 2 is an applet called ConfigApplet, which takes a single parameter. This parameter is the text string to display. Listing 3 is the HTML document that loads and runs the applet.

Listing 2 - ConfigApplet.java: An Applet with a Single Parameter.

import java.awt.*;

import java.applet.*;

public class ConfigApplet extends Applet

{

      String str;

      public void init()

      {

                str = getParameter("text");

             Font font = new Font("TimesRoman", Font.BOLD, 24);

             setFont(font);

      }

      public void paint(Graphics g)

      {

             g.drawString(str, 50, 50);

      }

}

Line by line

- Tell Java that the applet uses the classes in the awt package.

- Tell Java that the applet uses the classes in the applet package.

- Derive the ConfigApplet class from Java's Applet class.

- Declare the class's data field.

- Override the init() method.

- Retrieve the value of the text parameter.

- Create and set the font for the applet.

- Override the paint() method.

- Display the given string.

Listing 3 - CONFIGAPPLET.htmL : HTML Document for ConfigApplet.

Applet Test Page

Applet Test Page

code="ConfigApplet.class"

width=250

height=150

name="ConfigApplet">

     

Once you get ConfigApplet compiled, try running the applet several times, each time changing the parameter in the HTML document to a new text string. This will give you a good example of how parameters work from the HTML document writer's point of view. Changing the value of the parameter in the HTML document is all you need to do to display a different text string. You don't have to change the applet's source code at all.

Multiple Parameters

When you're writing an application that others may use in their Web pages, it's important that you make the applet as flexible as possible. One way to do this is to use parameters for any applet value that the user might like to customize. Adding multiple parameters is just a matter of adding additional tags to the HTML document and then retrieving the values of the parameters in the applet. In the next example, you take a look at ConfigApplet2, which gives the user much more control over how the applet displays the text string.

Example: Using Multiple Parameters in an Applet

Suppose that you want to rewrite ConfigApplet so that the user can customize not just the text string the applet will display, but also the position of the text and the size of the font used to print the text. To do this, you need to create four parameters, one each for the text to display, the X position of the text, the Y position of the text, and ...

Post view interrupted. To view full content, click here
9/28/2011 6:17:00 PM





Article - Classes in Java - Introduction and Practical Examples

Classes and Objects

A class is the template for an object and a way to encapsulate both data (called fields in Java) and the functions (called methods) that operate on that data. The Inheritance, enables a class, called the subclass, inheriting the capabilities of a base class, called a superclass in Java. The polymorphism enables you to create virtual methods that can be implemented differently in derived classes. In this article, you'll apply what you know about object-oriented programming towards creating Java classes.

Defining a Simple Class

As I said, a class is sort of a template for an object. In this way, a class is equivalent to a data type such as int. The main difference is that Java already knows what an integer is. However, when you create a class, you must tell Java about the class's characteristics. You define a class by using the class keyword along with the class name, like this:

class MyClass

{

}

Believe it or not, the preceding lines are a complete Java class. If you save the lines in a file called MyClass.java, you could even compile the class into a .CLASS file, although the file won't actually do anything if you tried to run it. As you can see, the class definition begins with the keyword class followed by the name of the class. The body of the class is marked off by curly braces just like any other program block. In this case, the class's body is empty. Because its body is empty, this example class doesn't do anything. You can, however, compile the class and even create an object from it. To create an object from a class, you type the class's name followed by the name of the object. For example, the line below creates an object from the MyClass class:

MyClass myObject = new MyClass();

Declaring Fields for a Class

As I said, the MyClass example class doesn't do much yet. In order to be useful, it needs both data fields and methods. You declare fields for your class in much the same way you declare any variable in a program, by typing the data type of the field followed by the name of the field, like this:

         int myField;

The above line declares a data field of type integer. However, looking at the above line doesn't tell you much about how data fields are used with classes. In fact, you can't tell from the above line whether myField is actually part of an object or just a normal variable. To clear up this ambiguity, you can plug the above line into the MyClass class definition, as shown in Listing1.

Listing 1: Adding a Data Field to a Class.

class MyClass

{

      int myField;

}

Now you can see that myField is a data field of the MyClass class. Moreover, this data field is by default accessible only by methods in the same package. (For now, you can think of a package as a file.) You can change the rules of this access by using the public, protected, and private keywords. A public data field can be accessed by any part of a program, inside or outside of the class in which it's defined. A protected data field can only be accessed from within the class or from within a derived class (a subclass). A private data field cannot even be accessed by a derived class.

Defining a Constructor

You have now added a data field to MyClass. However, the class has no methods and so can do nothing with its data field. The next step in defining the class, then, is to create methods. One special type of method, called a constructor, enables an object to initialize itself when it's created. A constructor is a public method (a method that can be accessed anywhere in a program) with the same name as the class. Listing2 shows the MyClass class with its constructor in place.

Listing 2: Adding a Constructor to a Class.

class MyClass

{

int myField;

public MyClass(int value)

{

myField = value;

}

}

As you can see, the class's constructor starts with the public keyword. This is important because you want to be able to create an object from the class anywhere in your program, and when you create an object, you're actually calling its constructor. After the public keyword comes the name of the constructor followed by the constructor's arguments in parentheses. When you create an object of the class, you must also provide the required arguments.

Example: Creating an Object by Calling a Constructor

If you want to create an object from MyClass, you must supply an integer value that the class uses to initialize the myField data field. This integer is the MyClass constructor's single argument. You'd create an object of the class like this:

MyClass myObject = new MyClass(1);

This line not only creates an object of the MyClass class, but also initializes the myField data field to 1. The first word in the line tells Java that myObject is going to be an object of the MyClass class. The next word is the object's name. After the equals sign comes the keyword new and the call to the class's constructor.

Defining Methods

You just need to be sure to provide the proper type of access to your methods. That is, methods that must be called from outside the class, should be defined as public, methods that must be callable only from the class and its derived classes should be defined as protected, and methods that must be callable only from within the class should be declared as private.

Suppose myField is defined as private, and you now want to be able to set the value of myField from outside the MyClass class. Because that data field is defined as private, meaning it can be accessed only from within the same class, you cannot access it directly by name. To solve this problem, you can create a public method that can set the value for you. You might also want to create a method that returns the value of the field, as well, as shown in Listing3.

Listing 3: Adding a Method to the Class.

class MyClass

{

private int myField;

public MyClass(int value)

{

      myField = value;

}

public void SetField(int value)

{

      myField = value;

}

public int GetField()

{

      return myField;

}

}

Line by line

- Start defining the MyClass class.

- Declare the class's myField data field.

- Define the class's constructor.

- Initialize the data field.

- Start defining the SetField() method.

- Set the data field to the value passed to SetField().

- Start Defining the GetField() method.

- Return the value of the myField data field.

NOTE

According to the rules of strict object-oriented design, all class data fields should be declared as private. Some programmers would go so far as to say that you should not even provide access to data fields through public methods. However, you'll see these rules broken a lot, even by programmers hired by big companies like Microsoft, Borland, and Sun. When you become more familiar with object-oriented programming, you'll better understand why the rules were made and when it's appropriate to break them.

 

Example: Using Classes in Applets

You've been writing applets using the classes already supplied as part of Java. Now, you'll see how to use your own classes in applets. This will help you understand not only how your own classes work, but also help you to understand why you used Java's classes as you did. Follow the steps below to see how all this class stuff works.

1. Type Listing3 and save it to your CLASSES folder under the name MyClass.java.

2. Start a DOS session by selecting Programs/MS-DOS Prompt from the Start menu.

3. Type CD C:\CLASSES to switch to your CLASSES folder.

4. Type javac MyClass.java to compile the MyClass class. You'll then find the MyClass.class file in your CLASSES folder.

5. Type Listing 4 and save it as Applet1.java in your CLASSES folder.

Listing 4 - Applet1 : An Applet That Uses the MyClass Class.

import java.awt.*;

import java.applet.*;

import MyClass;

public class Applet1 extends Applet

{

MyClass myObject;

TextField textField1;

public void init()

{

      myObject = new MyClass(1);

      textField1 = new TextField(10);

      add(textField1);

      textField1.setText("1");

}

public void paint(Graphics g)

{

      String s = textField1.getText();

      int value = Integer.parseInt(s);

      myObject.SetField(value);

      value = myObject.GetField();

      s = String.valueOf(value);

      g.drawString("The data field of the object" ...

Post view interrupted. To view full content, click here
9/20/2011 6:28:00 PM





Article - Earn an iPad 2!

It is not a raffle, to win the iPad 2 is up to you!

Mr. Bool website has over 390 free videos and online courses that can be viewed freely on our site.

We believe that these videos can help thousands of people and we count on your help in disseminating this free videos.

Just disclose any url of our website to start participating.

Just choose any url on our website and post it on your blog to start participating.

The blog that brings more unique visitors to the Mr Bool website in the period from 20/09/2011 to 20/11/2011 will be the winner.

Did you saw how it is easy to win a iPad 2?

We will publish a partial list of the top 10 blogs from time to time, stay tuned!

We will contact you via the contact form from the winner blog.

We will monitor the disclosures through our Google Analytics account.

Good job! We will be glad to give you the iPad 2.

Pedro Cunha
Mr. Bool Team.

-->">
9/20/2011 2:37:00 PM





Article - Arrays in Java - Introduction and Practical Examples

An Introduction to Arrays

Often in your programs, you'll want to store many values that are related in some way. Suppose you manage a bowling league, and you want to keep track of each player's average. One way to do this is to give each player a variable in your program, as shown in Listing 1.

Listing 1 - Applet1.java: Using Variables to Track Scores.

import java.awt.*;

import java.applet.*;

public class Applet1 extends Applet

{

TextField textField1, textField2, textField3;

int avg1, avg2, avg3;

public void init()

{

      textField1 = new TextField(5);

      textField2 = new TextField(5);

      textField3 = new TextField(5);

      add(textField1);

      add(textField2);

      add(textField3);

      textField1.setText("0");

      textField2.setText("0");

      textField3.setText("0");

}

public void paint(Graphics g)

{

      g.drawString("Your bowlers' averages are: ", 50, 80);

      String s = textField1.getText();

      g.drawString(s, 75, 110);

      avg1 = Integer.parseInt(s);

      s = textField2.getText();

      g.drawString(s, 75, 125);

      avg2 = Integer.parseInt(s);

      s = textField3.getText();

      g.drawString(s, 75, 140);

      avg3 = Integer.parseInt(s);

}

public boolean action(Event event, Object arg)

{

      repaint();

      return true;

}

}

When you run Applet1, you can enter bowling scores into the three boxes at the top of the applet's display area. After you enter these averages, they're displayed on-screen as well as copied into the three variables avg1, avg2, and avg3.

Nothing too tricky going on here, right?

Now examine the listing. If you could find some way to make a loop out of this code, you could shorten the program significantly. How about a for loop that counts from 1 to 3?

But how can you use a loop when you're stuck with three different variables? The answer is an array. An array is a variable that can hold more than one value. As you know, a variable is like a box in memory that holds a single value. Now, if you take a bunch of these boxes and put them together, what do you have? You have an array. For example, to store the bowling averages for your three bowlers, you'd need an array that can hold three values. You could call this array avg. You can even create an array for a set of objects like the TextField objects Applet1 uses to get bowling scores from the user. You could call this array textField.

Now you have an array called avg that can hold three bowling averages and an array called textField that can hold three TextField objects. But how can you retrieve each individual average or object from the array? You do this by adding something called a subscript to the array's name. A subscript (also called an index) is a number that identifies the element of an array in which a value is stored. For example, to refer to the first average in your avg array, you'd write avg[0]. The subscript is the number in square brackets. In this case, you're referring to the first average in the array (array subscripts always start from zero.) To refer to the second average, you'd write avg[1]. The third average is avg[2].

 In this case, the three bowling averages are 145, 192, and 160. The value of avg[0] is 145, the value of avg[1] is 192, and the value of avg[2] is 160.

Example: Creating an Array

Suppose that you need an array that can hold 30 floating-point numbers. First, you'd declare the array like this:

float numbers[];

Another way to declare the array is to move the square brackets to after the data type, like this:

float[] numbers;

After declaring the array, you need to create it in memory. Java lets you create arrays only using the new operator, like this:

numbers = new float[30];

The last step is to initialize the array, a task that you might perform using a for loop:

for (int x=0; x<30; ++x)

      numbers[x] = (float)x;

These lines of Java source code initialize the numbers[] array to the numbers 0.0 to 29.0. Notice how the loop only goes up to 29. This is because, although there are 30 elements in the numbers[] array, those elements are indexed starting with 0, rather than 1. That is, the subscript is always one less than the number of the element you're accessing. The first element has a subscript of 0, the second a subscript of 1, the third a subscript of 2, and so on.

Example: Using a Variable as a Subscript

As you know, most numerical literals in a Java program can be replaced by numerical variables. Suppose you were to use the variable x as the subscript for the array avg[]. Then  if the value of x is 1, the value of avg[x] is 192. If the value of x is 3, the value of avg[x] is 160.

Now take one last, gigantic, intuitive leap (c'mon, you can do it) and think about using your subscript variable x as both the control variable in a for loop and the subscript for the avg[] and textField arrays. If you use a for loop that counts from 0 to 2, you can handle all three averages with much less code than in the original program. Listing 2 shows how this is done.

Listing 2 - Applet2.java: Using Arrays.

import java.awt.*;

import java.applet.*;

public class Applet2 extends Applet

{

TextField textField[];

int avg[]; 

public void init()

{

      textField = new TextField[3];

      avg = new int[3];

      for (int x=0; x<3; ++x)

      {

            textField[x] = new TextField(5);

            add(textField[x]);

            textField[x].setText("0");

      }

}

public void paint(Graphics g)

{

      g.drawString("Your bowlers' averages are: ", 50, 80);

      for (int x=0; x<3; ++x)

      {

            String s = textField[x].getText();

            g.drawString(s, 75, 110 + x*15);

            avg[x] = Integer.parseInt(s);

      }

}

public boolean action(Event event, Object arg)

{

      repaint();

      return true;

}

}

Line by line

- Tell Java that the program uses classes in the awt package.

- Tell Java that the program uses classes in the applet package.

- Derive the Applet2 class from Java's Applet class.

- Declare TextField and int arrays.

- Override the Applet class's init() method.

- Create the textField and int arrays with three elements each.

- Loop from 0 to 2.

- Create a new TextField object and store it in the array.

- Add the new TextField object to the applet.

- Set the new TextField object's text.

- Override the Applet class's paint() method.

- Display ...

Post view interrupted. To view full content, click here
9/14/2011 11:31:00 AM





Article - Functions in Java - Introduction and Practical Examples

When you start writing real programs, however, you'll quickly discover that they can grow to many pages of code. When programs get long, they also get harder to organize and read. To overcome this problem, professional programmers break their programs down into individual functions, each of which completes a specific and well-defined task.

The Top-Down Approach to Programming

As I said, long programs are hard to organize and read. A full-length program contains many pages of code, and trying to find a specific part of the program in all that code can be tough. You can use modular program-design techniques to solve this problem. Using modular programming techniques, you can break a long program into individual modules, each of which performs a specific task.

In that article, I used the example of cleaning a house as a way to understand the process of breaking tasks up into specific steps. (The only reasonable way to clean my house is to douse it with gasoline and throw in a lighted match, but we won't get into that now.) You'll use that metaphor here, in preparation for learning about functions.

When cleaning a house, the main task might be called CLEAN HOUSE. Thinking about cleaning an entire house, however, can be overwhelming. So, to make the task easier, you can break it down into a number of smaller steps. These steps might be CLEAN LIVING ROOM, CLEAN BEDROOM, CLEAN KITCHEN, and CLEAN BATHROOM.

After breaking the housecleaning task down into room-by-room steps, you have a better idea of what to do. But cleaning a room is also a pretty big task-especially if it hasn't been done in a while or if you have cats coughing up fur balls all over the place. So why not break each room step down, too? For example, cleaning the living room could be broken down into PICK UP ROOM, DUST AND POLISH, CLEAN FURNITURE, and VACUUM RUG.

After breaking each room's cleaning down into steps, your housecleaning job is organized much like a pyramid, with the general task on the top. As you work your way down the pyramid, from the main task to the room-by-room list and finally to the tasks for each room, the tasks get more and more specific.

Of course, when cleaning a house, you don't usually write a list of steps. If you're an efficient housecleaner, the steps are organized in your mind. (If you clean house like I do, there are only two steps: TURN ON TV and COLLAPSE ON COUCH.) However, when writing a program, which is a more conceptual task, you may not have a clear idea of exactly what needs to be done. This can lead to your being overwhelmed by the project.

Breaking programming tasks down into steps, or modules, is called modular programming. And when you break your program's modules down into even smaller modules-as we did with the task of cleaning a house-you're using a top-down approach to program design. By using top-down programming techniques, you can write any program as a series of small, easy-to-handle tasks. In Java, the basic unit for organizing code in a top-down manner is the function.

Example: Using Functions as Subroutines

When programmers talk about subroutines, they usually mean program modules that return no value to your program. In a way, a subroutine is like a small program within your main program. If you write a housecleaning program, the subroutines in the main module might be called CleanLivingRoom(), CleanBedroom(), CleanKitchen(), and CleanBathroom(). The CleanLivingRoom() subroutine would contain all the steps needed to clean the living room, the CleanBedroom() subroutine would contain all the steps needed to clean a bedroom, and so on.

Of course, it takes an extremely talented programmer to get a computer to clean a house. (If you manage that trick, contact me immediately.) We need a more computer-oriented example. Suppose you want to write a program that displays game instructions on-screen. Listing 1 shows one way you might accomplish this task in a Java applet.

 Listing 1 - Applet1.java: Printing Instructions in an Applet.

import java.awt.*;

import java.applet.*;

 

public class Applet1 extends Applet

{

  public void paint(Graphics g)

  {

     g.drawString("Try to guess the number I am", 48, 65);

     g.drawString("thinking of. The number will be", 48, 80);

     g.drawString("between 0 and 100. You have an", 48, 95);

     g.drawString("unlimited number of tries.", 48, 110);

     g.drawString("Good Luck.", 95, 140);

  }

}

 

Applet1 is about the simplest applet you can write. All it does is display text. The text comprises instructions for playing a simple number game. If you had to sum up in a couple of words the task performed by Applet1's paint() method, you might come up with something like "Draw Instructions," which is an excellent name for a function to handle that task. Listing 2 is a new version of the applet that isolates the instruction-display task in its own function. When you run this applet, it looks identical to Applet1.

Listing 2 - Applet2.java: Placing the Instructions in a Function.

import java.awt.*;

import java.applet.*;

public class Applet2 extends Applet

{

  public void paint(Graphics g)

  {  

    DrawInstructions(g);

  }

  void DrawInstructions(Graphics g)

  {

    g.drawString("Try to guess the number I am", 48, 65);

    g.drawString("thinking of. The number will be", 48, 80);

    g.drawString("between 0 and 100. You have an", 48, 95);

    g.drawString("unlimited number of tries.", 48, 110);

    g.drawString("Good Luck.", 95, 140);

  }

}

 

Now for the million-dollar question: How does this Applet2 work? The program is divided into two functions. The first is the paint() method, which Java calls whenever the applet's display area must be redrawn. In this applet, paint() is at the highest level of your top-down design. That is, no other part of the program calls paint(), but paint() calls functions that are lower in level.

NOTE

You might be confused about the difference between methods, functions, and subroutines. The truth is that they are very similar. Specifically, a method is a function that is part of a class. So, in Applet2, both paint() and DrawInstructions() are methods of the Applet2 class. (They are also functions.) A subroutine is a function that returns no value. That is, it has the word void in front of its name.

 

The second function in Listing 2 is the DrawInstructions() subroutine, which is really just a Java function that returns no value to the calling function (paint(), in this case). DrawInstructions() is one level down from the main program in the top-down design. In paint(), instead of having all the code that's needed to display the instructions, you only have a line that calls the function that handles this task. This makes it easier to see what's going on in paint(). If you need to see more detail, you can always drop down a level in your program and take a look at DrawIns ...

Post view interrupted. To view full content, click here
9/2/2011 5:59:00 PM





Article - Java Applets - Introduction and Practical Examples

If you are not familiar with the use of HTML (Hypertext Markup Language) for creating Web pages, you should pick up a book on HTML to get an idea of ​​how this markup works. And even if you are an expert in HTML, you may not have seen the HTML extension that Sun Microsystems has created to support Java applets on Web pages. So, in this article, you not only will have the chance to see Java applets up and running but also will learn how to add them to your Web pages.

The Sample Java Applets

The Java Developer's Kit (JDK) includes many sample applets that you can test in your Web pages. (The HotJava browser, too, comes with a few of these sample applets.). As soon as you install the JDK, you're will ready to start experimenting with Java applets. In this section, you will use the Appletviewer tool-which comes with the JDK-to get a quick look at some applets. A following section, "Adding Applets to an HTML Document," will show you how to add an applet to a Web page.

 The Appletviewer Tool

The truth is that you can write and run applets without even having a Java-compatible browser. This is thanks to the Appletviewer tool that comes as part of the JDK. Appletviewer is a Windows application (unless you're using a non-Windows version of the JDK) that you run from a DOS command line. Part of the command line is the applet that you want to run. When Appletviewer appears, the applet appears in the viewer's main window.

To run the Appletviewer application, first bring up an MS-DOS window by selecting the MS-DOS Prompt command from Programs on the Start menu. Then, switch to the folder containing the applet you want to run and type the command line C:\JAVA\BIN\APPLETVIEWER DOC.htmL.

In the preceding command line, DOC.htmL is the name of an HTML document that contains the tag for the applet you want to see.

 

Example: Running TicTacToe

Suppose you want to run the TicTacToe demo applet that comes with the JDK. To do this, just follow these steps:

 

- Select the Start/Programs/MS-DOS Prompt command. The DOS window appears.

 

- Change to the directory containing the TicTacToe applet

 

- Type the command line C:\JAVA\BIN\APPLETVIEWER EXAMPLE1.htmL.The

Appletviewer runs, loading and displaying the TicTacToe.

 

- Now that you have the applet started, try a few games of TicTacToe against the computer. To place an X, click the square you want. You'll quickly discover that the computer player is as dumb as yogurt. Let's just say that you don't have to be a rocket scientist to win.

 

TIP

If you want to avoid typing the full path name for Appletviewer every time you run it, type the command PATH=C:\JAVA\BIN at the MS-DOS prompt to add Appletviewer's directory to your path. (Of course, if you've installed the JDK somewhere else on your hard drive, you'll have to use a different path in the command.) After you type this command, MS-DOS will be able to find Appletviewer without your having to type the full path. For example, you'll be able to run TicTacToe by switching to the TicTacToe directory and simply typing APPLETVIEWER EXAMPLE1.htmL. You can also add Appletviewer's path to the PATH statement in your AUTOEXEC.BAT file and thus avoid having to type it in by hand every time you start your system and want to use Appletviewer.

 

The Animator Applet

Another applet that demonstrates some interesting facets of Java programming is the Animator applet, which not only displays various animation sequences, but also plays sound effects simultaneously. To run the Animator applet, switch to the C:\JAVA\DEMO\ANIMATOR folder and type the command line APPLETVIEWER EXAMPLE1.htmL. (The previous command line assumes that you've set your path to the JAVA\BIN directory.). (Yep, it's the ubiquitous Duke, waving at you from his very own applet.)

 Animator is an example of a configurable applet. That is, by modifying the HTML tag that loads and runs the applet, the user can display his or her own custom animation sequence and sound effects. For now, though, it's enough for you to know that Java is capable of adding both animation sequences and sound effects to your Web pages.

 

NOTE

If you'd like to see what the applet's HTML tag looks like, select Appletviewer's Applet,Tag command.

 

The BarChart Applet

BarChart, another configurable applet, is especially useful when you need to graphically display data values in a Web page. To check out BarChart, switch to the JAVA\DEMO\BARCHART folder and type the command line APPLETVIEWER EXAMPLE1.htmL.

Because BarChart is configurable, you can create all sorts of different bar charts in your Web pages just by specifying different parameters in the applet's HTML tag. As you can see, applets can be powerful tools for creating dynamic and useful Web pages. (Try out Appletviewer's Applet,Tag command to see the code that specifies how the bar chart appears.)

 

Other Demo Applets

The DEMO folder contains many sample applets that you can experiment with using Appletviewer. All of the demo applets are run from HTML documents with names such as EXAMPLE1.htmL, EXAMPLE2.htmL, and so on. All demo applets have at least the EXAMPLE1.htmL document, while others have additional examples. To run any demo applet, change to the applet's folder and type APPLETVIEWER EXAMPLE1.htmL (assuming that you've set your path to the Appletviewer application). Use the DIR command to display the contents of an applet's directory in order to discover whether the applet features additional example HTML files.

 

NOTE

Remember that the HotJava browser cannot load and run newer applets like those that come with the latest version of the JDK.

 

Adding Applets to an HTML Document

If you've created Web pages before, you know that you use HTML to create a template for the page. The commands in the template tell a Web browser how to display the Web page. When Sun Microsystems developed Java, they also had to come up with an extension to HTML that would enable Web pages to contain Java applets. That extension is the <applet> tag, which Sun Microsystems defines as shown in Listing 1.

Listing 1: The <applet> Tag Definition.

<applet attributes>

parameters

alternate -content

</applet>

In the preceding tag, the text in normal characters is typed literally; the text shown in italics is replaced by whatever is appropriate for the applet you're including in the document. As you can see, the <applet> tag is similar to other HTML tags with which you may be familiar. For example, the tag starts with <applet attributes> and ends with </applet>, which is not unlike the format of other HTML tags. The first and last lines are required. Other lines in the tag are optional.

The attributes section of the <applet> tag conta ...

Post view interrupted. To view full content, click here
9/1/2011 8:40:00 PM





Article - New syntax of Java 7 (Project Coin)

Project coin is one of the projects that were developed for the implementation of Java 7.

The project idea was to add small changes in language, without having to depend on other projects, and without forcing developers to join the new syntax.

After several suggestions, was chosen about five modifications:

* Ability to use strings in switch
* Try-to-resources & Multi-catch
* Improvement in the creation of objects using generics (diamond)
* Simplify methods with variable number of arguments.
* Support for dynamic languages ??JSR 292

In this tutorial I will (try to) explain the use of the new syntax of the first three items on the list.

(The last two are very specific to your area, more information about them can be found in their links)

Strings in switch

The operator switch until the previous versions only supported types char, byte, short, int, Character, Byte, Short, Integer or enums.

In the new version, it is also possible to use Strings. Before, the only way was to make chains of if-else, for example:

String string = //anything  

  

if(string.equals("one"){  

} else if(string.equals("two"){  

  

}  else if(string.equals("three"){  

    

}  else if(string.equals("four"){  

     

} else {  

  //default  

}  



In  java 7 this same piece of code can be written with a switch:

 

String string = //anything

switch(string){  

case "one":   

              //one  

              break;  

case "two":   

              //two 

              break;  

case "three":   

              //three 

              break;  

case "four":   

              //four

              break;  

default :  

             //default  

}  

 

try-with-resources

It was created a new interface: AutoCloseable. All classes that implement (directly or indirectly) this interface are considered to be resources and have to be flushed (. Close ()) after use.

With the new try, it is possible that these resources are automatically closed  after the execution of the block (either for normal execution or exception).

An example of code that can be modified to use the new feature is this: a method that makes a query to the database, and uses a statement as a resource:

public static void viewTable(Connection con) throws SQLException {  

 

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";  

   Statement stmt;  

  try{  

     stmt = con.createStatement();  

     ResultSet rs = stmt.executeQuery(query);  

 

     while (rs.next()) {  

       String coffeeName = rs.getString("COF_NAME");  

       int supplierID = rs.getInt("SUP_ID");  

       float price = rs.getFloat("PRICE");  

       int sales = rs.getInt("SALES");  

       int total = rs.getInt("TOTAL");  

...

Post view interrupted. To view full content, click here
8/31/2011 11:27:00 AM





Article - Knowing the Hibernate Validator - Part 1

About the article:

This article introduces the Hibernate Validator, reference implementation of JSR 303 - Bean Validation API. This API allows you to easily validate, class objects that represent the application domain.

What is it for?

This article introduces developers to the Hibernate Validator API, which allows to incorporate data validation from the application through an easy to use and customizable API.

When this subject is useful:

Developers who want to learn how the Hibernate Validator works and how to integrate it into their applications will find detailed explanations in this article on how this API works.

Knowing the Hibernate Validator:

The Bean Validation API, represented by the JSR 303 was released in December 2009. Hibernate Validator has emerged as the reference implementation of this API and lets you use annotations to validate data quickly and easily. The biggest advantage is that the Bean Validation API is independent of the application layer where it is used and even in the way it is coded, allowing it to be used in various scenarios. This article discusses in detail how the Hibernate Validator works.

 

 In December 2009, the final version of JSR 303 was released. It's about the Bean Validation API that allows quickly and easily data validation through the use of annotations. The purpose of this JSR is the validation of the data present in the classes that model the application domain, which usually follow the standard JavaBeans. What's interesting is that the Bean Validation API is independent of the application layer where it is used and even the way of how we code it. It can be used in both desktop and web applications, and isn't tied to the persistence mechanism used. Thus, can be used in various scenarios.

Data validation was always present in systems that receive input from the user. Each framework implements a proprietary mechanism to validate the information, which created incompatibility problems and was harder to integrate.

With the advent of JSR 303 has established a standard API for validation, which is flexible enough to be used for many different types of frameworks. In addition, the Bean Validation API provides data validation classes in the application domain, which is simpler than when the process is done by layer. In the layer validation, it is necessary to verify the same data several times (in the presentation layer, business, persistence, etc.). In order to ensure information consistency. By validating the data directly in the domain classes, the whole process is centralized, therefore the objects of these classes typically runs thru the application layers.

The JSR 303 implementation reference is the Hibernate Validator, which will be explained in detail throughout this article.

Configuring Hibernate Validator

To work with the API you must use Java version 5 or higher, since the Hibernate Validator is not compatible with earlier versions of JDK. Setting the application to use the API is simple. The first step is to download from the project official website, which can be found in the reference section. The version available until the time of this writing is 4.1.0.

After unpacking the file (which can be downloaded in ZIP or TGZ format), simply add the following JARs in your application's classpath: hibernate-validator-4.1.0.Final.jar, log4j-1.2.14.jar, slf4j-api-1.5.6.jar, slf4j-log4j12-1.5.6.jar and validation-api-1.0.0.Ga.jar.They are all inside of the downloaded compressed file. If your application use Java 5 instead of 6, you must also add the API JAXB JARs: JAXB-api-2.2.jar and JAXB-impl-2.1.12.jar.This set of files is the minimum necessary to set the Hibernate Validator to work.

Setting constraints using annotations

The constraints are used to define rules regarding the data of an object. You can, for example, define that a particular attribute can not be null or that a value of a numeric attribute must be within a defined interval. When the data validation process is performed, a verification is made to check if the data are consistent with the established rules.

When you need to add validation constraints in the code, this is done through the use of annotations. Hibernate Validator comes with a set of annotations for common validations, although the API allows the programmer to make customizations. The creation of custom constraints will be addressed later in this article.

There are two places where constraints may apply. The first is directly in the class attribute. In this case the Java directly accesses the attribute thru reflection in order to do the validation. Listing 1 shows an example. The second form of implementation of constraints can be used when the class follows the specification of a JavaBean. In this case you can use the annotation on the getter method of the attribute. Listing 2 shows how this can be done. You must choose only one option, because if both are used the validation will be done twice.

 

Listing 1.Using the constraint @NotNull on the attribute.

public class Student {

 

  @NotNull

  private String name;

}

 

Listing 2.Using the constraint @NotNull on the getter method.

public class Student {

 

  @NotNull

  public String getName () {

    return name;

  }

}

All elements of the Hibernate Validator (classes, interfaces, annotations, etc..) Used by your code belong to the package javax.validation.

In addition to the annotation @NotNull shown in the example, which verifies that the data is not null, there are other important annotations included in Hibernate Validator. Following we are going to discuss some of them in more details. For more information about these and other annotations, refer to JSR 303 and the Hibernate Validator documentation.

@AssertFalse and @AssertTrue

These annotations validate if the data is true or false, respectively. Should be implemented in Boolean data (the primitive type Boolean and Boolean class are supported).Listing 3 shows both constraints. The attribute hasWarnings shall be false while fullAge must be true.

 

Listing 3.Using the annotations @AssertTrue and @AssertFalse.

public class Student {

 

  @AssertFalse

  private boolean hasWarning;

 

  @AssertTrue ...

Post view interrupted. To view full content, click here
7/29/2011 11:21:00 AM





Article - Knowing the Hibernate Validator - Part 2

This article is a continuation of the post http://www.mrbool.com/articles/viewcomp.asp?comp=21877 

Using validation groups

Often it is desirable to separate in groups the validations that should be accomplished. This allows the validation of only part of the constraints defined in the class, and not all of them at once.

Hibernate Validator support this separation. Each group is usually represented by a marker interface, which has no methods or attributes. It is important to understand that every time the validation process is invoked, you must specify one or more groups of validation. When a group is not explicitly provided, Hibernate Validator uses the group javax.validation.groups.Default as default. Listing 11 shows the class Student and the constraints made ​​to its attributes. As the constraints do not refer to a specific group, the default is used.

 

Listing 11.Restrictions on Student class defined in the standard group validation.

public class Student {

 

  @NotNull

  private String name;

 

  @Min(3)

  private int age;

 

  @Size (max = 10)

  private String numEnrollment;

 

  @NotNull

  private Date dateEnrollment;

}

 

Validation should always be associated with one or more groups, which are passed as parameters to methods validate(), validateProperty() andvalidateValue(). To validate the default group, simply omit this information (the calls validate(student) and validate(studentjavax.validation.groups.Default.class) have exactly the same effect in this case). The invocation of the validation process takes into account only the constraints of the specified groups and ignores the rest. At this point, it is noteworthy that each constraint can belong to one or more groups.

Knowing now that every invocation of validation is done in one or more groups and that all constraints belong to at least one group, it is easy to understand the process of grouping constraints. The first step is the creation of groups, and Listing 12 shows the definition of two of them:PersonalData and EnrollmentData.

 

Listing 12.Definition of groups PersonalData and EnrollmentData.

public interface PersonalData {

}

 

public interface EnrollmentData {

}

 

Then you need to declare the constraints using the newly created groups, rather than the standard group. This is done through the attribute groupspresent in all annotations used for validation. Listing 13 shows the attributes name and age were assigned to the group PersonalData andnumEnrollment and dateEnrollment being assigned to EnrollmentData. If it is necessary to assign more than one group to a constraint, simply provide an array with the interfaces to the element groups from the annotation.If a constraint @NotNull is applied to both groups, for example, it could be declared as @NotNull (groups = {PersonalData.class, EnrollmentData.class}).

 

Listing 13.Organizing the constraints in groups.

public class Student {

 

  @NotNull (groups = PersonalData.class)

  private String name;

 

  @Min (value = 3, groups = PersonalData.class)

  private int age;

 

  @Size (max = 10, groups = EnrollmentData.class)

  private String numEnrollment;

 

  @NotNull (groups = EnrollmentData.class)

  private Date dateEnrollment;

}

 

Finally, just inform the group to be validated at the time of invoking the validation.Indeed, it is even possible to validate more than one group in one invocation. Listing 14 shows three examples of calls to the validate() method. The first two rely on validation to a group at a time, and the third for both groups. Always remember that the constraints that are not part of groups where the validation is being performed are ignored.

 

Listing 14.Invoking the validation per group.

validator.validate (student PersonalData.class);

validator.validate (student EnrollmentData.class);

validator.validate (student PersonalData.class, EnrollmentData.class);

 

Besides the separation of validation in groups, another important aspect should be considered. By default, there are no guarantees about the order of the validation of the constraints In cases where it is important to ensure the order, you can use the annotation @GroupSequence.

@GroupSequence allows to define an execution order for the groups. Suppose you want to perform validations in groups PersonalData andEnrollmentData respecting that order.For this you need to create a new group and define which groups it will check and in what order.Listing 15shows the creation of the group FullData, which defines that the first validation will be done on the group PersonalData and then in the group EnrollmentData. To validate this new group, just reference it at the time of validation. Invoking validate (student, FullData.class) will run the validation of the groups PersonalData and EnrollmentData in this order.

 

Listing 15.FullData group definition with an validation order set.

@GroupSequence ({PersonalData.class, EnrollmentData.class})

public interface FullData {

}

When a validation error is found in a group, the next groups are not validated.

Another function of the annotation @GroupSequence is redefining the standard group for a class, which by default is thejavax.validation.groups.Default.To change this setting, simply use @GroupSequence at class level.Listing 16 shows its use in theStudent.Now, when the validation is invoked for the default group, the groups PersonalData and EnrollmentData will be called and that order will continue to be respected. Another important point is to always add the class being annotated as a member of the group defined by@GroupSequence, as was done with the Student class in Listing 16.   If this condi tion is not met, a GroupDefinitionException will be thrown.

 

Listing 16.Redefining the default group with the annotation @GroupSequence.

@GroupSequence ({Student.class, PersonalData.class, EnrollmentData.class})

public class Student {

  //...

}

Customizing error messages

When you use the Hibernate Validator and validation problems occur and you are faced with messages like: "may not be null", "must be greater than or equal to 70" or "size Must Be Between 2 and 10."It is evident that not always these messages, which are set by default in the API, are ideal for your application.

For this reason, Hibernate Validator allows customizations to be made in the messages. To understand how this process works, you should keep in mind that each constraint has an associated message descriptor. A message descriptor is nothing more than a template that defines how will be the resulting message.

If we consider the annotations @NotNull @Min and @Size, for example, their respectives messages descriptors are{javax.validation.constraints.NotNull.message}, {javax.validation.constraints.Min.message} and{javax.validation.constraints.Size.message}.This information can easily be obtained if the method getMessageTemplate() is invoked on aConstraintViolation (which represents a validation error, as explained earlier).Any information of the message descriptor declared between braces, in fact, is a parameter that will be replaced in the time of the final message generation, a process known as interpolation.

To perform the interpolation Hibernate Validator queries parameter value in the file org/hibernate/validator/ValidationMessages.properties, which is located within the Hibernate Validator JAR. Listing 17 shows the portion that corresponds to the messages of the annotations @NotNull,@Min and @Size. This file maps a key to a value where the key is the parameter of the message descriptor and the value is what needs to be generated as output when occurs the interpolation process.

 

Listing 17.Part of the file ValidationMessages.properties provided by Hibernate Validator.

javax.validation.constraints.NotNull.message = may not be null

javax.validation.constraints.Min.message = must be greater than or equal to {value}

javax.validation.constraints.Size.message = size must be between {min} and {max}

 

To customize the error messages, you must create an ValidationMessages.properties file and redefine the messages. It should be at the root of the classpath of your application and has read precedence over the default Hibernate Validator file.Listing 18 shows how could be theValidationMessages.properties file of your application, which changes the messages generated for constraints with null value, minimum value and size.

 

Listing 18.ValidationMessages.properties file of the application.

javax.validat ion.constraints.NotNull.message = The data can not be null

javax.validation.constraints.Min.message = The value must be greater than or equal to {value}

javax.validation.constraints.Size.message = The data length must be between {min} and {max}

 

Another possibility which the API provides is to override the message descriptor of only one constraint.Thi ...

Post view interrupted. To view full content, click here
7/29/2011 11:21:00 AM





 

gladstone@clubedelphi.net

Mr.Bool team writes articles to several sites on internet
Archive updates
 2013
 2011

Stats:
Total posts: 13
What people think:
Technical content:
People learning:
His posts are helpful?
16 2