<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>JavaWorld's Daily Brew</title>
  <subtitle>Starting conversations in the Java developer community</subtitle>
  <link rel="alternate" type="text/html" href="http://www.javaworld.com/community"/>
  <link rel="self" type="application/atom+xml" href="http://www.javaworld.com/community/atom/feed"/>
  <id>http://www.javaworld.com/community/atom/feed</id>
  <updated>2012-01-13T00:01:21-05:00</updated>
  <entry>
    <title>JavaFX 2 Animation: Path Transitions</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8311" />
    <id>http://www.javaworld.com/community/node/8311</id>
    <published>2012-02-06T23:41:00-05:00</published>
    <updated>2012-02-07T00:01:30-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>One of the flashiest aspects of <a href="http://javafx.com/">JavaFX</a> 2 is its <a href="http://www.asgteach.com/blog/?p=372">animation</a> support. The insightful <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm">Creating Transitions and Timeline Animation in JavaFX</a> covers using both <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm#CJAJJAGI">Transitions</a> and <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm#CJAFADFJ">Timelines</a> in JavaFX 2.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>One of the flashiest aspects of <a href="http://javafx.com/">JavaFX</a> 2 is its <a href="http://www.asgteach.com/blog/?p=372">animation</a> support. The insightful <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm">Creating Transitions and Timeline Animation in JavaFX</a> covers using both <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm#CJAJJAGI">Transitions</a> and <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm#CJAFADFJ">Timelines</a> in JavaFX 2. In this blog post, I adapt an example provided in that tutorial to specifically demonstrate Path Transitions.</p>

<p>Example 2 ("Path Transition") shown in <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm">Creating Transitions and Timeline Animation in JavaFX</a> demonstrates creating a Path with classes from the JavaFX 2 "shapes" package: <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/shape/Path.html">javafx.scene.shape.Path</a>, <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/shape/MoveTo.html">javafx.scene.shape.MoveTo</a>, and <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/shape/CubicCurve.html">javafx.scene.shape.CubicCurve</a>. That example then demonstrates instantiation of a <a href="http://docs.oracle.com/javafx/2.0/api/javafx/animation/PathTransition.html">javafx.animation.PathTransition</a> and applying an instantiated <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/shape/Rectangle.html">javafx.scene.shape.Rectangle</a> to move along the created Path.</p>

<p>In my code listing below, I've made some slight changes to Example 2 in <a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm">Creating Transitions and Timeline Animation in JavaFX</a>. I have specifically changed the moving shape from a rectangle to a <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/shape/Circle.html">Circle</a>, added two "end knobs" to the path as two separate circles, and added the ability to change the opacity of the path along with the animated circle moves. The nice side effect of using a zero opacity is that the path itself does not appear and it instead looks like the circle is moving along freely. I tried to break each major piece of this up into its own private method to make it easier to see the "chunks" of functionality.</p>

<strong>JavaFxAnimations.java</strong>
<pre name="code" class="java" style="font-size: 9pt; overflow: auto;">
package dustin.examples;

import java.util.List;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * Simple example demonstrating JavaFX animations.
 * 
 * Slightly adapted from Example 2 ("Path Transition") which is provided in
 * "Creating Transitions and Timeline Animation in JavaFX"
 * (<a href="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm" title="http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm">http://docs.oracle.com/javafx/2.0/animations/jfxpub-animations.htm</a>).
 * 
 * @author Dustin
 */
public class JavaFxAnimations extends Application
{
   /**
    * Generate Path upon which animation will occur.
    * 
    * @param pathOpacity The opacity of the path representation.
    * @return Generated path.
    */
   private Path generateCurvyPath(final double pathOpacity)
   {
      final Path path = new Path();
      path.getElements().add(new MoveTo(20,20));
      path.getElements().add(new CubicCurveTo(380, 0, 380, 120, 200, 120));
      path.getElements().add(new CubicCurveTo(0, 120, 0, 240, 380, 240));
      path.setOpacity(pathOpacity);
      return path;
   }

   /**
    * Generate the path transition.
    * 
    * @param shape Shape to travel along path.
    * @param path Path to be traveled upon.
    * @return PathTransition.
    */
   private PathTransition generatePathTransition(final Shape shape, final Path path)
   {
      final PathTransition pathTransition = new PathTransition();
      pathTransition.setDuration(Duration.seconds(8.0));
      pathTransition.setDelay(Duration.seconds(2.0));
      pathTransition.setPath(path);
      pathTransition.setNode(shape);
      pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
      pathTransition.setCycleCount(Timeline.INDEFINITE);
      pathTransition.setAutoReverse(true);
      return pathTransition;
   }

   /**
    * Determine the path's opacity based on command-line argument if supplied
    * or zero by default if no numeric value provided.
    * 
    * @return Opacity to use for path.
    */
   private double determinePathOpacity()
   {
      final Parameters params = getParameters();
      final List&lt;String&gt; parameters = params.getRaw();
      double pathOpacity = 0.0;
      if (!parameters.isEmpty())
      {
         try
         {
            pathOpacity = Double.valueOf(parameters.get(0));
         }
         catch (NumberFormatException nfe)
         {
            pathOpacity = 0.0;
         }
      }
      return pathOpacity;
   }

   /**
    * Apply animation, the subject of this class.
    * 
    * @param group Group to which animation is applied.
    */
   private void applyAnimation(final Group group)
   {
      final Circle circle = new Circle(20, 20, 15);
      circle.setFill(Color.DARKRED);
      final Path path = generateCurvyPath(determinePathOpacity());
      group.getChildren().add(path);
      group.getChildren().add(circle);
      group.getChildren().add(new Circle(20, 20, 5));
      group.getChildren().add(new Circle(380, 240, 5));
      final PathTransition transition = generatePathTransition(circle, path);
      transition.play(); 
   }

   /**
    * Start the JavaFX application
    * 
    * @param stage Primary stage.
    * @throws Exception Exception thrown during application.
    */
   @Override
   public void start(final Stage stage) throws Exception
   {
      final Group rootGroup = new Group();
      final Scene scene = new Scene(rootGroup, 600, 400, Color.GHOSTWHITE);
      stage.setScene(scene);
      stage.setTitle("JavaFX 2 Animations");
      stage.show();
      applyAnimation(rootGroup);
   }

   /**
    * Main function for running JavaFX application.
    * 
    * @param arguments Command-line arguments; optional first argument is the
    *    opacity of the path to be displayed (0 effectively renders path
    *    invisible).
    */
   public static void main(final String[] arguments)
   {
      Application.launch(arguments);
   }
}
</pre>

<p>The following series of screen snapshots show this simple JavaFX animation example in action. They are listed in order of descending opacity (from 1.0 to 0.0).</p>

<strong>Demonstration of Adapted PathTransition Example (Opacity 1.0)</strong>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-6cBHRPCjnqE/TzCmt7LUpPI/AAAAAAAAC_4/El7lUUlYuY4/s1600/pathTransitionOpacity1BallOnPath.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="226" width="320" src="http://2.bp.blogspot.com/-6cBHRPCjnqE/TzCmt7LUpPI/AAAAAAAAC_4/El7lUUlYuY4/s320/pathTransitionOpacity1BallOnPath.png" /></a></div>

<strong>Demonstration of Adapted PathTransition Example (Opacity 0.2)</strong>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-X3Vapb9DqdE/TzCmyrT8HbI/AAAAAAAADAE/Jlm7fH39wjw/s1600/pathTransitionOpacity02BallOnPath.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="226" width="320" src="http://1.bp.blogspot.com/-X3Vapb9DqdE/TzCmyrT8HbI/AAAAAAAADAE/Jlm7fH39wjw/s320/pathTransitionOpacity02BallOnPath.png" /></a></div>

<strong>Demonstration of Adapted PathTransition Example (Opacity 0.05)</strong>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-QG5Cd-tXAEU/TzCm2iWxTcI/AAAAAAAADAU/vMYI9CIEYLk/s1600/pathTransitionOpacity005BallOnPath.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="226" width="320" src="http://2.bp.blogspot.com/-QG5Cd-tXAEU/TzCm2iWxTcI/AAAAAAAADAU/vMYI9CIEYLk/s320/pathTransitionOpacity005BallOnPath.png" /></a></div>

<strong>Demonstration of Adapted PathTransition Example (Opacity 0.0)</strong>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-ysyVlBfL03A/TzCm7h3UqqI/AAAAAAAADAc/M_4k65Ij7OA/s1600/pathTransitionOpacity0BallOnPath.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="226" width="320" src="http://1.bp.blogspot.com/-ysyVlBfL03A/TzCm7h3UqqI/AAAAAAAADAc/M_4k65Ij7OA/s320/pathTransitionOpacity0BallOnPath.png" /></a></div>

<p>Each of the above screen snapshots was taken after running the application with the specified command-line argument (1, 0.2, 0.05, and 0).</p>

<p>This adapted example has demonstrated using <code>PathTransition</code> to animate a node's movement along the prescribed path (I have <a href="http://marxsoftware.blogspot.com/2011/12/javafx-20-christmas-tree-javafx-20.html">blogged on use of Path</a> and some of its <a href="http://marxsoftware.blogspot.com/2011/12/javafx-20-path-alternatives.html">alternatives</a> before). Developers can implement their own derivative of <a href="http://docs.oracle.com/javafx/2.0/api/javafx/animation/Transition.html">Transition</a> and there are other supplied transitions supported as well (such as <a href="http://docs.oracle.com/javafx/2.0/api/javafx/animation/FadeTransition.html">FadeTransition</a>, <a href="http://docs.oracle.com/javafx/2.0/api/javafx/animation/ParallelTransition.html">ParallelTransition</a>, and <a href="http://docs.oracle.com/javafx/2.0/api/javafx/animation/SequentialTransition.html">SequentialTransition</a>).</p>

<p>It is a straightforward process to quickly begin applying JavaFX 2 animation using the provided Transition classes.</p><div class="blogger-post-footer"><p>Original posting available at <a href="http://marxsoftware.blogspot.com/">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6517450204508339514-46725781961741473?l=marxsoftware.blogspot.com" alt="" /></div><img src="http://feeds.feedburner.com/~r/InspiredByActualEvents/~4/UwG6fbsZBzA" height="1" width="1" />    ]]></content>
  </entry>
  <entry>
    <title>The Passage of Time</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8310" />
    <id>http://www.javaworld.com/community/node/8310</id>
    <published>2012-02-06T13:21:57-05:00</published>
    <updated>2012-02-06T13:21:58-05:00</updated>
    <author>
      <name>Jeff Friesen</name>
    </author>
    <category term="beginning java 7" />
    <category term="clock" />
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter-->I introduced my <em>Java Tutor</em> blog last February, to teach about various Java technologies. Starting in July, I suspended this blog for several months to focus exclusively on <em>Beginning Java 7</em>, a beginner-oriented book on Java 7 that I wrote for Apress.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter-->I introduced my <em>Java Tutor</em> blog last February, to teach about various Java technologies. Starting in July, I suspended this blog for several months to focus exclusively on <em>Beginning Java 7</em>, a beginner-oriented book on Java 7 that I wrote for Apress. This book’s cover appears in Figure 1.

<p>
<img src="http://tutortutor.ca/blogs/jt/11/figure1.jpg">

<p>
<strong>Figure 1:</strong> Visit <a 
href="http://tutortutor.ca/cgi-bin/makepage.cgi?/books/bj7">http://tutortutor.ca/cgi-bin/makepage.cgi?/books/bj7</a> to learn about Beginning Java 7.

<p>
<em>Beginning Java 7</em> consists of twelve chapters and four appendixes (the appendixes are not included in the print version). Now that I’ve finished the print version, I’m resuming this blog by excerpting the <code>Clock</code> application from this book’s Appendix D (Applications Gallery).

<p>
<table border=1>
<tr> 
<td> 
<strong>Note:</strong> I recently refactored Java Tutor to focus only on Java 7 and successor versions of the Java standard edition, as well as on JavaFX 2.0 and successor versions. I eliminated my four-part series on Android Gingerbread because Android isn’t relevant to my new focus. I also revisited each post to ensure that code and content are compliant with JDK 7u2. Regarding my two-part <em>Rebooting JavaFX</em> series, I made sure that code and content are compliant with JDK 7u2 and JavaFX 2.0.2.
</td>
</tr>
</table>

<h2>
Analog Clock
</h2>

A clock displays the current time in digital or analog format. Creating a digital clock application is trivial, but creating an application that presents an analog clock with moving hour/minute/second hands isn’t so easy. Listing 1 presents the source code to a <code>Clock</code> application that reveals one way to simulate an analog clock.

<p>
<pre style="background: #eeeeee; padding: 5px">import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Calendar;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;

class Clock extends JFrame
{
   Clock()
   {
      super("Clock");
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setContentPane(new SwingCanvas());
      pack();
      setVisible(true);
   }
   public static void main(String[] args)
   {
      Runnable r = new Runnable()
                   {
                      @Override
                      public void run()
                      {
                         new Clock();
                      }
                   };
      EventQueue.invokeLater(r);
   }
}
class SwingCanvas extends JComponent
{
   private final static int BORDER_WIDTH = 10;
   private BasicStroke bs;
   private Calendar cal;
   private Dimension d;
   private Font font;
   private int width;
   SwingCanvas()
   {
      bs = new BasicStroke(2.5f);
      cal = Calendar.getInstance();
      d = new Dimension(300, 300);
      font = new Font("Arial", Font.BOLD, 14);
      width = d.width-2*BORDER_WIDTH;
      ActionListener al;
      al = new ActionListener()
           {
              @Override
              public void actionPerformed(ActionEvent ae)
              {
                 cal.setTimeInMillis(System.currentTimeMillis());
                 repaint();
              }
           };
      new Timer(50, al).start();
   }
   @Override
   public Dimension getPreferredSize()
   {
      return d;
   }
   @Override
   public void paint(Graphics g)
   {
      Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.translate(BORDER_WIDTH, BORDER_WIDTH);
      Stroke stroke = g2d.getStroke();
      // Paint oval.
      g2d.setStroke(bs);
      g2d.drawOval(0, 0, width, width);
      g2d.setStroke(stroke);
      // Paint tick marks.
      int tickEnd = width/2;
      for (int second = 0; second < 60; second++)
      {
         int tickStart;
         if (second%5 == 0)
            tickStart = tickEnd-26; // long tick
         else
            tickStart = tickEnd-13;  // short tick
         drawSegment(g2d, second/60.0, tickStart, tickEnd);
      }
      // Paint hour labels.
      g2d.setFont(font);
      for (int hour = 1; hour <= 12; hour++)
      {
         double angle = (hour-3)*2*Math.PI/12;
         int x = (int) (Math.cos(angle)*(width/2-35))+width/2-5;
         int y = (int) (Math.sin(angle)*(width/2-35))+width/2+5;
         g2d.drawString(""+hour, x, y);
      }
      // Paint hands.
      int hour = cal.get(Calendar.HOUR);
      int min = cal.get(Calendar.MINUTE);
      int sec = cal.get(Calendar.SECOND);
      int ms = cal.get(Calendar.MILLISECOND);
      int secHandMaxRad = width/2-5;
      double fracSec = (sec+ms/1000.0)/60.0;
      g2d.setColor(Color.RED);
      drawSegment(g2d, fracSec, 0, secHandMaxRad);
      g2d.setColor(Color.BLACK);
      int minHandMaxRad = width/3-10;
      double fracMin = (min+fracSec)/60.0;
      drawSegment(g2d, fracMin, 0, minHandMaxRad);
      int hrHandMaxRad = width/4;
      drawSegment(g2d, (hour+fracMin)/12.0, 0, hrHandMaxRad);
   }
   private void drawSegment(Graphics2D g2d, double fraction, int start, int end)
   {
      double angle = fraction*Math.PI*2-Math.PI/2.0;
      double _cos = Math.cos(angle);
      double _sin = Math.sin(angle);
      double minx = width/2+_cos*start;
      double miny = width/2+_sin*start;
      double maxx = width/2+_cos*end;
      double maxy = width/2+_sin*end;
      g2d.drawLine((int) minx, (int) miny, (int) maxx, (int) maxy);
   }
}</pre>

<p>
<strong>Listing 1:</strong> Simulating an analog clock

<p>
Listing 1 consists of <code>Clock</code> and <code>SwingCanvas</code> classes. <code>Clock</code> serves as this application’s main class and trivially constructs a GUI consisting of a single <code>SwingCanvas</code> instance. <code>SwingCanvas</code> describes a specialized Swing component for displaying a clock face with moving hands, and also contains animation logic for animating this clock to constantly display the current time.

<p>
<code>SwingCanvas</code> first declares the following fields:

<ul>
<li>
<code>BORDER_WIDTH</code>: an integer constant that describes the number of pixels to reserve as a border around the clock face. The border gives the clock a nicer appearance.
</li>

<p>
<li>
<code>bs</code>: A <code>java.awt.BasicStroke</code> instance that determines the thickness of the clock face’s round outline. (Chapter 7 introduces <code>BasicStroke</code>.)
</li>

<p>
<li>
<code>cal</code>: A <code>java.util.Calendar</code> instance that’s used to extract the current time in terms of hour, minute, second, and millisecond. (Appendix C introduces <code>Calendar</code>.)
</li>

<p>
<li>
<code>d</code>: A <code>java.awt.Dimension</code> instance that stores the <code>SwingCanvas</code> component’s preferred size. (Chapter 7 introduces <code>Dimension</code>.)
</li>

<p>
<li>
<code>font</code>: A <code>java.awt.Font</code> instance that identifies the font used to display the clock face’s text. (Chapter 7 introduces <code>Font</code>.)
</li>

<p>
<li>
<code>width</code>: An integer that specifies the width of the <code>SwingCanvas</code> component’s drawing area less its border.
</li>
</ul>

<p>
These fields are followed by a <code>SwingCanvas()</code> constructor that initializes them to appropriate values. This constructor then creates and starts a Swing timer that fires action events after an initial 50-millisecond delay and at 50-millisecond intervals. Each time an event is fired, the registered action listener initializes the <code>Calendar</code> instance to the current time via <code>cal.setTimeInMillis(System.currentTimeMillis());</code>, and then invokes <code>repaint()</code> to redraw the clock face to reflect this value.

<p>
The overriding <code>getPreferredSize()</code> method returns the component’s preferred size and the overriding <code>paint()</code> method redraws the clock face.

<p>
<code>paint()</code> first performs initial graphics setup by activating antialiasing (see Chapter 7), which ensures that the clock face looks smooth (no jagged edges), and by translating the drawing area’s (0, 0) origin to (<code>BORDER_WIDTH</code>, <code>BORDER_WIDTH</code>), to facilitate drawing.

<p>
Next, <code>paint()</code> saves the current stroke attribute value, installs the custom stroke that was created in the constructor, draws the clock face’s circular outline using the custom stroke, and resets the stroke attribute to its previously saved value.

<p>
At this point, <code>paint()</code> draws sixty tick marks (line segments) around the clock face. Each tick mark is a drawn segment of the invisible radius line (at a particular angle) that extends from the circle’s center to its circumference. Its start and end limits are stored in local variables <code>tickStart</code> and <code>tickEnd</code>.

<p>
<code>paint()</code> continues by installing the previously created font, and then drawing the hour labels around the clock face and closer to the circle’s center than the tick marks. For each hour from 1 to 12, it first calculates an angle (in radians) for where the hour’s textual label should appear. Because angles are relative to the 3 o’clock position, hour label 0 would appear at this position if it existed, hour label 1 would appear at the 4 o’clock position, and so on unless 3 was subtracted from the hour value before calculating the angle.

<p>
After the angle has been calculated, the <code>java.lang.Math</code> class’s <code>double cos(double angle)</code> and <code>double sin(double angle)</code> class methods are invoked to calculate the (x, y) location on the circumference of a unit circle that corresponds to the angle. These values are multiplied by the circle’s radius less a value so that they appear inside the tick marks perimeter; an offset is added to the result so that the location is relative to the center of the component drawing area and not the translated origin. A small offset is subtracted from the x location and added to the y location so that the label is roughly centered below its long tick mark.

<p>
<code>paint()</code>’s final task is to paint the second, minute, and hour hands. It first invokes <code>Calendar</code> methods to obtain the current hour, minute, second, and millisecond values – the millisecond value enables the hands to move smoothly in an analog fashion rather than jump forward in a digital fashion.

<p>
Each hand is drawn starting from the circle’s center, but not all the way to the circumference. For example, the second hand is drawn to 5 pixels short of the circumference (<code>width/2-5</code>). To distinguish the second hand from the minute and hour hands, the second hand is drawn in red whereas the other hands are drawn in black (the hour hand is shorter to distinguish it from the minute hand).

<p>
The <code>paint()</code> method relies on the <code>drawSegment()</code> method to draw tick marks and clock hands. The first argument passed to this method is the graphics context, the second argument is a fraction between 0.0 and 1.0 that represents the amount of clockwise angular movement from the 3 o’clock position, and the third and fourth arguments define the start and end of the visible portion of the radius to display.

<p>
This method first calculates the angle via expression <code>fraction*Math.PI*2-Math.PI/2.0</code>. It subtracts <code>Math.PI/2</code> from <code>fraction*Math.PI*2</code> to make the angle relative to the 12 o’clock position.

<p>
It next calculates the angle’s cosine and sine, and uses these values with the <code>start</code> and <code>end</code> arguments and the <code>width</code> field variable’s value to calculate the starting and ending positions of the line segment to draw.

<p>
Compile Listing 1 (<code>javac Clock.java</code>) and run this application (<code>java Clock</code>). You should see output similar to that shown in Figure 2.

<p>
<img src="http://tutortutor.ca/blogs/jt/11/figure2.jpg">

<p>
<strong>Figure 2:</strong> <code>Clock</code> presents the current time in analog format.

<h2>
Moving Forward
</h2>

Future posts will introduce you to more Java-oriented topics. Along with tutorials on language, API, and other Java features, I’ll cover various aspects of JavaFX (including a detailed study of binding). Many of the posts will focus on various projects, including projects related to compiler construction and other tools. Not everything will be exclusively about Java, 
but Java will be involved in some fashion.

<p>
I won’t be posting regularly, but will post at least once or twice a month.

<h2>Exercises</h2>

<ol>
<li>
Digital clocks present an AM/PM indicator, but <code>Clock</code> does not have this capability. Modify <code>Clock</code> to indicate whether the specified time reflects AM or PM (e.g., 3AM or 5PM).
</li>
</ol>

<h2>Code</h2>

<p>
You can download this post's code and answers <a href="http://tutortutor.ca/blogs/jt/11/code.zip">here</a>. Code was developed and tested with JDK 7u2 on a Windows XP SP3 platform.

<p>
* * *

<p>
I welcome your input to this blog, and will write about relevant topics that you suggest. While waiting for the next blog post, check out my <a href="http://tutortutor.ca">TutorTutor website</a> to learn more about Java and other computer technologies (and that's just the beginning).    ]]></content>
  </entry>
  <entry>
    <title>Properties with Spring</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8309" />
    <id>http://www.javaworld.com/community/node/8309</id>
    <published>2012-02-06T09:42:43-05:00</published>
    <updated>2012-02-06T10:00:17-05:00</updated>
    <author>
      <name>baeldung</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>Spring has always tried to be as transparent as possible when it comes to working with properties. Before Spring 3.1 however, the mechanism of both adding new sources of properties into Spring as well as actually using the properties wasn’t as flexible and as robust as it could be.</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Spring has always tried to be as transparent as possible when it comes to working with properties. Before Spring 3.1 however, the mechanism of both adding new sources of properties into Spring as well as actually using the properties wasn’t as flexible and as robust as it could be.</p><p>Starting with Spring 3.1, the new <em>Environment</em> and <em>PropertySource</em> abstractions simplify working with properties. The <strong>default Spring Environment</strong> now contains two property sources: the System properties and the JVM properties, with the System properties having precedence.</p><p>For more information on the unified property management in Spring 3.1, see <a title="Spring 3.1 M1: Unified Property Management" href="http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/" target="_blank">this official article</a>.</p><h2>Registering Properties via the XML namespace</h2><p>In an XML configuration, new property files can be made accessible to Spring via the following namespace element:</p> <script src="https://gist.github.com/1752323.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752323">Gist</a>.</p></noscript><h2>Registering Properties via Java Annotations</h2><p>Spring 3.1 also introduces <strong>the new <em>@PropertySource</em> annotation</strong>, as a convenient mechanism of adding property sources to the environment. This annotation is to be used in conjunction with Java based configuration and the <em>@Configuration</em> annotation:</p> <script src="https://gist.github.com/1752330.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752330">Gist</a>.</p></noscript><p>As opposed to using XML namespace element, the Java <em>@PropertySource</em> annotation <strong>does not automatically register a <em>PropertySourcesPlaceholderConfigurer</em> with Spring</strong>. Instead, the bean must be explicitly defined in the configuration to get the property resolution mechanism working. The reasoning behind this unexpected behavior is by design and documented on <a title="Automatic registration of PSPC when @PropertySource is used" href="https://jira.springsource.org/browse/SPR-8539" target="_blank">this issue</a>.</p><h2>Behind the Scenes &#8211; the Spring Configuration</h2><h3>Before Spring 3.1</h3><p>Since the convenience of defining property sources with annotations was introduced in the recently released Spring 3.1, XML based configuration was necessary in the previous versions.</p><p>Defining a <em>&lt;context:property-placeholder&gt;</em> XML element automatically registers a new <em>PropertyPlaceholderConfigurer</em> bean in the Spring Context. This is also the case in Spring 3.1 if, for backwards compatibility purposes, the XSD schemas are not updated to the 3.1 versions.</p><h3>In Spring 3.1</h3><p>From Spring 3.1 onward, the XML <em>&lt;context:property-placeholder&gt;</em> will no longer register the old <em>PropertyPlaceholderConfigurer</em> but the newly introduced <em>PropertySourcesPlaceholderConfigurer</em>. This replacement class was created be more flexible and to better interact with the newly introduced <em>Environment</em> and <em>PropertySource</em> mechanism; it should be considered the standard for 3.1 applications.</p><h2>Properties by hand in Spring 3.0 &#8211; <em>PropertyPlaceholderConfigurer</em></h2><p>Besides the convenient methods of getting properties into Spring &#8211; annotations and the XML namespace &#8211; the property configuration bean can also be defined and registered <strong>manually</strong>. Working with the <em>PropertyPlaceholderConfigurer</em> gives us full control over the configuration, with the downside of being more verbose and most of the time, unnecessary.</p><h3>Java configuration</h3> <script src="https://gist.github.com/1752336.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752336">Gist</a>.</p></noscript><h3>XML configuration</h3> <script src="https://gist.github.com/1752350.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752350">Gist</a>.</p></noscript><h2>Properties by hand in Spring 3.1 &#8211; <em>PropertySourcesPlaceholderConfigurer</em></h2><p>Similarly, in Spring 3.1, the new <em>PropertySourcesPlaceholderConfigurer</em> can also be configured manually:</p><h3>Java configuration</h3> <script src="https://gist.github.com/1752360.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752360">Gist</a>.</p></noscript><h3>XML configuration</h3> <script src="https://gist.github.com/1752369.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752369">Gist</a>.</p></noscript><h2>Using properties in Spring</h2><p>Both the older <em>PropertyPlaceholderConfigurer</em> and the new <em>PropertySourcesPlaceholderConfigurer</em> added in Spring 3.1 <strong>resolve ${&#8230;} placeholders</strong> within bean definition property values and <em>@Value</em> annotations.</p><p>For example, to inject a property using the <em>@Value</em> annotation:</p> <script src="https://gist.github.com/1752404.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752404">Gist</a>.</p></noscript><p>Using properties in Spring XML configuration:</p> <script src="https://gist.github.com/1752450.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752450">Gist</a>.</p></noscript><p>And lastly, obtaining properties via the new Environment APIs:</p> <script src="https://gist.github.com/1752454.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1752454">Gist</a>.</p></noscript><h3>Properties Search Precedence</h3><p>By default, in Spring 3.1, local properties are search last, after all environment property sources, including property files. This behavior can be overridden via the <em>localOverride</em> property of the <em>PropertySourcesPlaceholderConfigurer</em>, which can be set to <em>true</em> to allow local properties to override file properties.</p><p>In Spring 3.0 and before, the old <em>PropertyPlaceholderConfigurer</em> also attempted to look for properties both in the manually defined sources as well as in the System properties. The lookup precedence was also customizable via the <em>systemPropertiesMode</em> property of the configurer:</p><ul><li><em><strong>never</strong></em> &#8211; Never check system properties</li><li><em><strong>fallback</strong></em> (default) &#8211; Check system properties if not resolvable in the specified properties files</li><li><em><strong>override</strong></em> &#8211; Check system properties first, before trying the specified properties files. This allows system properties to override any other property source.</li></ul><h2>Conclusion</h2><p>This article covered the various ways to work with Properties in Spring, discussing both the older Spring 3.0 and below and the new support for properties, introduced in Spring 3.1. For a project making heavy use of properties, check out the <a title="the github REST project containing the implementation for this post" href="https://github.com/eugenp/REST" target="_blank">github project</a>.</p><p>If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/#!/baeldung" target="_blank">follow me on twitter here</a>.</p> <img src="http://feeds.feedburner.com/~r/Baeldung/~4/lcFHdHmpQPY" height="1" width="1" />    ]]></content>
  </entry>
  <entry>
    <title>Book Review: JBoss AS 7: Configuration, Deployment, and Administration</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8308" />
    <id>http://www.javaworld.com/community/node/8308</id>
    <published>2012-01-31T22:04:00-05:00</published>
    <updated>2012-02-01T11:00:16-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><p>I eagerly accepted <a href="http://www.packtpub.com/" rel="nofollow" rel="nofollow">Packt Publishing</a>'s invitation to review <a href="https://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book" rel="nofollow" rel="nofollow">JBoss AS 7: Configuration, Deployment, and Administration</a> because it has been several years since I last used JBoss and I was curious to learn more about <a href="http://www.jboss.org/as7" rel="nofollow" rel="nofollow">JBoss AS 7</a>.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>I eagerly accepted <a href="http://www.packtpub.com/" rel="nofollow">Packt Publishing</a>'s invitation to review <a href="https://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book" rel="nofollow">JBoss AS 7: Configuration, Deployment, and Administration</a> because it has been several years since I last used JBoss and I was curious to learn more about <a href="http://www.jboss.org/as7" rel="nofollow">JBoss AS 7</a>. I have already written about my <a href="http://marxsoftware.blogspot.com/2012/01/first-impressions-of-book-jboss-as-7.html" rel="nofollow">First Impressions of Book 'JBoss AS 7 Configuration, Deployment and Administration'</a> and in this post I review the book in greater detail while attempting to minimize how much I repeat from that post. My review is based on an electronic (PDF) copy of <em>JBoss AS 7: Configuration, Deployment, and Administration</em>.</p>
<p><strong>General Features</strong></p>
<p><em>JBoss AS 7: Configuration, Deployment, and Administration</em> highlights particularly important notes and warnings within boxing that makes them obvious and with an icon representing a pencil and paper. Similarly, tips and tricks also attract special attention with similar boxing and with a light bulb icon. It is helpful to have the most important notes and tips and tricks highlighted like this.</p>
<p>It didn't take much reading of this book to realize how significantly new JBoss AS 7's architecture is. One of the strengths of <em>JBoss AS 7: Configuration, Deployment, and Administration</em> is its comparisons of previous versions of JBoss AS to JBoss AS 7. These comparisons help to understand how changed JBoss AS 7 is and should be especially helpful to anyone migrating to JBoss AS 7 from a previous version.</p>
<p>This book provides several tables of various configuration options and their descriptions. These tables provide easy reference for various configuration options. Although I mostly just skimmed these as I read this book, I noted their existence for future reference when configuring various parts of JBoss AS 7.</p>
<p>Command line interfaces and script-based configuration and administration are emphasized throughout the book. I appreciate this because I tend to use command line approaches far more frequently than I use graphical tools, but some books focus almost exclusively on the graphical tools.</p>
<p>Perhaps the greatest strength of <em>JBoss AS 7: Configuration, Deployment, and Administration</em> is its focus on what its title promises: configuration, deployment, and administration. Although this book does provide brief introductory details about Java EE, the book assumes that the reader will look to focused books or tutorials for detailed information on Java EE. This allows the book to focus on administration and configuration of and deployment to JBoss AS 7.</p>
<p>Although examples in the book specifically use Eclipse, MySQL, and Windows, the descriptions and explanations are broad enough to cover other choices of IDE, database, and operating system respectively. The illustrations assuming one of these are relatively rare and most of the discussion is more general to JBoss AS 7 rather than to any of these supporting products. In many of these cases, alternatives (and how to use those alternatives) are mentioned. The final chapter (cloud computing with OpenShift) and the Appendix (common commands and operations) provide Linux-based examples.</p>
<p>There is a small number of typos and a few instances of questionable sentence structure, but the author's writing style generally flows easily and is easy to follow. There are numerous drawings, tables, and screen snapshots to illustrate points and highlight the more important details. I like the significant white space and the call outs for special notes and observations.</p>
<p><strong>Chapter 1: Installing JBoss AS 7</strong></p>
<p>Because I have not used JBoss for several years, I needed to install JBoss AS 7 and <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_1" rel="nofollow">this chapter</a> provides an easy guide to doing that. The chapter begins with brief coverage of the usefulness of Java EE application servers and of JBoss AS 7's high-level design. It then moves into the practical steps necessary for installing JBoss AS 7. The author recommends in one of the "important notes" that readers download and use the Java 6 SDK, but does acknowledge that Java SE 7 SDK is available and should work fine with JBoss AS 7. The chapter discusses installation on Windows and Linux/Unix and even includes a "tip/trick" highlighting of installation on Windows Vista. The chapter goes beyond basic installation (which amounts to uncompressing archive files) to discuss starting and stopping JBoss AS 7 and using <a href="https://community.jboss.org/wiki/CommandLineInterface" rel="nofollow">Command Line Interface</a> (CLI) to connect to it locally and remotely.</p>
<p>The initial chapter also discusses installation of <a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a> ("the development environment used in this book"). Besides downloading and installing Eclipse (<a href="http://eclipse.org/indigo/" rel="nofollow">Indigo</a>), the chapter also discusses installation of the JBoss AS plugins (part of <a href="http://download.jboss.org/jbosstools/updates/development/indigo/" rel="nofollow">JBoss Tools</a>) for Eclipse.</p>
<p>One of my favorite parts of this initial chapter is its coverage of the application server's <a href="https://docs.jboss.org/author/display/AS7/Getting+Started+Guide#GettingStartedGuide-AS7DirectoryStructure" rel="nofollow">directory structure</a> and differentiation of JBoss AS 7's "standalone servers and domain servers." This was an important distinction for me coming back to JBoss after such a long period of time, but was an easy one to grasp because of my familiarity with <a href="http://glassfish.java.net/" rel="nofollow">GlassFish</a>. After differentiating between the types of servers supported in JBoss AS 7, the section concludes with coverage of several significant directories/folders in the JBoss AS 7 installation.</p>
<p><strong>Chapter 2: Configuring the Application Server</strong></p>
<p>With JBoss AS 7 and tools (Eclipse) installed, it is natural to move onto configuring the JBoss AS 7 instance. <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_2" rel="nofollow">This chapter</a> had some surprises for me, including starting with this: "The application configuration has also been renewed, moving from a large set of XML files to a single monolithic file." The chapter discusses this single file and covers its default names (depending on server configuration). It goes through the configuration file one major section at a time, detailing how to configure the server in each area. There is quite a bit in this chapter on configuring logging. Another thing I learned here that has changed in JBoss in recent years is default use of its <a href="https://community.jboss.org/thread/154993#555972" rel="nofollow">own logging framework</a>.</p>
<p><strong>Chapter 3: Configuring Enterprise Services</strong></p>
<p>The <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_3" rel="nofollow">third chapter</a> is on configuring enterprise services. This chapter specifically focuses on configuring database connectivity, EJB container, messaging service, and transaction service.</p>
<p>The section of Chapter 3 on configuring database connectivity mentions that JBoss AS 7 comes with the <a href="http://www.h2database.com/html/main.html" rel="nofollow">H2</a> open source database server built in, but then uses <a href="http://www.mysql.com/" rel="nofollow">MySQL</a> for its examples. I liked how this chapter compared and contrasted how database configuration was performed in previous versions of JBoss AS to how it is now done in JBoss AS 7. The chapter demonstrates XML-based configuration of a data source (and how it was similar to that used in previous versions of the JBoss application server), but then also shows <a href="http://blogs.oracle.com/Lance/entry/introducing_the_datasourcedefinition_annotation" rel="nofollow">how to use</a> the <a href="http://docs.oracle.com/javaee/6/tutorial/doc/" rel="nofollow">Java EE 6</a> annotation <a href="http://docs.oracle.com/javaee/6/api/javax/annotation/sql/DataSourceDefinition.html" rel="nofollow">@DataSourceDefinition</a> to programmatically configure the data source in conjunction with an <a href="http://www.theserverside.com/news/1321151/New-Features-in-EJB-31" rel="nofollow">EJB 3.1</a> Singleton EJB.</p>
<p>Chapter 3's section on configuring the EJB container starts by introducing the basics of EJBs with specific introductory focus on the "new EJB 3.1 variants introduced by Java EE 6": <a href="http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html" rel="nofollow">Singleton EJB</a>, <a href="http://blogs.oracle.com/kensaks/entry/optional_local_business_interfaces" rel="nofollow">No-Interface EJB</a>, and <a href="http://blogs.oracle.com/arungupta/entry/totd_137_asynchronous_ejb_a" rel="nofollow">Asynchronous EJB</a>. The chapter discusses in detail how to configure the different types of EJBs. It also points out the built-in JMS support in JBoss AS 7 provided by <a href="http://www.jboss.org/hornetq" rel="nofollow">HornetQ</a>. It also covers configuration related to JBoss AS 7's/HornetQ's use of <a href="http://www.jboss.org/netty" rel="nofollow">Netty</a>.</p>
<p>The section of Chapter 3 on configuring transactions introduces the <a href="http://www.oracle.com/technetwork/java/javaee/jta/index.html" rel="nofollow">Java Transaction API</a>. It then explains how to configure the JTA support for timeouts and statistics gathering.</p>
<p><strong>Chapter 4: JBoss Web Server Configuration</strong></p>
<p>The focus of the <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_4" rel="nofollow">fourth chapter</a> of <em>JBoss AS 7: Configuration, Deployment, and Administration</em> is on configuration of the JBoss web server (<a href="http://www.jboss.org/jbossweb" rel="nofollow">JBoss Web</a>), which is based on a fork of <a href="http://tomcat.apache.org/" rel="nofollow">Tomcat 7</a>. The chapter discusses HTTP connectors, including JBoss Web's built-in <a href="http://en.wikipedia.org/wiki/Apache_Tomcat#Coyote" rel="nofollow">Coyote</a> HTTP 1.1 connector and the <a href="http://apr.apache.org/" rel="nofollow">Apache Portable Runtime</a> (<a href="http://docs.jboss.org/jbossweb/3.0.x/apr.html" rel="nofollow">APR</a>) connector. The chapter shows how to separately download and use the ARP connector with JBoss AS 7.</p>
<p>The chapter of JBoss Web server covers configuration of static (HTML/images) and dynamic (JSP) resources and then moves onto discussion of deploying <a href="http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html" rel="nofollow">JavaServer Faces</a> (<a href="http://www.jboss.org/richfaces" rel="nofollow">JSF</a>)-based applications on JBoss AS 7. The author points out: "Currently, JBoss AS 7 supports the JSF release 2.1 using the <a href="http://java.net/projects/mojarra/" rel="nofollow">Mojarra</a> implementation,<br />
although there are plans for supporting <a href="http://myfaces.apache.org/" rel="nofollow">MyFaces</a> implementation too." The chapter then demonstrates using Eclipse to create a JSF project and adding an EJB layer to that application. The chapter also demonstrates adding <a href="http://www.oracle.com/technetwork/articles/marx-jpa-087268.html" rel="nofollow">JPA</a>-based persistence (including how to switch the JPA provider from default <a href="http://www.hibernate.org/" rel="nofollow">Hibernate 4</a>), setting a custom web context, and deploying the web application.</p>
<p><strong>Chapter 5: Configuring a JBoss AS Domain</strong></p>
<p>The <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_5" rel="nofollow">fifth chapter</a> concludes the chapters on configuration by providing a more detailed look at configuring JBoss AS 7 domains. Of particular interest to me is the sections on configuring the JVM and providing JVM options. I also found the author's use of <a href="http://marxsoftware.blogspot.com/2008/08/from-jconsole-to-visualvm.html" rel="nofollow">VisualVM</a> to be helpful. This detailed chapter introduces domain terminology, explains what a domain is, and explains why a domain does not provide the same functionality or purpose as node clustering. It provides thorough detail on configuring domains.</p>
<p><strong>Chapter 6: Deploying Applications on JBoss AS 7</strong></p>
<p>Deployment to JBoss AS 7 is the focus of <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_6" rel="nofollow">Chapter 6</a>. The chapter begins with an introduction to <a href="http://docs.oracle.com/javase/tutorial/deployment/jar/" rel="nofollow">JAR</a>, <a href="http://docs.jboss.org/jbossweb/3.0.x/deployer-howto.html" rel="nofollow">WAR</a>, <a href="http://docs.oracle.com/javaee/5/tutorial/doc/bnaby.html" rel="nofollow">EAR</a>, <a href="http://www.jboss.org/ironjacamar" rel="nofollow">RAR</a>, and <a href="http://www.javabeat.net/tips/117-sar-service-archive-file-in-jboss.html" rel="nofollow">SAR</a> files and then goes onto more detailed (but still thankfully brief) coverage of the first three types of archive files.</p>
<p>After covering JAR, WAR, and EAR, the chapter moves onto coverage of manual and automatic deployments to JBoss AS 7. I was happy to see coverage of using CLI to deploy from the command line, but fans of deploying via web page will be happy to know that there is also coverage of deploying from the web administration console. The chapter also demonstrates deploying from the Eclipse IDE.</p>
<p>The most significant bane of my Java development experience has probably been <a href="https://community.jboss.org/wiki/JBossClassLoaderHistory" rel="nofollow">classloaders</a>, which become tricky when application servers, IDEs, and frameworks like Spring are involved. With this in mind, I was happy to see a section in the sixth chapter called "JBoss AS 7 classloading explained." Several pages are devoted to using JBoss's provided mechanism for appropriately dealing with classes used by the application server as well as the deployed applications. The chapter also talks about using Java EE's standard approach of specifying <code>Class-Path</code> in the <code>MANIFEST.MF</code> file.</p>
<p><strong>Chapter 7: Managing the Application Server</strong></p>
<p>The <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_7" rel="nofollow">seventh chapter</a> focuses on managing JBoss AS 7 via the command line-based CLI tool and the web-based Web admin console. Differentiation is made between CLI commands and CLI operations. I find the sections "Executing CLI scripts in batch" and "Executing scripts in a file" to be particularly interesting from a CLI perspective. The first section talks about CLI support for a group of commands as an atomic unit and the second section talks about writing file-based administration scripts. The book further peaks my interest in CLI by explaining how to take snapshots in CLI and how to display CLI history.</p>
<p>Although I find that I use command line-based tools for configuration, administration, and deployment of an application server in the long-run, web-based or other graphically-oriented tools are often nice when first using an application server or when trying to figure new things out. In other words, I prefer command line scripting for routine tasks and prefer graphically-oriented administrative tools for new or unusual tasks. The second half of Chapter 7 covers using "The new Web admin console."</p>
<p>Chapter 7's coverage of the history of JBoss's web administrative consoles is a good example of how the overall book does a nice job of comparing and contrasting different versions of JBoss tools. The chapter points out the advantages and limitations of the <a href="https://community.jboss.org/wiki/JMXConsole" rel="nofollow">jmx-console</a> approach (versions of JBoss up to JBoss 4.x) and the <a href="http://seamframework.org/" rel="nofollow">Seam</a>-based Web admin console (JBoss 5.x and 6.x) before covering JBoss AS 7's <a href="http://code.google.com/webtoolkit/" rel="nofollow">GWT</a>-based Web admin console. As one would expect, the section on Web admin console is filled with screen snapshots demonstrating the Web admin console in action.</p>
<p><strong>Chapter 8: Clustering</strong></p>
<p>One of the things many of us want from our application server is <a href="https://www.jboss.org/dms/AS7/as7webinar/AS7-clustering-webinar.pdf" rel="nofollow">clustering</a> functionality, which is the theme of <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_8" rel="nofollow">Chapter 8</a> (load balancing of web applications is covered in the next chapter). The chapter points out several facets of clustering that have changed in JBoss AS 7. It also covers how <a href="http://www.jgroups.org/" rel="nofollow">JGroups</a> and <a href="http://www.jboss.org/infinispan" rel="nofollow">Infinispan</a> are used to implement JBoss clustering. This is an information--packed chapter that I will be sure to read again before using JBoss AS 7 clustering.</p>
<p><strong>Chapter 9: Load-balancing Web Applications</strong></p>
<p><a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_9" rel="nofollow">Chapter 9</a> covers load-balancing of web applications. The chapter only briefly covers installation of Tomcat's <a href="http://tomcat.apache.org/connectors-doc/" rel="nofollow">mod_jk</a> and Apache's <a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html" rel="nofollow">mod_proxy</a> to connect the Apache web server to JBoss AS 7 because "the installation of either mod_jk or mod_proxy does not differ from earlier AS releases." The remainder of the chapter focused on load balancing covers <a href="http://www.jboss.org/mod_cluster" rel="nofollow">mod_cluster</a> (new to JBoss AS 7). The chapter concludes by returning to discussion of clustering. The author references the <a href="https://docs.jboss.org/author/display/AS71/High+Availability+Guide" rel="nofollow">JBoss AS 7.1 High Availability Guide</a> for continuing developments related to JBoss AS 7's clustering support.</p>
<p><strong>Chapter 10: Securing JBoss AS 7</strong></p>
<p><a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_10" rel="nofollow">Chapter 10</a> of <em>JBoss AS 7: Configuration, Deployment, and Administration</em> is focused on security, an increasingly popular topic. Reading about security is often my best cure for insomnia, but there were some interesting nuggets in this chapter that kept my attention.</p>
<p>The chapter introduces <a href="http://www.jboss.org/picketbox" rel="nofollow">PicketBox</a> (formerly known as <a href="https://community.jboss.org/wiki/PicketBoxOverview#What_is_PicketBox" rel="nofollow">JBoss Security</a>), the security framework upon which JBoss AS 7's security is built. It then provides a basic overview of Java's security API and provide definitions of key security terms in a Java EE context. This thorough chapter covers a wide range of security-related topics as they pertain to JBoss AS 7.</p>
<p><strong>Chapter 11: Taking JBoss AS 7 in the Cloud</strong></p>
<p>The <a href="http://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book#chapter_11" rel="nofollow">final chapter</a> is devoted to the <a href="http://marxsoftware.blogspot.com/2011/12/significant-software-development.html" rel="nofollow">trendiest topic</a> of them all: cloud computing. The central focus of this chapter is <a href="http://www.redhat.com/" rel="nofollow">Red Hat</a>'s <a href="https://openshift.redhat.com/app/" rel="nofollow">OpenShift</a> (<a href="http://en.wikipedia.org/wiki/Platform_as_a_service" rel="nofollow">PaaS</a>). The author does as good a job as I have seen of describing cloud computing and I particularly liked the contrasting of cloud computing to grid computing. The majority of the chapter discusses starting with <a href="https://openshift.redhat.com/app/express" rel="nofollow">OpenShift Express</a> and then transitioning to <a href="https://openshift.redhat.com/app/flex" rel="nofollow">OpenShift Flex</a>.</p>
<p><strong>Appendix</strong></p>
<p>The Appendix is six pages of "common commands and operations" that provides an easy access reference. Although the shown commands use Linux script <code>jboss-admin.sh</code>, the alternative for Windows (<code>jboss-admin.bat</code>) is shown at the beginning of the appendix. The subsections of the appendix are Startup Options, General Commands, Domain Mode, JMS, Data sources, mod_cluster, Batch, and Snapshots.</p>
<p><strong>Conclusion</strong></p>
<p><a href="https://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book" rel="nofollow">JBoss AS 7: Configuration, Deployment, and Administration</a> delivers what it's title promises: an introduction and in-depth coverage of configuring and administrating and deploying to JBoss AS 7. Along the way, the book manages to provide differences in JBoss AS 7 from previous versions and to provide introductory details about aspects of Java EE supported in JBoss AS 7. This is not the book one would learn how to write JavaServer Pages, JavaServer Faces applications, EJBs, or other Java EE code from. However, it is the book one would learn how to deploy a Java EE application to JBoss AS 7 and how to maintain and configure JBoss AS 7 to most efficiently support Java EE applications.</p>
<p><strong>Other Reviews</strong></p>
<p>Other reviews of <a href="https://www.packtpub.com/jboss-as-7-configuration-deployment-administration/book" rel="nofollow">JBoss AS 7: Configuration, Deployment, and Administration</a> are available. These include <a href="https://plus.google.com/100362024804331957185/about" rel="nofollow">Markus Eisele</a>'s <a href="http://blog.eisele.net/2012/01/review-jboss-as7-configuration.html" rel="nofollow">Review: "JBoss AS7 Configuration, Deployment and Administration" by Francesco Marchioni</a>, <a href="http://rickwagner.blogspot.com/" rel="nofollow">Rick Wagner</a>'s <a href="http://rickwagner.blogspot.com/2011/11/book-review-for-jboss-as-7.html" rel="nofollow">Book Review for "JBoss AS 7 Configuration Deployment and Administration"</a> (unfinished version of the book), <a href="http://maksim.sorokin.dk/it/about/" rel="nofollow">Maksim Sorokin</a>'s <a href="http://maksim.sorokin.dk/it/2012/01/06/packt-jboss-as-7-configuration-deployment-and-administration/" rel="nofollow">[PACKT] JBoss AS 7 Configuration, Deployment and Administration</a> (announcing review coming), and <a href="http://www.blogger.com/profile/02280824131541047038" rel="nofollow">David Salter</a>'s <a href="http://www.davidsalter.com/2012/01/forthcoming-book-review.html" rel="nofollow">Forthcoming Book Review</a> (announcing review coming).</p>
<p>Original posting available at <a href="http://marxsoftware.blogspot.com/" rel="nofollow">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p>
    ]]></content>
  </entry>
  <entry>
    <title>the case for pre-built EJB components</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8305" />
    <id>http://www.javaworld.com/community/node/8305</id>
    <published>2012-01-30T16:07:09-05:00</published>
    <updated>2012-01-30T16:07:09-05:00</updated>
    <author>
      <name>Douglas Dooley</name>
    </author>
    <category term="EJB" />
    <category term="glassfish" />
    <summary type="html"><![CDATA[<!--paging_filter--><p>The case is simple, and it has a history: build functional applications that are cross-platform, and revive the model of Java to be write-once-run across multiple platforms.  This was done, in some form, by Theory Center before they were acquired by BEA in 1999, and it allowed WebLogic to take the early lead, that ultimately led to their sizable cash-out, in the form of the Oracle acquisition.  Nothing made IT managers happier than to see something actually working on top of these Internet operating systems, that were to be known as application servers.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>The case is simple, and it has a history: build functional applications that are cross-platform, and revive the model of Java to be write-once-run across multiple platforms.  This was done, in some form, by Theory Center before they were acquired by BEA in 1999, and it allowed WebLogic to take the early lead, that ultimately led to their sizable cash-out, in the form of the Oracle acquisition.  Nothing made IT managers happier than to see something actually working on top of these Internet operating systems, that were to be known as application servers.  They could see what they were investing in, if Theory Center worked, then their own development efforts could also work.  I was working on iPlanet's competitor to WL, and never once did I see a deployment of Theory Center, yet many of the largest financial services firms and teleco's, deployed WebLogic in their environments.  Some will say that application servers never lived up to their promise of integrating all of Java, in to one common platform, that could rival Microsoft's datacenter offerings.  But that is what is available today: a belief that cloud computing will re-orient the data-center like no other offering brought forth by enterprise vendors in the last twenty years.  It is the Internet taken to its natural destination, and it is custom-made for application server vendors to take their offerings in to the cloud.  The vendors, themselves, are coming at from different angles.  JBoss is the lead environment for Red Hat Linux, and OS that desires to see the market go cloud, it is Oracle that will lead with applications for intra-environment deployment, and IBM will offer up some customization to argue for their own tools to be deployed as cloud infrastructure.  Even Spring Source is in the cloud game with VMWare having invented the enterprise cloud architecture.  What do all of these have in common?</p>
<p>They all are lacking the Theory Center moment, when you can walk in to a customer and visibly demonstrate what is being explained in technical terms.  The promise of pre-built functionality has always been on the minds of the vendors, and customers have their own in-house set of components that run certain functionality, and that can be re-used across multiple projects.  What is needed is a firm, a coalition of firms, or a series of start-up moves to re-kindle the fire originally set by the promise of the EJB component model.  Pre-built EJBs are what would give the cloud that discernible advantage over the Azure promise of integration across the platform.  Windows Server is acquiring the enterprise, slowly but surely, with 50% of deployments worldwide having gone to WS, and 20% with Linux, and 30% other.  In order for the remaining non-Windows 50% to compete, it needs these pre-built components to show the power of Java's development model, and work across the vendors to prove the deployment model.  Whether that be IBM Global Services, or Oracle's Support Network, or JBoss consultants, worldwide, the component model needs a new life.  This can be done in basic steps toward a full-fledged platform, that would deliver shopping cart, credit card transactions, other shopping features for consumers, B2B transactions like supply chain management, integration with all sorts of data sources are ready for pre-built functionality, and beyond. </p>
<p>The best way to deliver this is on top of Glassfish, as the Reference Implementation for JEE 6 and 7, it can showcase the advanced cloud features of Enterprise Java.  Pre-built components would give customers something to work with as they investigate the business model of going with Java over Azure in the cloud build-out.  Microsoft will be forced to retaliate, but they do not have an industry that has committed to delivering specification after another, with partners, that compete for the same accounts.  The Microsoft components will be more centered at Google, anyway, their Great Plains product-set has been focused on ERP and other large functionality efforts, not micro-enough to be componentized in time for Java components to build a user base that will set them off on the cloud projects, that are certain to spring up, as IT managers look to new models to improve delivery of their respective employers' web offerings.  Get EJBs back in the discussion, and integrate with other non-EJB models through JAX, and see the application server vendors regain the argument that has been eroded by years of over-hype, now is the time to deliver on the hype of Java on the server-side.  Right now, it is all a process of upgrades and maintenance decisions, make it about the cloud and see new models and new opportunities rise to the surface.</p>
<p>This cause has been called for before, it has been dis-credited, and to be honest, is like kryptonite to IT everywhere.  The promise of pre-buuilt components, a long-time Holy Grail in development, is a real possibility in deployment, today, with the clouds becoming the leading selling point of vendors, and the leading interest area of customers.  How to make these clouds work?  Microsoft has it figured out with their complete package of development and integration among a wide-swath of products.  All Java needs is a development environment, pre-built components, and application servers to compliment the data sources and integration efforts already in place across the enterprise.  There is no need to sell new platforms, or new models, the app servers are the cloud OS, always have been, they were just disguised as dot-com enablers, in their earlies incarnation, but they power the Internet.  Where would IT be without enterprise Java, it would be stuck in non-standard, non-compatible environments, without any hope of achieving acquisition or other-wise integration, it would be much costlier to run an IT environment, without application servers.  Re-charge the debate around Java with pre-built EJBs, that work across cloud environments, make it a competitive marketplace for selecting components, that can work together, and turn the power back to developers within enterprises.  The cloud will shake out from there.  Without it, there is no functionality to sell on, and allows Microsoft and Azure all the advantages of integration without standards.  All of the Java vendors would benefit, and Glassfish would have a standing chance of becoming one of those deployment environments ready for the cloud.  This is Oracle's best opportunity for the cloud, beyond whatever WebLogic does to become Fusion for the Oracle Cloud, a pre-built set of Java specific functionality would be a major starting point for how Java vendors are to approach the cloud.  It would translate to benefits across the Java ecosystem.</p>
    ]]></content>
  </entry>
  <entry>
    <title>JavaFX 2 Presents the Quadratic Formula</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8304" />
    <id>http://www.javaworld.com/community/node/8304</id>
    <published>2012-01-30T09:58:00-05:00</published>
    <updated>2012-01-30T11:00:31-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><p>I recently needed to check some homework answers related to use of the <a href="http://www.purplemath.com/modules/quadform.htm" rel="nofollow" rel="nofollow">quadratic formula</a>. After realizing that it was getting tedious to do these by hand, I thought of using my <a href="http://en.wikipedia.org/wiki/HP-48_series" rel="nofollow" rel="nofollow">calculator</a> to solve them. However, I realized that I could write a simple application using <a href="http://javafx.com/" rel="nofollow" rel="nofollow">JavaFX</a> to calculate the results and that approach seemed more interesting than using the calculator.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>I recently needed to check some homework answers related to use of the <a href="http://www.purplemath.com/modules/quadform.htm" rel="nofollow">quadratic formula</a>. After realizing that it was getting tedious to do these by hand, I thought of using my <a href="http://en.wikipedia.org/wiki/HP-48_series" rel="nofollow">calculator</a> to solve them. However, I realized that I could write a simple application using <a href="http://javafx.com/" rel="nofollow">JavaFX</a> to calculate the results and that approach seemed more interesting than using the calculator. This post demonstrates that simple application and provides the relatively straightforward code required to make it happen.</p>
<p>The next couple of screen snapshots demonstrate the simple application in example. They include the initial appearance of the application followed by a couple images showing different values calculated by the application.</p>
<p><a href="http://3.bp.blogspot.com/-W5tOqQ1Rfho/TyTJh7IJPmI/AAAAAAAAC-k/3MvnFG3Imgg/s1600/javaFxQuadraticFormulaInitialStartup.png" imageanchor="1" rel="nofollow"></a></p>
<p><a href="http://1.bp.blogspot.com/-AvalxUb6YUU/TyTKT1wXcHI/AAAAAAAAC-w/5tYjhpYKXvo/s1600/javaFxQuadraticFormula5and5.png" imageanchor="1" rel="nofollow"></a></p>
<p><a href="http://1.bp.blogspot.com/-CTvg0vr-B80/TyTKYwSHpQI/AAAAAAAAC-8/xDkImgBMIZE/s1600/javaFxQuadraticFormula5and10.png" imageanchor="1" rel="nofollow"></a></p>
<p><a href="http://3.bp.blogspot.com/-YPWRu-xSSM0/TyTKbgzyHYI/AAAAAAAAC_I/YOn_cE9tk3s/s1600/javaFxQuadraticFormulaInvalid.png" imageanchor="1" rel="nofollow"></a></p>
<p>The last screen snapshot shows the output when one of the coefficients provided does not allow the quadratic formula to be applied. To provide this application slightly broader application than solely quadratic equation solving, I have added code to detect when the 'a' coefficient is zero and the 'b' coefficient is non-zero. This is a linear equation and the simple application solves it as well as the quadratic equations provided. The next screen snapshot demonstrates the output when coefficients for a linear equation are provided.</p>
<p><a href="http://2.bp.blogspot.com/-SEaAv0CxyZA/TyW25mysPWI/AAAAAAAAC_U/UD_vXjaLC3w/s1600/javaFxQuadraticFormulaLinearEquationExample.png" imageanchor="1" rel="nofollow"></a></p>
<p>The first code listing has nothing to do with the JavaFX presentation layer, but is instead a simple call that provides the basic back-end quadratic formula calculations. I include it here because it is use by the JavaFX example application. It is somewhat interesting in its own right because there are so many ways to calculate a square root in Java. The best-known approach is to use <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#sqrt(double)" rel="nofollow">Math.sqrt(double)</a>, but the <a href="http://stackoverflow.com/questions/1384919/are-there-libraries-for-square-root-over-bigdecimal" rel="nofollow">choices are often more varied</a> when using <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html" rel="nofollow">BigDecimal</a> instead of <code>double</code>. Because the purpose of my post is to focus on the JavaFX aspect of this and because my chosen approach is accurate enough for its purposes, I've taken the "easy way" out here and simply use <code>Math.sqrt(double)</code>.</p>
<p><strong>SimplisticQuadraticFormula.java</strong></p>
<p>package dustin.examples;</p>
<p>import java.math.BigDecimal;<br />
import java.math.MathContext;<br />
import java.math.RoundingMode;<br />
import java.util.ArrayList;<br />
import java.util.List;</p>
<p>/**<br />
 * Class encapsulating quadratic formula implementation.<br />
 *<br />
 * @author Dustin<br />
 */<br />
public class SimplisticQuadraticFormula<br />
{<br />
   /** Default precision used for specifying scale. */<br />
   private static final int DEFAULT_PRECISION = MathContext.DECIMAL64.getPrecision();</p>
<p>   /** Convenient representation of zero as BigDecimal. */<br />
   private static final BigDecimal ZERO = new BigDecimal("0");</p>
<p>   /** Convenient representation of two as BigDecimal. */<br />
   private static final BigDecimal TWO = new BigDecimal("2");</p>
<p>   /** Convenient representation of four as BigDecimal. */<br />
   private static final BigDecimal FOUR = new BigDecimal("4");</p>
<p>   /**<br />
    * Calculate intercepts with x-axis.<br />
    *<br />
    * @param a Coefficient 'a' from a quadratic equation to be solved.<br />
    * @param b Coefficient 'b' from a quadratic equation to be solved.<br />
    * @param c Coefficient 'c' from a quadratic equation to be solved.<br />
    * @return The x-intercepts or solutions to the quadratic equation (two values)<br />
    *     or a single value if solution to a linear equation. Note that two<br />
    *     solutions are always provided for quadratic equations even if they are<br />
    *     the same.<br />
    * @throws NumberFormatException Thrown when x-intercepts cannot be calculated.<br />
    */<br />
   public static List&lt;BigDecimal&gt; calculateXIntercepts(<br />
      final BigDecimal a, final BigDecimal b, final BigDecimal c)<br />
   {<br />
      final List&lt;BigDecimal&gt; intercepts = new ArrayList&lt;BigDecimal&gt;();<br />
      if (a.compareTo(ZERO) == 0 &amp;&amp; b.compareTo(ZERO) == 0)<br />
      {<br />
         // neither quadratic nor linear<br />
         throw new NumberFormatException("Must have coefficient for one of x terms.");<br />
      }<br />
      else if (a.compareTo(ZERO) == 0)  // linear equation<br />
      {<br />
         intercepts.add(c.setScale(DEFAULT_PRECISION).negate().divide(b, RoundingMode.HALF_UP));<br />
      }<br />
      else<br />
      {<br />
         final BigDecimal intercept1 =<br />
            calculateNumeratorWithAddition(a, b, c)<br />
               .divide(calculateDenominator(a), RoundingMode.HALF_UP);<br />
         intercepts.add(intercept1);<br />
         final BigDecimal intercept2 =<br />
            calculateNumeratorWithSubtraction(a, b, c)<br />
               .divide(calculateDenominator(a), RoundingMode.HALF_DOWN);<br />
         intercepts.add(intercept2);<br />
      }<br />
      return intercepts;<br />
   }</p>
<p>   /**<br />
    * Calculate axis of symmetry, if applicable.<br />
    *<br />
    * @param a Coefficient 'a' from a quadratic equation to be solved.<br />
    * @param b Coefficient 'b' from a quadratic equation to be solved.<br />
    * @return The "x" axis of symmetry.<br />
    * @throws NumberFormatException Thrown if the provided 'a' coefficient is<br />
    *    zero because cannot divide by zero.<br />
    */<br />
   public static BigDecimal calculateAxisOfSymmetry(final BigDecimal a, final BigDecimal b)<br />
   {<br />
      if (a.compareTo(ZERO) == 0)<br />
      {<br />
         throw new NumberFormatException(<br />
            "Cannot calculate axis of symmetry based on x-intercepts when a is zero.");<br />
      }<br />
      return b.setScale(DEFAULT_PRECISION).negate().divide(a.multiply(TWO), RoundingMode.HALF_UP);<br />
   }</p>
<p>   /**<br />
    * Calculate numerator of quadratic formula where the terms are added.<br />
    *<br />
    * @param a Coefficient 'a' from a quadratic equation to be solved.<br />
    * @param b Coefficient 'b' from a quadratic equation to be solved.<br />
    * @param c Coefficient 'c' from a quadratic equation to be solved.<br />
    * @return Value of numerator in quadratic formula where terms are added.<br />
    * @throws NumberFormatException Thrown if no real solution is available.<br />
    */<br />
   private static BigDecimal calculateNumeratorWithAddition(<br />
      final BigDecimal a, final BigDecimal b, final BigDecimal c)<br />
   {<br />
      return b.negate().add(calculateSquareRootPortion(a, b, c));<br />
   }</p>
<p>   /**<br />
    * Calculate numerator of quadratic formula where the terms are subtracted.<br />
    *<br />
    * @param a Coefficient 'a' from a quadratic equation to be solved.<br />
    * @param b Coefficient 'b' from a quadratic equation to be solved.<br />
    * @param c Coefficient 'c' from a quadratic equation to be solved.<br />
    * @return Value of numerator in quadratic formula where terms are subtracted.<br />
    * @throws NumberFormatException Thrown if no real solution is available.<br />
    */<br />
   private static BigDecimal calculateNumeratorWithSubtraction(<br />
      final BigDecimal a, final BigDecimal b, final BigDecimal c)<br />
   {<br />
      return b.negate().subtract(calculateSquareRootPortion(a, b, c));<br />
   }</p>
<p>   /**<br />
    * Calculate denominator of quadratic formula.<br />
    *<br />
    * @param a Coefficient of 'a' from a quadratic equation to be solved.<br />
    * @return Value of denominator in quadratic formula.<br />
    * @throws NumberFormatException Thrown in 0 is provided for coefficient 'a'<br />
    *    because denominator cannot be zero.<br />
    */<br />
   private static BigDecimal calculateDenominator(final BigDecimal a)<br />
   {<br />
      if (a.compareTo(ZERO) == 0)<br />
      {<br />
         throw new NumberFormatException("Denominator cannot be zero.");<br />
      }<br />
      return a.multiply(TWO);<br />
   }</p>
<p>   /**<br />
    * Calculates value of square root portion of quadratic formula.<br />
    *<br />
    * @param a Coefficient 'a' from a quadratic equation to be solved.<br />
    * @param b Coefficient 'b' from a quadratic equation to be solved.<br />
    * @param c Coefficient 'c' from a quadratic equation to be solved.<br />
    * @return The square root portion of the quadratic formula applied with<br />
    *    the three provided co-efficients.<br />
    * @throws NumberFormatException Thrown if there is no solution (no<br />
    *    intersection of the x-axis) or if a number is encountered that cannot<br />
    *    be handled with BigDecmal return type.<br />
    */<br />
   private static BigDecimal calculateSquareRootPortion(<br />
      final BigDecimal a, final BigDecimal b, final BigDecimal c)<br />
   {<br />
      BigDecimal sqrt;<br />
      final BigDecimal subtrahend = a.multiply(c).multiply(FOUR);<br />
      final BigDecimal insideSqrt = b.pow(2).subtract(subtrahend);<br />
      if (insideSqrt.compareTo(ZERO) &lt; 0)<br />
      {<br />
         throw new NumberFormatException("Cannot be solved: no x-intercepts.");<br />
      }<br />
      else<br />
      {<br />
         final double value = insideSqrt.doubleValue();<br />
         final double sqrtDouble = Math.sqrt(value);<br />
         sqrt = new BigDecimal(sqrtDouble);  // may throw NumberFormatException<br />
      }<br />
      return sqrt;<br />
   }<br />
}</p>
<p>With the calculations portion in place, it is time to move to the focus of this post (the presentation via JavaFX 2). The following code listing provides the JavaFX 2 class (written in pure Java) used for the application. Note that much of this presentation layer code could have been written using <a href="http://docs.oracle.com/javafx/2.0/fxml_get_started/jfxpub-fxml_get_started.htm" rel="nofollow">FXML</a>.</p>
<p><strong>QuadraticCalculator.java</strong></p>
<p>package dustin.examples;</p>
<p>import java.math.BigDecimal;<br />
import java.util.List;<br />
import javafx.application.Application;<br />
import javafx.event.ActionEvent;<br />
import javafx.event.EventHandler;<br />
import javafx.geometry.Pos;<br />
import javafx.scene.Group;<br />
import javafx.scene.Scene;<br />
import javafx.scene.control.Button;<br />
import javafx.scene.control.Label;<br />
import javafx.scene.control.TextField;<br />
import javafx.scene.control.TextFieldBuilder;<br />
import javafx.scene.image.Image;<br />
import javafx.scene.image.ImageView;<br />
import javafx.scene.layout.HBox;<br />
import javafx.scene.layout.VBox;<br />
import javafx.scene.paint.Color;<br />
import javafx.stage.Stage;</p>
<p>/**<br />
 * JavaFX-based application for solving quadratic equations.<br />
 *<br />
 * @author Dustin<br />
 */<br />
public class QuadraticCalculator extends Application<br />
{<br />
   /** Coefficient A used in quadratic formula. */<br />
   private TextField coefficientA =<br />
      TextFieldBuilder.create().promptText("Enter Coefficient A").build();</p>
<p>   /** Coeffecient B used in quadratic forumal. */<br />
   private TextField coefficientB =<br />
      TextFieldBuilder.create().promptText("Enter Coefficient B").build();</p>
<p>   /** Coeffecient C (constant) used in quadratic formula. */<br />
   private TextField coefficientC =<br />
      TextFieldBuilder.create().promptText("Enter Coefficient C").build();</p>
<p>   /** First x-intercept. */<br />
   private TextField xIntercept1 =<br />
      TextFieldBuilder.create().disable(true).editable(false).build();</p>
<p>   /** Second x-intercept. */<br />
   private TextField xIntercept2 =<br />
      TextFieldBuilder.create().disable(true).editable(false).build();</p>
<p>   /** Axis of symmetry. */<br />
   private TextField symmetryAxis =<br />
      TextFieldBuilder.create().disable(true).editable(false).build();</p>
<p>   /**<br />
    * Extract Image with provided name.<br />
    *<br />
    * @param imageName Name of image to be provided.<br />
    * @return Loaded image.<br />
    */<br />
   private Image getImage(final String imageName)<br />
   {<br />
      final String jarFileUrl =<br />
         this.getClass().getProtectionDomain().getCodeSource().getLocation().toString();<br />
      final String url = "jar:" + jarFileUrl + "!/" + imageName;<br />
      System.out.println(url);<br />
      return new Image(url, true);<br />
   }</p>
<p>   /**<br />
    * Provide a read-only horizontal box with quadratic equation and quadratic<br />
    * formula and with a button that can be clicked to calculate solution to<br />
    * quadration equation with provided coefficients.<br />
    *<br />
    * @return Horizontal box with quadratic equation and quadratic formula.<br />
    */<br />
   private HBox buildEquationsBox()<br />
   {<br />
      final HBox equationsBox = new HBox();<br />
      equationsBox.setAlignment(Pos.CENTER);<br />
      equationsBox.setSpacing(50);<br />
      final Image quadraticEquation = getImage("quadraticEquation-transparent.png");<br />
      final ImageView equationView = new ImageView(quadraticEquation);<br />
      equationsBox.getChildren().add(equationView);<br />
      final Image quadraticFormula = getImage("quadraticFormula-transparent.png");<br />
      final ImageView formulaView = new ImageView(quadraticFormula);<br />
      equationsBox.getChildren().add(formulaView);<br />
      final Button calculateButton = new Button("Calculate");<br />
      calculateButton.setOnAction(<br />
         new EventHandler&lt;ActionEvent&gt;()<br />
         {<br />
            public void handle(ActionEvent t)<br />
            {<br />
               final BigDecimal a = extractBigDecimal(coefficientA.getText());<br />
               final BigDecimal b = extractBigDecimal(coefficientB.getText());<br />
               final BigDecimal c = extractBigDecimal(coefficientC.getText());<br />
               try<br />
               {<br />
                  final List&lt;BigDecimal&gt; intercepts =<br />
                     SimplisticQuadraticFormula.calculateXIntercepts(a, b, c);<br />
                  xIntercept1.setText(intercepts.get(0).toPlainString());<br />
                  xIntercept1.setDisable(false);<br />
                  if (intercepts.size() &gt; 1)<br />
                  {<br />
                     xIntercept2.setText(intercepts.get(1).toEngineeringString());<br />
                     xIntercept2.setDisable(false);<br />
                  }<br />
                  else<br />
                  {<br />
                     xIntercept2.setText("-");<br />
                     xIntercept2.setDisable(true);<br />
                  }<br />
                  if (a.compareTo(new BigDecimal("0")) != 0)<br />
                  {<br />
                     final BigDecimal axis =<br />
                        SimplisticQuadraticFormula.calculateAxisOfSymmetry(a, b);<br />
                     symmetryAxis.setText(axis.toPlainString());<br />
                     symmetryAxis.setDisable(false);<br />
                  }<br />
                  else<br />
                  {<br />
                     symmetryAxis.setText("-");<br />
                     symmetryAxis.setDisable(true);<br />
                  }<br />
               }<br />
               catch (NumberFormatException nfe)<br />
               {<br />
                  xIntercept1.setText("-");<br />
                  xIntercept1.setDisable(true);<br />
                  xIntercept2.setText("-");<br />
                  xIntercept2.setDisable(true);<br />
                  symmetryAxis.setText("-");<br />
                  symmetryAxis.setDisable(true);<br />
               }<br />
            }<br />
         });<br />
      equationsBox.getChildren().add(calculateButton);<br />
      return equationsBox;<br />
   }</p>
<p>   /**<br />
    * Converts provided String to BigDecimal.<br />
    *<br />
    * @param possibleNumber String to be converted to an instance of BigDecimal.<br />
    * @return The BigDecimal corresponding to the provided String or Double.NaN<br />
    *     if the conversion cannot be performed.<br />
    */<br />
   private BigDecimal extractBigDecimal(final String possibleNumber)<br />
   {<br />
      BigDecimal extractedNumber;<br />
      try<br />
      {<br />
         extractedNumber = new BigDecimal(possibleNumber);<br />
      }<br />
      catch (NumberFormatException nfe)<br />
      {<br />
         extractedNumber = null;<br />
      }<br />
      return extractedNumber;<br />
   }</p>
<p>   /**<br />
    * Provide horizontal box with labels of coefficients and fields to enter<br />
    * coefficient values.<br />
    *<br />
    * @return Horizontal box for entering coefficients.<br />
    */<br />
   private HBox buildEntryBox()<br />
   {<br />
      final HBox entryBox = new HBox();<br />
      entryBox.setSpacing(10);<br />
      final Label aCoeff = new Label("a = ");<br />
      entryBox.getChildren().add(aCoeff);<br />
      entryBox.getChildren().add(this.coefficientA);<br />
      final Label bCoeff = new Label("b = ");<br />
      entryBox.getChildren().add(bCoeff);<br />
      entryBox.getChildren().add(this.coefficientB);<br />
      final Label cCoeff = new Label("c = ");<br />
      entryBox.getChildren().add(cCoeff);<br />
      entryBox.getChildren().add(this.coefficientC);<br />
      return entryBox;<br />
   }</p>
<p>   /**<br />
    * Construct the output box with solutions based on quadratic formula.<br />
    *<br />
    * @return Output box with solutions of applying quadratic formula given<br />
    *    provided input coefficients.<br />
    */<br />
   private HBox buildOutputBox()<br />
   {<br />
      final HBox outputBox = new HBox();<br />
      outputBox.setSpacing(10);<br />
      final Label x1 = new Label("x1 = ");<br />
      outputBox.getChildren().add(x1);<br />
      outputBox.getChildren().add(this.xIntercept1);<br />
      final Label x2 = new Label("x2 = ");<br />
      outputBox.getChildren().add(x2);<br />
      outputBox.getChildren().add(this.xIntercept2);<br />
      final Label axis = new Label("axis = ");<br />
      outputBox.getChildren().add(axis);<br />
      outputBox.getChildren().add(this.symmetryAxis);<br />
      return outputBox;<br />
   }</p>
<p>   /**<br />
    * Build overall presentation of application.<br />
    *<br />
    * @return Vertical box representing input and output of application.<br />
    */<br />
   private VBox buildOverallVerticalLayout()<br />
   {<br />
      final VBox vbox = new VBox();<br />
      vbox.setSpacing(25);<br />
      vbox.getChildren().add(buildEquationsBox());<br />
      vbox.getChildren().add(buildEntryBox());<br />
      vbox.getChildren().add(buildOutputBox());<br />
      vbox.setAlignment(Pos.CENTER);<br />
      return vbox;<br />
   }</p>
<p>   /**<br />
    * Start the JavaFX application for solving quadratic equations.<br />
    *<br />
    * @param stage Primary stage.<br />
    * @throws Exception JavaFX-related exception.<br />
    */<br />
   @Override<br />
   public void start(final Stage stage) throws Exception<br />
   {<br />
      final Group groupRoot = new Group();<br />
      groupRoot.getChildren().add(buildOverallVerticalLayout());<br />
      final Scene scene = new Scene(groupRoot, 600, 150, Color.LIGHTGRAY);<br />
      stage.setTitle("Quadratic Formula: JavaFX Style");<br />
      stage.setScene(scene);<br />
      stage.show();<br />
   }</p>
<p>   /**<br />
    * Main function for running the JavaFX-based quadratic equation solver.<br />
    *<br />
    * @param arguments<br />
    */<br />
   public static void main(final String[] arguments)<br />
   {<br />
      Application.launch(arguments);<br />
   }<br />
}</p>
<p>The JavaFX 2 code above loads two images with <a href="http://marxsoftware.blogspot.com/2011/04/making-white-image-backgrounds.html" rel="nofollow">transparent backgrounds</a> to display the standard form of a quadratic equation and to display the quadratic formula. In a previous post, I loaded these images from an external URL, but I loaded them from the application's JAR in this example. These images are shown next independent of the application.</p>
<p><strong>quadraticEquation-transparent.png</strong></p>
<p><a href="http://4.bp.blogspot.com/-WRHK8oEkTrs/TyW9oW0zZ7I/AAAAAAAAC_g/IkkUpnjGM6U/s1600/quadraticEquation-transparent.png" imageanchor="1" rel="nofollow"></a></p>
<p><strong>quadraticFormula-transparent.png</strong></p>
<p><a href="http://1.bp.blogspot.com/-bLGYh7p_yUc/TyW99YfcESI/AAAAAAAAC_s/Ld0oGuY2Znc/s1600/quadraticFormula-transparent.png" imageanchor="1" rel="nofollow"></a></p>
<p>There are several ways this simplistic application could be improved. One improvement would be to make sizes adjustable and bound to one another so the window could be dragged larger or smaller and still look good. Another improvement would be to provide some type of status message on the interface, especially for situations where solutions could not be calculated. A third improvement that would be to present a graph of the quadratic equation specified with the provided coefficients to visually indicate the x-intercepts and axis of symmetry.</p>
<p>JavaFX 2 makes it fairly straight-forward to write simple, user-friendly applications.</p>
<p>Original posting available at <a href="http://marxsoftware.blogspot.com/" rel="nofollow">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p>
    ]]></content>
  </entry>
  <entry>
    <title>JavaFX 2.1: JavaFX 2&#039;s @DefaultProperty Annotation</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8301" />
    <id>http://www.javaworld.com/community/node/8301</id>
    <published>2012-01-27T01:56:00-05:00</published>
    <updated>2012-01-27T02:00:16-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><p>The <a href="http://java.dzone.com/articles/focus-javafx-2-fxml-netbeans" rel="nofollow" rel="nofollow">JavaLobby/DZone syndicated version</a> of my blog post <a href="http://marxsoftware.blogspot.com/2012/01/focus-on-javafx-2-fxml-with-netbeans-71.html" rel="nofollow" rel="nofollow">Focus on JavaFX 2 FXML with NetBeans 7.1</a> was recently published and <a href="http://java.dzone.com/users/md54345" rel="nofollow" rel="nofollow">Mihai Dinca-panaitescu</a> (author of DZone article <a href="http://java.dzone.com/articles/tuning-your-java-vm" rel="nofollow" rel="nofollow">Tuning Your Java VM</a>) added an interesting and useful feedback comment.</p>
    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>The <a href="http://java.dzone.com/articles/focus-javafx-2-fxml-netbeans" rel="nofollow">JavaLobby/DZone syndicated version</a> of my blog post <a href="http://marxsoftware.blogspot.com/2012/01/focus-on-javafx-2-fxml-with-netbeans-71.html" rel="nofollow">Focus on JavaFX 2 FXML with NetBeans 7.1</a> was recently published and <a href="http://java.dzone.com/users/md54345" rel="nofollow">Mihai Dinca-panaitescu</a> (author of DZone article <a href="http://java.dzone.com/articles/tuning-your-java-vm" rel="nofollow">Tuning Your Java VM</a>) added an interesting and useful feedback comment. Specifically, he stated:<br />
I needed to put <code>&amp;lt;children&amp;gt;</code> tag in JavaFx2Menus.fxml</p>
<p />
before MenuBar tag.</p>
<p />
otherwise an Exception is raised:</p>
<p />
javafx.fxml.LoadException: javafx.scene.layout.VBox does not have a default property.</p>
<p>I'm glad that Mihai posted this response for several reasons. First, it will help anyone else reading my post to be aware of that issue. Second, it has allowed me to speculate on the cause of this message in this blog post.</p>
<p>My first thought at reading Mihai's comment was that perhaps the difference was that I was using JavaFX 2.1 (still beta) when I ran the example and perhaps Mihai was using production-ready JavaFX 2.0. Assuming this is the case, the next question was, "What changed in JavaFX 2.1 to make this example work without the <code>children</code> element? Feeling that I need to balance out recent cogitations on my blog with rampant speculation, I decided to do some of that speculation in this post. I speculate that JavaFX 2.1 has applied <a href="http://docs.oracle.com/javafx/2.0/api/javafx/beans/DefaultProperty.html" rel="nofollow">@DefaultProperty</a> to more controls than in JavaFX 2.0 and that <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/layout/VBox.html" rel="nofollow">VBox</a> was one of these which now has it applied.</p>
<p>The Javadoc <a href="http://docs.oracle.com/javafx/2.0/api/javafx/beans/DefaultProperty.html" rel="nofollow">description of the DefaultProperty annotation</a> states, "Specifies a property to which child elements will be added or set when an explicit property is not given." The "<a href="http://docs.oracle.com/javafx/2.0/api/javafx/fxml/doc-files/introduction_to_fxml.html#default_properties" rel="nofollow">Default Properties</a>" section of the highly useful <a href="http://fxexperience.com/wp-content/uploads/2011/08/Introducing-FXML.pdf" rel="nofollow">Introducing FXML</a> adds:</p>
<p>A class may define a "default property" using the <code>@DefaultProperty</code> annotation defined in the <code>javafx.fxml</code> package. If present, the sub-element representing the default property can be omitted from the markup.</p>
<p />For example, if the <code>Group</code> class were to define a default property of "children", the <code>&amp;lt;children&amp;gt;</code> element would no longer be required.</p>
<p>My speculation was that JavaFX 2.1 had added <code>@DefaultProperty</code> annotation to the <code>VBox</code> (among others) control. Although the Javadoc for JavaFX 2.1's <code>VBox</code> does not show this annotation applied, the JavaFX 2.1 Javadoc documentation for its parent class, <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/layout/Pane.html" rel="nofollow">Pane</a>, does indicate the presence of the annotation (and the <code>@DefaultProperty</code> annotation is itself marked <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html" rel="nofollow">@Inherited</a>). The next image shows <code>Pane</code> JavaFX 2.0 and JavaFX 2.1 Javadoc versions side-by-side.</p>
<p><a href="http://4.bp.blogspot.com/-er6W6BDQX7w/TyJI2lIdMYI/AAAAAAAAC-Y/Tkc1gv3H6fI/s1600/comparingPaneJavadocJavaFx20JavaFx21AnnotationCircled.png" imageanchor="1" rel="nofollow"></a></p>
<p>The circled portion of the JavaFX 2.1 API documentation for <code>Pane</code> shows that this control (and controls inheriting from it such as <code>VBox</code>) have <code>children</code> as the component's default property. This explains why <code>children</code> must be explicitly specified in JavaFX 2.0, but is optional for <code>VBox</code> in JavaFX 2.1.</p>
<p>The <code>@DefaultProperty</code> annotation has also been applied to the MenuBar control in JavaFX 2.1. Comparing Javadoc for <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/control/MenuBar.html" rel="nofollow">MenuBar in JavaFX 2.0</a> to the Javadoc for MenuBar in 2.1 proves this. The next screen snapshot shows them side-by-side.</p>
<p><a href="http://2.bp.blogspot.com/-i0nXz6WYg70/TyI7Zv-XOvI/AAAAAAAAC-M/_vD6zZ--IOY/s1600/comparingJavaFx20ToJavaFx21MenuBarJavadocCircledAnnotation.png" imageanchor="1" rel="nofollow"></a></p>
<p>The circled portion of the JavaFX 2.1 API documentation shows that an annotation has been added in JavaFX 2.1 to the <code>MenuBar</code> class to specify that the default sub-element for <code>MenuBar</code> is now "menus" in JavaFX 2.1. Incidentally, <code>Menu</code> also has a new <code>@DefaultProperty</code> with "items" as its default property. With the <code>@DefaultProperty</code> annotation of <code>MenuBar</code>, I decided to try removing the <code>&amp;lt;menus&amp;gt;</code> elements from my FXML and this appeared to work fine, removing a couple lines of XML from my source FXML and allowing many lines to be less indented. It worked and I had a little more concise of an FXML representation of the same menus application layout.</p>
<p>The more widespread use of the <code>@DefaultProperty</code> annotation is a small, but very welcome addition to JavaFX 2.1. Although adding opening and closing "children" tags adds only two lines per use, it does increase the indentation as well for a well-formatted FXML file. FXML can be appealing because of its visual similarity to the presentation itself and having fewer "extra" lines for common cases can make it even more readable. Although the <code>@DefaultProperty</code> annotation itself was available in JavaFX 2.0, it's much more widely applied and can be more widely used in FXML when using JavaFX 2.1.</p>
<p>Original posting available at <a href="http://marxsoftware.blogspot.com/" rel="nofollow">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p>
    ]]></content>
  </entry>
  <entry>
    <title>Is Programming Less Exciting Today?</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8300" />
    <id>http://www.javaworld.com/community/node/8300</id>
    <published>2012-01-25T18:24:43-05:00</published>
    <updated>2012-01-25T19:00:31-05:00</updated>
    <author>
      <name>Ted Neward</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>
As discriminatory as this is going to sound, this one is for the old-timers. If you
started programming after the turn of the milennium, I don’t know if you’re going
to be able to follow the trend of this post—not out of any serious deficiency on your
part, hardly that. But I think this is something only the old-timers are going to
identify with. (And thus, do I alienate probably 80% of my readership, but so be it.)
</p>
<p>
Is it me, or is programming just less interesting today than it was two decades ago?
</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>
As discriminatory as this is going to sound, this one is for the old-timers. If you
started programming after the turn of the milennium, I don’t know if you’re going
to be able to follow the trend of this post—not out of any serious deficiency on your
part, hardly that. But I think this is something only the old-timers are going to
identify with. (And thus, do I alienate probably 80% of my readership, but so be it.)
</p>
<p>
Is it me, or is programming just less interesting today than it was two decades ago?
</p>
<p>
By all means, shake your smartphones and other mobile devices at me and say, “Dude,
how can you say that?”, but in many ways programming for Android and iOS reminds me
of programming for Windows and Mac OS two decades ago. HTML 5 and JavaScript remind
me of ten years ago, the first time HTML and JavaScript came around. The discussions
around programming languages remind me of the discussions around C++. The discussions
around NoSQL remind me of the arguments both for and against relational databases.
It all feels like we’ve been here before, with only the names having changed.
</p>
<p>
Don’t get me wrong—if any of you comment on the differences between HTML 5 now and
HTML 3.2 then, or the degree of the various browser companies agreeing to the standard
today against the “browser wars” of a decade ago, I’ll agree with you. This isn’t
so much of a rational and logical discussion as it is an emotive and intuitive one.
It just <em>feels</em> similar.
</p>
<p>
To be honest, I get this sense that across the entire industry right now, there’s
a sort of malaise, a general sort of “Bah, nothing really all that new is going on
anymore”. NoSQL is re-introducing storage ideas that had been around before but were
discarded (perhaps injudiciously and too quickly) in favor of the relational model.
Functional languages have obviously been in place since the 50’s (in Lisp). And so
on.
</p>
<p>
More importantly, look at the Java community: what truly innovative ideas have emerged
here in the last five years? Every new open-source project or commercial endeavor
either seems to be a refinement of an idea before it (how many different times are
we going to create a new Web framework, guys?) or an attempt to leverage an idea coming
from somewhere else (be it from .NET or from Ruby or from JavaScript or….). With the
upcoming .NET 4.5 release and Windows 8, Microsoft is holding out very little “new
and exciting” bits for the community to invest emotionally in: we hear about “async”
in C# 5 (something that F# has had already, thank you), and of course there is WinRT
(another platform or virtual machine… sort of), and… well, honestly, didn’t we just
do this a decade ago? Where is the WCFs, the WPFs, the Silverlights, the things that
would get us fired up? Hell, even a new approach to data access might stir some excitement.
Node.js feels like an attempt to reinvent the app server, but if you look back far
enough you see that the app server itself was reinvented once (in the Java world)
in Spring and other lightweight frameworks, and before that by people who actually
thought to write their own web servers in straight Java. (And, for the record, the
whole event-driven I/O thing is something that’s been done in both Java and .NET a
long time before now.)
</p>
<p>
And as much as this is going to probably just throw fat on the fire, all the excitement
around JavaScript as a language reminds me of the excitement about Ruby as a language.
Does nobody remember that Sun did this once already, with Phobos? Or that Netscape
did this with LiveScript? JavaScript on the server end is not new, folks. It’s just
new to the people who’d never seen it before.
</p>
<p>
In years past, there has always seemed to be something deeper, something more exciting
and more innovative that drives the industry in strange ways. Artificial Intelligence
was one such thing: the search to try and bring computers to a state of human-like
sentience drove a lot of interesting ideas and concepts forward, but over the last
decade or two, AI seems to have lost almost all of its luster and momentum. User interfaces—specifically,
GUIs—were another force for a while, until GUIs got to the point where they were so
common and so deeply rooted in their chosen pasts (the single-button of the Mac, the
menubar-per-window of Windows, etc) that they left themselves so little room for maneuver.
At least this is one area where Microsoft is (maybe) putting the fatted sacred cow
to the butcher’s knife, with their Metro UI moves in Windows 8… but only up to a point.
</p>
<p>
Maybe I’m just old and tired and should hang up my keyboard and go take up farming,
then go retire to my front porch’s rocking chair and practice my <em>Hey you kids!
Getoffamylawn!</em> or something. But before you dismiss me entirely, do me a favor
and tell me: what gets you excited these days? If you’ve been programming for twenty
years, what about the industry today gets your blood moving and your mind sharpened?
</p>
<img width="0" height="0" src="http://blogs.tedneward.com/aggbug.ashx?id=20604d47-a520-4a9f-8fd2-469caa49eb40" />
<br />
<hr />
Enterprise consulting, mentoring or instruction. Java, C++, .NET or XML services.
1-day or multi-day workshops available. <a href="mailto:ted@tedneward.com">Contact
me for details</a>.    ]]></content>
  </entry>
  <entry>
    <title>Recent Java-Related Posts Worthy of Special Notice</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8298" />
    <id>http://www.javaworld.com/community/node/8298</id>
    <published>2012-01-23T09:59:00-05:00</published>
    <updated>2012-01-23T10:00:19-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>In this blog post, I reference and summarize recent Java-related posts that I have found to be particularly interesting and well worth the time spent reading them.</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>In this blog post, I reference and summarize recent Java-related posts that I have found to be particularly interesting and well worth the time spent reading them.</p>

<strong style="font-size: 125%;">JDK 8 and Unsigned Integer Arithmetic</strong>

<p><a href="http://blogs.oracle.com/darcy/">Joe Darcy</a>'s post <a href="http://blogs.oracle.com/darcy/entry/unsigned_api">Unsigned Integer Arithmetic API now in JDK 8</a> states that "initial API support for unsigned integer arithmetic" has been pushed into <a href="http://openjdk.java.net/projects/jdk8/">Java 8</a>. Darcy explains that this is implemented largely via static methods on classes <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html">java.lang.Integer</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html">java.lang.Long</a>.</p>

<p>Although Darcy's post is not very long, he manages to talk about the specific unsigned arithmetic functionality that is supported (conversion of Strings to unsigned integers, conversion of unsigned integers to Strings, comparing unsigned values, and calculation of unsigned division and remainder) as well as why it was decided to not implement new types such as <code>UnsignedInt</code>. A consequence of not implementing specific unsigned types is that it is easier to inadvertently mix signed and unsigned values and Darcy suggests some ideas built on naming conventions or new built-in annotations to address this concern.</p>


<strong style="font-size: 125%;">Versions, Code Names, and Features of Java Releases</strong>

<p>Speaking of new versions of Java, another Joe (<a href="http://javapapers.com/about-me/">Joseph Kulandai</a>) started 2012 off with a nice post on <a href="http://javapapers.com/core-java/java-features-and-history/">Java Versions, Features and History</a>. In this post, Kulandai lists the versions of Java in backwards chronological order (Java SE 7 listed first and JDK Version 1.0 at the bottom of the post). Under each major version of Java, Kulandai provides bullet lists of new features in that release and provides the <a href="http://javachamp.blogspot.com/2008/07/java-code-names_04.html">code name</a> of each release.</p>


<strong style="font-size: 125%;">Java 8 Status Updates</strong>

<p>Continuing the theme of Java 8 updates, another post of interest is <a href="http://jthoenes.bergischweb.de/">Johannes Thönes</a>'s <a href="http://jthoenes.bergischweb.de/2011/12/23/java-8-status-updates/">Java 8 Status Updates</a>. This post looks at the status of "the two big new language features of the upcoming Java SE 8" (<a href="http://openjdk.java.net/projects/lambda/">Project Lambda</a> and <a href="http://openjdk.java.net/projects/jigsaw/">Project Jigsaw</a>).</p>


<strong style="font-size: 125%;">Java 7 Concurrency</strong>

<p><a href="http://www.blogger.com/profile/12402045792243894660">Niklas Schlimm</a> has written two recent posts on using Java 7 concurrency features. He introduces "a flexible thread synchronization mechanism called <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.html">Phaser</a>" in the post <a href="http://niklasschlimm.blogspot.com/2011/12/java-7-understanding-phaser.html">Java 7: Understanding the Phaser</a> and looks in detail at <a href="http://marxsoftware.blogspot.com/2011/12/java-7s-threadlocalrandom.html">ThreadLocalRandom</a> in the post <a href="http://niklasschlimm.blogspot.com/2012/01/java-7-how-to-write-really-fast-java.html">Java 7: How to write really fast Java code</a>.</p>


<strong style="font-size: 125%;">OutOfMemoryError: Using Command-line Tools</strong>

<p><a href="http://forum.plumbr.eu/template/NamlServlet.jtp?macro=user_nodes&amp;user=241253">Vladimir Šor</a>'s <a href="http://plumbr.eu/blog/solving-outofmemoryerror-jdk-tools">Solving OutOfMemoryError (part 5) - JDK Tools</a> is, as its title suggests, the fifth in a series on Java memory issues available on <a href="http://plumbr.eu/blog">that blog</a> ("Solving OutOfMemoryError blog post series"). This post provides a brief summary description and usage information for three <a href="http://docs.oracle.com/javase/7/docs/webnotes/tsg/other/tools-Windows.html">command-line tools</a> bundled with the Oracle Java SDK (<a href="http://marxsoftware.blogspot.com/2008/01/jps-java-virtual-machine-process-status.html">jps</a>, <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/share/jmap.html">jmap</a>, and <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/share/jhat.html">jhat</a>).</p>

<p>The previous entries in this series are written by Nikita Salnikov-Tarnovski: <a href="http://plumbr.eu/blog/solving-outofmemoryerror-story-of-a-developer">Solving OutOfMemoryError (part 1) - story of a developer</a>, <a href="http://plumbr.eu/blog/solving-outofmemoryerror-why-didnt-operations-solve-it">Solving OutOfMemoryError (part 2)- why didn’t operations solve it?</a>, <a href="http://plumbr.eu/blog/solving-outofmemoryerror-where-do-you-start">Solving OutOfMemoryError (part 3) - where do you start?</a>, and <a href="http://plumbr.eu/blog/solving-outofmemoryerror-memory-profilers">Solving OutOfMemoryError (part 4) - memory profilers</a>.</p>


<strong style="font-size: 125%;">Debugging the JVM</strong>

<p><a href="http://www.transylvania-jug.org/transilvania-jug/despre-noi">Attila Balazs</a>'s post <a href="http://www.transylvania-jug.org/archives/331">Debugging the JVM</a> provides interesting insight on something that we don't seem to have to do as often these days as in the earlier days of the JVM, but could be a very useful resource on the occasions this does occur. Balazs talks about "crashing the JVM itself" via <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7105883">null thread group name</a> and then goes onto explain using <a href="http://www.ibm.com/developerworks/library/l-gdb/">gdb in Linux</a> to debug the issue with the JVM.</p>


<strong style="font-size: 125%;">Groovy Introduction</strong>

<p><a href="http://www.blogger.com/profile/11632964711752480304">Alex</a>'s post provides an <a href="http://alexsotob.blogspot.com/2011/09/soy-el-capitan-de-la-nave-tengo-el.html">introduction to Groovy</a> including coverage of <a href="http://marxsoftware.blogspot.com/2009/11/slurping-xml-with-groovy.html">XML with Groovy</a>, <a href="http://marxsoftware.blogspot.com/2010/12/regular-expressions-in-groovy-via-java.html">regular expressions with Groovy</a>, and <a href="http://marxsoftware.blogspot.com/2009/05/groovysql-groovy-jdbc.html">SQL with Groovy</a>.</p>


<strong style="font-size: 125%;">A New Java Blog With Two JavaFX Posts</strong>

<p>I've posted before on why more <a href="http://marxsoftware.blogspot.com/2009/09/more-software-developers-should-write.html">developers should write blogs</a>. One of the reasons is the variety of opinions and ideas that are generated that way. With this in mind, I have been interested to read the first two posts of new blog <a href="http://saidandem.blogspot.com/">Experiments with Java</a>. Both of the blog's current posts have been written in January 2012 and are on JavaFX 2. The posts are <a href="http://saidandem.blogspot.com/2012/01/percent-width-for-tablecolumn-in-javafx.html">Percent Width for TableColumn in JavaFX 2.x TableView</a> and <a href="http://saidandem.blogspot.com/2012/01/sliding-in-javafx-its-all-about.html">Sliding in JavaFX (It’s all about clipping)</a>.</p>

<strong style="font-size: 125%;">Conclusion</strong>

<p>There have been several good Java-related posts in recent weeks and a sample of them are highlighted in this post.</p><div class="blogger-post-footer"><p>Original posting available at <a href="http://marxsoftware.blogspot.com/">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6517450204508339514-6690254032930193842?l=marxsoftware.blogspot.com" alt="" /></div><img src="http://feeds.feedburner.com/~r/InspiredByActualEvents/~4/UK0YByKUOBw" height="1" width="1" />    ]]></content>
  </entry>
  <entry>
    <title>REST Pagination in Spring</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8295" />
    <id>http://www.javaworld.com/community/node/8295</id>
    <published>2012-01-18T11:03:25-05:00</published>
    <updated>2012-01-18T13:00:14-05:00</updated>
    <author>
      <name>baeldung</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>This is the <strong>seventh</strong> of a series of articles about setting up a secure RESTful Web Service using Spring 3.1 and Spring Security 3.1 with Java based configuration. This article will focus on the <strong>implementation of pagination</strong> in a RESTful web service.<span id="more-1047"></span></p>
<p>The REST with Spring series:</p>    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>This is the <strong>seventh</strong> of a series of articles about setting up a secure RESTful Web Service using Spring 3.1 and Spring Security 3.1 with Java based configuration. This article will focus on the <strong>implementation of pagination</strong> in a RESTful web service.<span id="more-1047"></span></p>
<p>The REST with Spring series:</p>
<ul>
<li><strong>Part 1</strong> &#8211; <a title="Bootstrapping a web application with Spring 3.1 and Java based Configuration, part 1" href="http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/" target="_blank">Bootstrapping a web application with Spring 3.1 and Java based Configuration</a></li>
<li><strong><strong>P</strong>art 2</strong> &#8211; <a title="Building a RESTful Web Service with Spring 3.1 and Java based Configuration, part 2" href="http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/" target="_blank">Building a RESTful Web Service with Spring 3.1 and Java based Configuration</a></li>
<li><strong><strong>P</strong>art 3</strong> &#8211; <a title="Securing a RESTful Web Service with Spring Security 3.1, part 3" href="http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/" target="_blank">Securing a RESTful Web Service with Spring Security 3.1</a></li>
<li><strong>Part 4</strong> &#8211; <a title="RESTful Web Service Discoverability, part 4" href="http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/" target="_blank">RESTful Web Service Discoverability</a></li>
<li><strong>Part 5</strong> &#8211; <a title="REST Service Discoverability with Spring, part 5" href="http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/" target="_blank">REST Service Discoverability with Spring</a></li>
<li><strong>Part 6</strong> &#8211; <a title="Basic and Digest authentication for a RESTful Service with Spring Security 3.1" href="http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/" target="_blank">Basic and Digest authentication for a RESTful Service with Spring Security 3.1</a></li>
</ul>
<h1>Page as resource vs Page as representation</h1>
<p>The first question when designing pagination in the context of a RESTful architecture is whether to consider the <strong>page an actual resource or just a representation of resources</strong>. Treating the page itself as a resource introduces a host of problems such as no longer being able to uniquely identify resources between calls. This, coupled with the fact that outside the RESTful context, the page cannot be considered a proper entity, but a holder that is constructed when needed makes the choice straightforward: <strong>the page is part of the representation</strong>.</p>
<p>The next question in the pagination design in the context of REST is where to include the paging information:</p>
<ul>
<li>in the <strong>URI path</strong>: <em>/foo/page/1</em></li>
<li>the <strong>URI query</strong>: <em>/foo?page=1</em></li>
</ul>
<p>Keeping in mind that <strong>a page is not a resource</strong>, encoding the page information in the URI is no longer an option.</p>
<h1><strong>Page information in the URI query</strong></h1>
<p>Encoding paging information in the <strong>URI query</strong> is the standard way to solve this issue in a RESTful service. This approach does however have one <strong>downside</strong> &#8211; it cuts into the query space for actual queries:</p>
<p><em>/foo?page=1<em>&amp;size=10</em></em></p>
<h1>The Controller</h1>
<p>Now, for the  implementation &#8211; the Spring <strong>MVC Controller for pagination</strong> is straightforward:</p>
<script src="https://gist.github.com/1617963.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1617963">Gist</a>.</p></noscript>
<p>The two query parameters are defined in the request mapping and injected into the controller method via <em>@RequestParam</em>; the HTTP response and the Spring <em>UriComponentsBuilder</em> are injected in the Controller method to be included in the event, as both will be needed to implement <strong>discoverability</strong>.</p>
<h1>Discoverability for REST pagination</h1>
<p>Withing the scope of <strong>pagination</strong>, satisfying the <strong>HATEOAS constraint of REST</strong> means enabling the client of the API to discover the <em>next</em> and <em>previous</em> pages based on the current page in the navigation. For this purpose, the <strong><em>Link</em> HTTP header</strong> will be used, coupled with the <a title="Link Relations" href="http://www.iana.org/assignments/link-relations/link-relations.xml" target="_blank">official</a> &#8220;<em><strong>next</strong></em>&#8220;, &#8220;<em><strong>prev</strong></em>&#8220;, &#8220;<em><strong>first</strong></em>&#8221; and &#8220;<em><strong>last</strong></em>&#8221; link relation types.</p>
<p>In REST, <strong>Discoverability is a cross cutting concern</strong>, applicable not only to specific operations but to types of operations. For example, each time a Resource is created, the URI of that resource should be discoverable by the client. Since this requirement is relevant for the creation of ANY Resource, it should be dealt with separately and decoupled from the main Controller flow.</p>
<p>With Spring, this <strong>decoupling is achieved with events</strong>, as was thoroughly discussed in the <a title="REST Service Discoverability with Spring" href="http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/" target="_blank">previous article</a> focusing on Discoverability of a RESTful service. In the case of pagination, the event &#8211; <em>PaginatedResultsRetrievedEvent</em> &#8211; was fired in the Controller, and discoverability is achieved in a listener for this event:</p>
<script src="https://gist.github.com/1618081.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1618081">Gist</a>.</p></noscript>
<p>In short, the listener logic checks if the navigation allows for a next, previous, first and last pages and, if it does, adds the relevant URIs to the Link HTTP Header. It also makes sure that the link relation type is the correct one &#8211; &#8220;next&#8221;, &#8220;prev&#8221;, &#8220;first&#8221; and &#8220;last&#8221;. This is the single responsibility of the listener (<a title="PaginatedResultsRetrievedEventDiscoverabilityListener" href="https://gist.github.com/1622997" target="_blank">the full code here</a>).</p>
<h1>Test Driving Pagination</h1>
<p>Both the main logic of pagination and discoverability should be extensively covered by small, focused integration tests; as in the <a title="RESTful Web Service Discoverability" href="http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/" target="_blank">previous article</a>, the <a title="rest-assured official project page" href="http://code.google.com/p/rest-assured/" target="_blank">rest-assured library</a> is used to consume the REST service and to verify the results.</p>
<p>These are a few example of pagination integration tests; for a full test suite, check out the github project (link at the end of the article):</p>
<script src="https://gist.github.com/1628931.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1628931">Gist</a>.</p></noscript>
<h1><strong>Test Driving Pagination Discoverability</strong></h1>
<p>Testing Discoverability of Pagination is relatively straightforward, although there is a lot of ground to cover. The tests are focused on the <strong>position of the current page in navigation</strong> and the different URIs that should be discoverable from each position:</p>
<script src="https://gist.github.com/1623199.js"></script><noscript><p>View the code on <a href="https://gist.github.com/1623199">Gist</a>.</p></noscript>
<p>These are just a few examples of integration tests consuming the RESTful service.</p>
<h1>Getting All Resources</h1>
<p>On the same topic of pagination and discoverability, the choice must be made if a client is allowed to <strong>retrieve all the Resources in the system</strong> at once, or if the client <strong>MUST</strong> ask for them paginated.</p>
<p>If the choice is made that the client cannot retrieve all Resources with a single request, and pagination is not optional but required, then several options are available for the <strong>response to a get all request</strong>.</p>
<p>One option is to return a <strong>404 (<em>Not Found</em>)</strong> and use the <strong><em>Link</em> header</strong> to make the first page discoverable:</p>
<blockquote><p>Link=&lt;http://localhost:8080/rest/api/admin/foo?page=0&amp;size=10&gt;; rel=&#8221;<strong>first</strong>&#8220;, &lt;http://localhost:8080/rest/api/admin/foo?page=103&amp;size=10&gt;; rel=&#8221;<strong>last</strong>&#8220;</p></blockquote>
<p>Another option is to return redirect &#8211; <strong>303 <em>(See Other</em></strong>) &#8211; to the first page of the pagination.</p>
<p>A third option is to return a <strong>405 (<em>Method Not Allowed)</em></strong> for the GET request.</p>
<h1>REST Paginag with <em>Range</em> HTTP headers</h1>
<p>A relatively different way of doing pagination is to work with the <strong>HTTP <em>Range</em> headers</strong> &#8211; <em>Range</em>, <em>Content-Range</em>, <em>If-Range</em>, <em>Accept-Ranges</em> &#8211; and <strong>HTTP status codes</strong> &#8211; 206 (<em>Partial Content</em>), 413 (<em>Request Entity Too Large</em>), 416 (<em>Requested Range Not Satisfiable</em>). One view on this approach is that the HTTP Range extensions were not intended for pagination, and that they should be managed by the Server, not by the Application.</p>
<p>Implementing pagination based on the HTTP Range header extensions is nevertheless technically possible, although not nearly as common as the implementation discussed in this article.</p>
<h2>Conclusion</h2>
<p>This article covered the implementation of Pagination in a RESTful service with Spring, discussing how to implement and test Discoverability. For a full implementation of pagination, check out the <a title="the github REST project containing the implementation for this post" href="https://github.com/eugenp/REST" target="_blank">github project</a>.</p>
<p>If you read this far, <strong>you should <a title="http://twitter.com/baeldung" href="http://twitter.com/#!/baeldung" target="_blank">follow me on twitter here</a></strong>.</p>
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/Ma-CtxUVfh8" height="1" width="1" />    ]]></content>
  </entry>
  <entry>
    <title>Book Review: JavaFX 2.0: Introduction by Example</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8294" />
    <id>http://www.javaworld.com/community/node/8294</id>
    <published>2012-01-16T21:49:00-05:00</published>
    <updated>2012-01-16T22:00:14-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>Although Oracle's changes to <a href="http://javafx.com/">JavaFX</a> at <a href="http://marxsoftware.blogspot.com/2010/09/javaone-2010-general-observations-and.html">JavaOne 2010</a> and <a href="http://marxsoftware.blogspot.com/2011/10/javaone-2011-overall-impressions-good.html">JavaOne 2011</a> have converted me from a <a href="http://marxsoftware.blogspot.com/2010/05/o-javafx-what-art-thou.html">skeptic</a> to a <a href="http://marxsoftware.blogspot.com/2011/05/javafx-2-beta-time-to-reevaluate-javafx.html">believer</a> when it comes to <a href="http://marxsoftware.blogspot.com/search/lab    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>Although Oracle's changes to <a href="http://javafx.com/">JavaFX</a> at <a href="http://marxsoftware.blogspot.com/2010/09/javaone-2010-general-observations-and.html">JavaOne 2010</a> and <a href="http://marxsoftware.blogspot.com/2011/10/javaone-2011-overall-impressions-good.html">JavaOne 2011</a> have converted me from a <a href="http://marxsoftware.blogspot.com/2010/05/o-javafx-what-art-thou.html">skeptic</a> to a <a href="http://marxsoftware.blogspot.com/2011/05/javafx-2-beta-time-to-reevaluate-javafx.html">believer</a> when it comes to <a href="http://marxsoftware.blogspot.com/search/label/JavaFX">JavaFX</a>, the shift in JavaFX vision has not been <a href="http://marxsoftware.blogspot.com/2011/12/challenges-of-javafx-reboot.html">without its downsides</a>. In particular, the JavaFX book market has been tricky because <a href="http://stackoverflow.com/questions/7754803/any-decent-books-on-javafx-2">nearly all available JavaFX books</a> have been about version 1.x. In this post, I review the only book that I'm aware of at time of this writing that is completely focused on <a href="http://javafx.com/roadmap/">JavaFX 2.0</a>: <a href="http://carlfx.wordpress.com/tag/carl-dea/">Carl Dea</a>'s <a href="http://www.apress.com/9781430242574">JavaFX 2.0: Introduction by Example</a>.</p>

<p>I'll start my review by stating the most important observation about <em>JavaFX 2.0: Introduction by Example</em>: it provided me exactly what I was looking for exactly when I needed it. There are some attributes of the book that might be considered negative by some readers that I felt were positives in my use of the book. I'll attempt in this post to articulate the finer points of these attributes so that perspective readers can make up their own minds.</p>

<p><em>JavaFX 2.0 Introduction by Example</em> does exactly what the title implies: it introduces JavaFX 2.0 via numerous and varied examples. This code-heavy book is roughly similar to a "recipes" or "cookbook" with individual item covered (AKA a "recipe" in a recipes or cookbook) featuring subsections on the problem to be solved, the solution or solutions to that problem, and how those solutions work. Like the best recipes-oriented or cookbook-oriented software development books, this one is constructed so that Chapter 1 ("JavaFX Fundamentals") covers some of the basics of JavaFX early on. In other words, the reader is not dropped into JavaFX without first getting some examples of how to write and deploy basic "Hello World" style JavaFX applications.</p>

<p>Although <em>JavaFX 2.0: Introduction by Example</em> does provide introductory examples early on, I really appreciated the author not spending significant time discussing esoteric features of the language or delving into the history of JavaFX in tedious detail or providing pages worth of explanation on why JavaFX is the <a href="http://idioms.thefreedictionary.com/the+best+thing+since+sliced+bread">greatest thing since sliced bread</a>. I'm usually in a hurry and I have come to resent books wasting my time on such things and this book doesn't do that. In this case, I was already familiar with these aspects of JavaFX (at least its history and why I might be interested in learning more about it), so I was especially appreciative of Dea not wasting paper and my time on that subject. In the book's concise "Introduction," Dea covers in a page and a half some advantages of JavaFX and "some history" of JavaFX along with a simple table articulating features of each release of JavaFX. It's a thing of beauty to be able to read all of this in less than two pages and in the introduction!</p>

<p>Dea covers some more background on JavaFX in the first chapter, but again limits that discussion to a single page. This page is more detailed than the introductory section and is a nice, brief segue into the technical meat of the book. This first page also contains the sentences that I think best sum up the value of this book:</p>
<blockquote>Although this book doesn't go through an exhaustive study of all of JavaFX 2.0's capabilities, you will find common use cases that can help you build richer applications. Hopefully, these recipes can lead you in the right direction by providing practical and real-world examples.</blockquote>

<p>This is exactly what <em>JavaFX 2.0: Introduction by Example</em> has done for me. It has provided me with a fast start into the world of JavaFX. Although I have since used several aspects of JavaFX not covered in this book, the book gave me the start that I needed and I was able to use <a href="http://www.oracle.com/technetwork/java/javafx/documentation/index.html">JavaFX documentation</a> for the areas not covered in this book.</p>

<p><em>JavaFX 2.0: Introduction by Example</em> gets to the point quickly. Besides common things like the very brief introduction and the index, the book contains four chapters (32 "recipes") spanning 174 pages of text, images, and code. Dea doesn't even waste time with a conclusion, but ends the book with "recipe" 4.5 ("Displaying Content from the Database"). Although some readers may need a conclusion to bring closure to their reading experience, I usually little value in this for me as a reader and I didn't miss it here. I typically don't read these types of book cover-to-cover anyway (instead focusing on sections or recipes I am most interested in), so the conclusion is often unnecessary. Lack of a conclusion is another example of how Dea's book focuses most on what I want: the technical meat.</p>

<p>The four chapters in <em>JavaFX 2.0: Introduction by Example</em> are "JavaFX Fundamentals," "Graphics with JavaFX," "Media with JavaFX," and "JavaFX on the Web." The first chapter was most useful for quickly immersing myself into the basics of JavaFX and how to apply it. The examples in that chapter tend to be simple and easy to follow. The examples in the other three chapters tend to be more sophisticated because the functionality being covered tends to be more sophisticated. There are numerous lengthy code listings in the book. Although code listings may not be the easiest to read, I like to see actual code in any book on a language. Dea typically follows each code sample with descriptive text on any new feature shown in the code sample that had not been covered previously in the book. The code samples can be downloaded from Apress's site. The book also features numerous screen snapshots, which I consider a must for a book focused on user interfaces.</p>

<p>The concise and introductory approach of <em>JavaFX 2.0: Introduction by Example</em> that appealed to me may not appeal to everyone. This book, as advertised in the above cited quotation from the first chapter, is intended to be introductory (hence the title) and not to be exhaustive. Some topics that I have not seen covered in this book include subjects such as <a href="http://marxsoftware.blogspot.com/2012/01/focus-on-javafx-2-fxml-with-netbeans-71.html">FXML</a>, the JavaFX <a href="http://marxsoftware.blogspot.com/2011/12/javafx-20-bar-and-scatter-charts-and.html">charting</a> functionality, <a href="http://groovy.codehaus.org/GroovyFX">GroovyFX</a>, and <a href="http://code.google.com/p/scalafx/">ScalaFX</a>. <a href="http://docs.oracle.com/javafx/2.0/deployment/deploy_quick_start.htm">Deployment</a> is only lightly covered (and mostly via NetBeans), but Dea does reference <a href="http://docs.oracle.com/javafx/2.0/deployment/jfxpub-deployment.htm">Deploying JavaFX Applications</a> for more details on JavaFX deployment. All of these areas, however, are fairly approachable given the JavaFX basics provided in this book. Dea recommends that readers reference forthcoming (<a href="http://learnjavafx.typepad.com/weblog/2012/01/zenpongfx-example-excerpt-from-pro-javafx-2-platform-book.html">mid-February 2012</a>, Apress) <a href="http://www.apress.com/9781430268727">Pro JavaFX 2.0 Platform</a> for an "invaluable resource" that provides "further insight into JavaFX."</p>

<p>Although a small number of the items/recipes covered in <em>JavaFX 2.0: Introduction by Example</em> are based on and assume use of <a href="http://netbeans.org/">NetBeans</a>, most examples in no way specific to any tool or IDE. Rather, most examples provide "raw" code that can be used in any IDE or favorite text editor. Indeed, many of the examples can be compiled with the <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.html">javac</a> <a href="http://java.sun.com/javase/technologies/core/toolsapis/javac/index.jsp">compiler</a> and executed with the <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/java.html">java</a> <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html">application launcher</a>. I appreciated that in at least one NetBeans-oriented recipe, Dea took the page or two necessary to provide the code listing for code generated by NetBeans. This is invaluable for those who do not use NetBeans or who want to understand the code itself rather than simply understanding how to use NetBeans to generate the code.</p>

<p><em>JavaFX 2.0: Introduction by Example</em> was exactly what I needed for an efficient and effective start to my investigation of JavaFX. It may not provide quite the level of soft introduction someone completely unfamiliar with JavaFX might want (especially if that person's basic Java skills are a little rusty) and it isn't an "exhaustive" JavaFX 2.0 reference either. It falls in between these extremes and seems to be a fast start example-based introduction to JavaFX for those who want to get into the core of JavaFX as quickly as possible. That's what I wanted when I purchased this book and I was happy to find out that's exactly what this book provides. It's completely JavaFX 2.x-oriented and there is no sign of deprecated JavaFX Script in any of the code examples.</p><div class="blogger-post-footer"><p>Original posting available at <a href="http://marxsoftware.blogspot.com/">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6517450204508339514-6659861515267164433?l=marxsoftware.blogspot.com" alt="" /></div><img src="http://feeds.feedburner.com/~r/InspiredByActualEvents/~4/MBVxgOUcrYI" height="1" width="1" />    ]]></content>
  </entry>
  <entry>
    <title>Focus on JavaFX 2 FXML with NetBeans 7.1</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8292" />
    <id>http://www.javaworld.com/community/node/8292</id>
    <published>2012-01-16T10:06:00-05:00</published>
    <updated>2012-01-16T11:00:16-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p>In <a href="http://marxsoftware.blogspot.com/2011_10_01_archive.html">October 2011</a>, I used the post <a href="http://marxsoftware.blogspot.com/2011/10/hello-javafx-20-introduction-by.html">Hello JavaFX 2.0: Introduction by NetBeans 7.1 beta</a> to look at using <a href="http://netbeans.org/community/news/show/1539.html">NetBeans 7.1 beta</a> to build a simple <a href="http://en.wikipedia.org/wiki/Hello_world_program">Hello, World</a> style of <a href="http://javafx.com/roadmap/">JavaFX 2.0</a> application.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p>In <a href="http://marxsoftware.blogspot.com/2011_10_01_archive.html">October 2011</a>, I used the post <a href="http://marxsoftware.blogspot.com/2011/10/hello-javafx-20-introduction-by.html">Hello JavaFX 2.0: Introduction by NetBeans 7.1 beta</a> to look at using <a href="http://netbeans.org/community/news/show/1539.html">NetBeans 7.1 beta</a> to build a simple <a href="http://en.wikipedia.org/wiki/Hello_world_program">Hello, World</a> style of <a href="http://javafx.com/roadmap/">JavaFX 2.0</a> application. In this post, I look at using <a href="http://wiki.netbeans.org/NewAndNoteworthyNB71#JavaFX_2_Support">NetBeans 7.1</a> (<a href="http://marxsoftware.blogspot.com/2012/01/netbeans-71-released.html">no longer in beta</a>) to build a slightly more sophisticated JavaFX 2 application that makes heavy use of <a href="http://wiki.netbeans.org/NewAndNoteworthyNB71#FXML">FXML</a>.</p>

<p>Most of my posts on JavaFX 2 up to this point have emphasized the "pure Java" nature of JavaFX 2. The examples in these posts have been written in standard Java using JavaFX 2 APIs directly from the Java source code. These examples have also been built with the <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html">javac compiler</a> and executed with the <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html">java application launcher</a>. In this post, I take one of those examples [<a href="http://marxsoftware.blogspot.com/2011/12/pure-java-javafx-20-menus.html">(Pure Java) JavaFX 2.0 Menus</a>] and "port" it to use <a href="http://docs.oracle.com/javafx/2.0/fxml_get_started/jfxpub-fxml_get_started.htm">FXML</a> for presentation layout.</p>

<p>For convenience, I include the entire Java listing for the "pure Java" implementation of the JavaFX 2 menus demonstration.</p>

<strong>JavaFX 2.0 Menus Demonstration (Pure Java)</strong>
<pre name="code" class="java" style="font-size: 9pt; overflow: auto;">
package dustin.examples;

import static java.lang.System.out;

import javafx.application.Application;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
 * Example of creating menus in JavaFX.
 * 
 * @author Dustin
 */
public class JavaFxMenus extends Application
{
   /**
    * Build menu bar with included menus for this demonstration.
    * 
    * @param menuWidthProperty Width to be bound to menu bar width.
    * @return Menu Bar with menus included.
    */
   private MenuBar buildMenuBarWithMenus(final ReadOnlyDoubleProperty menuWidthProperty)
   {
      final MenuBar menuBar = new MenuBar();

      // Prepare left-most 'File' drop-down menu
      final Menu fileMenu = new Menu("File");
      fileMenu.getItems().add(new MenuItem("New"));
      fileMenu.getItems().add(new MenuItem("Open"));
      fileMenu.getItems().add(new MenuItem("Save"));
      fileMenu.getItems().add(new MenuItem("Save As"));
      fileMenu.getItems().add(new SeparatorMenuItem());
      fileMenu.getItems().add(new MenuItem("Exit"));
      menuBar.getMenus().add(fileMenu);

      // Prepare 'Examples' drop-down menu
      final Menu examplesMenu = new Menu("JavaFX 2.0 Examples");
      examplesMenu.getItems().add(new MenuItem("Text Example"));
      examplesMenu.getItems().add(new MenuItem("Objects Example"));
      examplesMenu.getItems().add(new MenuItem("Animation Example"));
      menuBar.getMenus().add(examplesMenu);

      // Prepare 'Help' drop-down menu
      final Menu helpMenu = new Menu("Help");
      final MenuItem searchMenuItem = new MenuItem("Search");
      searchMenuItem.setDisable(true);
      helpMenu.getItems().add(searchMenuItem);
      final MenuItem onlineManualMenuItem = new MenuItem("Online Manual");
      onlineManualMenuItem.setVisible(false);
      helpMenu.getItems().add(onlineManualMenuItem);
      helpMenu.getItems().add(new SeparatorMenuItem());
      final MenuItem aboutMenuItem =
         MenuItemBuilder.create()
                        .text("About")
                        .onAction(
                            new EventHandler&lt;ActionEvent&gt;()
                            {
                               @Override public void handle(ActionEvent e)
                               {
                                  out.println("You clicked on About!");
                               }
                            })
                        .accelerator(
                            new KeyCodeCombination(
                               KeyCode.A, KeyCombination.CONTROL_DOWN))
                        .build();             
      helpMenu.getItems().add(aboutMenuItem);
      menuBar.getMenus().add(helpMenu);

      // bind width of menu bar to width of associated stage
      menuBar.prefWidthProperty().bind(menuWidthProperty);

      return menuBar;
   }

   /**
    * Start of JavaFX application demonstrating menu support.
    * 
    * @param stage Primary stage.
    */
   @Override
   public void start(final Stage stage)
   {
      stage.setTitle("Creating Menus with JavaFX 2.0");
      final Group rootGroup = new Group();
      final Scene scene = new Scene(rootGroup, 800, 400, Color.WHEAT);
      final MenuBar menuBar = buildMenuBarWithMenus(stage.widthProperty());
      rootGroup.getChildren().add(menuBar);
      stage.setScene(scene);
      stage.show();
   }

   /**
    * Main executable function for running examples.
    * 
    * @param arguments Command-line arguments: none expected.
    */
   public static void main(final String[] arguments)
   {
      Application.launch(arguments);
   }
}
</pre>

<p>Besides adding the ability to write JavaFX applications in "pure Java" as implemented in the last code listing, JavaFX 2 also provides <a href="http://tomsondev.bestsolution.at/2011/09/26/how-to-author-fxml/">FXML</a>, an XML grammar for specifying a JavaFX application's layout. This approach is very similar to that provided by <a href="http://learn.adobe.com/wiki/display/Flex/Getting+Started">Flex</a>'s <a href="http://learn.adobe.com/wiki/display/Flex/MXML">MXML</a>, by <a href="http://wiki.openlaszlo.org/Main_Page">OpenLaszlo</a>'s <a href="http://wiki.openlaszlo.org/Editing_LZX">LZX</a>, and by <a href="https://developer.mozilla.org/en-US/">Mozilla</a>'s <a href="https://developer.mozilla.org/En/XUL">XUL</a>. This approach works well with JavaFX's hierarchical Scene Graph.</p>

<p>The ported FXML code is shown next. It is easy to see the presentation structure in this XML.</p>

<strong>JavaFx2Menus.fxml</strong>
<pre name="code" class="xml" style="font-size: 9pt; overflow: auto;">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;?import java.lang.*?&gt;
&lt;?import javafx.scene.*?&gt;
&lt;?import javafx.scene.control.*?&gt;
&lt;?import javafx.scene.layout.*?&gt;

&lt;VBox id="vbox" prefHeight="400" prefWidth="800"
      xmlns:fx="http://javafx.com/fxml"
      fx:controller="dustin.examples.MenuController"&gt;
   &lt;MenuBar fx:id="menuBar" onKeyPressed="#handleKeyInput"&gt;
      &lt;menus&gt;
         &lt;Menu text="File"&gt;
            &lt;items&gt;
               &lt;MenuItem text="New"/&gt;
               &lt;MenuItem text="Open"/&gt;
               &lt;MenuItem text="Save"/&gt;
               &lt;MenuItem text="Save As"/&gt;
               &lt;SeparatorMenuItem  /&gt;
               &lt;MenuItem text="Exit"/&gt;
            &lt;/items&gt;
         &lt;/Menu&gt;
         &lt;Menu text="JavaFX 2.0 Examples"&gt;
            &lt;items&gt;
               &lt;MenuItem text="Text Example"/&gt;
               &lt;MenuItem text="Objects Example"/&gt;
               &lt;MenuItem text="Animation Example"/&gt;
            &lt;/items&gt;
         &lt;/Menu&gt;
         &lt;Menu text="Help"&gt;
            &lt;items&gt;
               &lt;MenuItem text="Search" disable="true"/&gt;
               &lt;MenuItem text="Online Manual" visible="false"/&gt;
               &lt;SeparatorMenuItem /&gt;
               &lt;MenuItem text="About" onAction="#handleAboutAction"/&gt;
            &lt;/items&gt;
         &lt;/Menu&gt;
      &lt;/menus&gt;
   &lt;/MenuBar&gt;
&lt;/VBox&gt;
</pre>

<p>The important portion of this simple FXML can be viewed on a single page within NetBeans 7.1 as shown in the next screen snapshot.</p>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-dJsqer3WE7I/TxOJ2RwJUvI/AAAAAAAAC9s/k_N0iQSZ6XQ/s1600/JavaFxMenusFxmlInNetBeans71.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="320" width="302" src="http://4.bp.blogspot.com/-dJsqer3WE7I/TxOJ2RwJUvI/AAAAAAAAC9s/k_N0iQSZ6XQ/s320/JavaFxMenusFxmlInNetBeans71.png" /></a></div>

<p>Besides the conciseness of the FXML and the aesthetically pleasing hierarchical presentation, the FXML also should look familiar to anyone who has worked with Flex, OpenLaszlo, or XUL. Most of the presentation structure is easily identified in the FXML document. This example includes an <code>onAction</code> handler that responds to the "About" menu item and there is an <code>onKeyPressed</code> action associated with the menu bar as well (I could not figure out a way to easily associate this handler with the menu item itself). Both of these actions reference names that start with the <code>#</code> symbol. The names following the <code>#</code> are names of methods on the controller class (defined by the <code>fx:controller</code> attribute of the <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/layout/VBox.html">VBox</a> as the class named <code>dustin.examples.MenuController</code>). The source for this controller class is shown next.</p>

<strong>MenuController.java</strong>
<pre name="code" class="java" style="font-size: 9pt; overflow: auto;">
package dustin.examples;

import static java.lang.System.out;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.MenuBar;
import javafx.scene.input.InputEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 * Controller class for JavaFX 2 Menus with FXML post and demonstration.
 * 
 * @author Dustin
 */
public class MenuController implements Initializable
{
   @FXML
   private MenuBar menuBar;

   /**
    * Handle action related to "About" menu item.
    * 
    * @param event Event on "About" menu item.
    */
   @FXML
   private void handleAboutAction(final ActionEvent event)
   {
      provideAboutFunctionality();
   }

   /**
    * Handle action related to input (in this case specifically only responds to
    * keyboard event CTRL-A).
    * 
    * @param event Input event.
    */
   @FXML
   private void handleKeyInput(final InputEvent event)
   {
      if (event instanceof KeyEvent)
      {
         final KeyEvent keyEvent = (KeyEvent) event;
         if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.A)
         {
            provideAboutFunctionality();
         }
      }
   }

   /**
    * Perform functionality associated with "About" menu selection or CTRL-A.
    */
   private void provideAboutFunctionality()
   {
      out.println("You clicked on About!");      
   }

   @Override
   public void initialize(final URL url, final ResourceBundle rb)
   {
      menuBar.setFocusTraversable(true);
   }   
}
</pre>

<p>The above code from the controller class includes the two methods referenced as action handlers in the FXML with the <code>#</code> prefixes. These two methods are <code>private</code> and normally would not be visible to the FXML loader, but the use of the annotation <a href="http://docs.oracle.com/javafx/2.0/api/javafx/fxml/FXML.html">@FXML</a> gets around this problem. The <code>menuBar</code> attribute is also <code>private</code> but visible to the FXML loader thanks to its own <code>@FXML</code> annotation.</p>

<p>To get the application to respond to CTRL-A before any initial access of the menu bar, I found that I needed to have a reference to the menu bar in the controller and call <a href="http://docs.oracle.com/javafx/2.0/api/javafx/scene/control/MenuBar.html">setFocusTraversable(true)</a> on that instance. Without doing that, the CTRL-A would only be responded to if I had first clicked on the menu bar once. The hook from the FXML to this attribute in the controller is the <code>fx:id</code> attribute used in the FXML. That attribute references the name "menuBar", which is (not coincidentally) also the name of the attribute in the controller class. In other words, the attribute <code>fx:id=&quot;menuBar&quot;</code> ties the XML element that attribute is on in the FXML to the attribute with the same name in the controller.</p>

<p>I did not show much in this post specific to NetBeans 7.1, but it is worth noting that I had all the pertinent files created in a new project using NetBeans 7.1's New Project wizard and selecting a JavaFX FXML Application as the project type. This created a basic FXML file, a basic controller file, and a main class for loading the FXML and running the application. I modified these to the examples above for the FXML and for the controller class. The modified class that loads the FXML and starts the JavaFX application is shown next. (There's not a lot to it!)</p>

<strong>JavaFxMenusWithFxmlDemo.java</strong>
<pre name="code" class="java" style="font-size: 9pt; overflow: auto;">
package dustin.examples;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 * Simple example of JavaFX 2 FXML used to demonstrate JavaFX 2 menus. This is a
 * "port" of the example featured using "pure Java" (no FXML) in the post
 * "(Pure Java) JavaFX 2.0 Menus"
 * (<a href="http://marxsoftware.blogspot.com/2011/12/pure-java-javafx-20-menus.html" title="http://marxsoftware.blogspot.com/2011/12/pure-java-javafx-20-menus.html">http://marxsoftware.blogspot.com/2011/12/pure-java-javafx-20-menus.html</a>).
 * 
 * @author Dustin
 */
public class JavaFxMenusWithFxmlDemo extends Application
{
   /**
    * Main function for running this application.
    * 
    * @param arguments Command-line arguments: none expected.
    */
   public static void main(String[] arguments)
   {
      Application.launch(JavaFxMenusWithFxmlDemo.class, arguments);
   }

   /**
    * Overridden Application.start(Stage) method.
    * 
    * @param stage Primary stage.
    * @throws Exception JavaFX application exception.
    */
   @Override
   public void start(final Stage stage) throws Exception
   {
      final Parent fxmlRoot = FXMLLoader.load(getClass().getResource("JavaFx2Menus.fxml"));
      stage.setScene(new Scene(fxmlRoot));
      stage.show();
   }
}
</pre>

<p>I won't show the output here because it's essentially what the "pure Java" version produced, which is shown in my post on that approach. Besides generating the files that I adapted for my application, NetBeans 7.1's new project wizard for a JavaFX FXML application also created a project that automatically packages up what I need for my JavaFX application in an executable JAR. The contents of the JAR in this case are shown in the next screen snapshot.</p>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-nALb9zuq8VY/TxOSdnu4omI/AAAAAAAAC94/tTN_lnADn7I/s1600/JavaFxMenusFxmlExampleJarContentsFromNB71Project.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="234" width="320" src="http://4.bp.blogspot.com/-nALb9zuq8VY/TxOSdnu4omI/AAAAAAAAC94/tTN_lnADn7I/s320/JavaFxMenusFxmlExampleJarContentsFromNB71Project.png" /></a></div>

<p>The trickiest part about using FXML is the relatively less available documentation. The pure Java APIs have the strong <a href="http://docs.oracle.com/javafx/2.0/api/index.html">Javadoc API documentation</a>, but I know of no such thing for FXML (including no documentation or schema for the namespace <a href="http://javafx.com/fxml">http://javafx.com/fxml</a>). There are some great resources of FXML such as <a href="http://docs.oracle.com/javafx/2.0/fxml_get_started/jfxpub-fxml_get_started.htm">Getting Started with FXML</a> and <a href="http://docs.oracle.com/javafx/2.0/api/javafx/fxml/doc-files/introduction_to_fxml.html">Introduction to FXML</a>. Perhaps the best document for figuring out what elements and attributes FXML provides is <a href="http://fxexperience.com/wp-content/uploads/2011/08/Introducing-FXML.pdf">Introducing FXML: A Markup Language for JavaFX</a>, which explains the "mapping" of JavaFX standard Java API classes to JavaFX FXML elements and attributes.</p>

<p>FXML appears to be a fairly attractive approach for building a JavaFX application because it nicely separates presentation (FXML) from business logic (controller class and classes that would be called by controller methods). This can make it easier to visually see the GUI layout in the hierarchical XML and keep the logic and presentation from cluttering each other.</p><div class="blogger-post-footer"><p>Original posting available at <a href="http://marxsoftware.blogspot.com/">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6517450204508339514-5947065025213051525?l=marxsoftware.blogspot.com" alt="" /></div><img src="http://feeds.feedburner.com/~r/InspiredByActualEvents/~4/nct__92lHGQ" height="1" width="1" />    ]]></content>
  </entry>
  <entry>
    <title>Code Forensics</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8293" />
    <id>http://www.javaworld.com/community/node/8293</id>
    <published>2012-01-16T09:13:00-05:00</published>
    <updated>2012-02-06T07:00:46-05:00</updated>
    <author>
      <name>John Dobie</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter-->How do you know if using code metrics really does help to produce code with fewer bugs.<br/>I am convinced they do, but how can I possibly prove it?<br /><br />All projects have historic data.  This is usually stored in your bug tracking and source code control tools.<br/>We can use the data stored in these systems to perform ‘code forensics.’<br/>  We use the historic data from real issues to see if they could have been avoided.<br />    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter-->How do you know if using code metrics really does help to produce code with fewer bugs.<br/>I am convinced they do, but how can I possibly prove it?<br /><br />All projects have historic data.  This is usually stored in your bug tracking and source code control tools.<br/>We can use the data stored in these systems to perform ‘code forensics.’<br/>  We use the historic data from real issues to see if they could have been avoided.<br /><br />This can all be done without affecting any of your existing code or adding any risk to your project.  <br/>Surely that’s a useful Software Engineering technique?<br /><h2>Disclaimer</h2>Firstly I realise that most bugs you find in a standard project are not caused by code quality – it’s probably only a small percentage.  However the ones that exist are avoidable.  <br/>It is these avoidable quality issues that I want to concentrate on.  I want to be able to determine when exceeding a metric threshold is likely to result in a problem<br/>It’s possible that if enough code forensics are run on my individual code base, I may be able to come up with some numbers that are useful to me in the future.<br/>In the long term it may be possible for someone to do a large study and come up with better guidelines.<br/><h2>Process</h2>The process is quite straightforward.<br /><br />1. Query your bug tracking tool for all the issues that required a code fix.<br />2. Assess the defects.<br />3. Identify the code.<br />4. Get the root cause.<br /><h2>Query your bug tracking tool.</h2>First thing you need to do is to identify all your recent bugs, let’s say for the last month.  <br/>Do a simple query to bring back all of the bugs during that period.This should be easy - otherwise you’re using the wrong tool! <br />Now you have a full list of all of the defects that you are potentially interested in<br /><div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-eDapBJwUqyQ/TxBaivhTEfI/AAAAAAAAAHo/SmDjL_IXP74/s1600/jira.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="153" src="http://4.bp.blogspot.com/-eDapBJwUqyQ/TxBaivhTEfI/AAAAAAAAAHo/SmDjL_IXP74/s640/jira.jpg" width="640" /></a></div><br /><h2>Assess the defects.</h2>You now need to go through each of the bugs and assess whether the issue really was a code issue.<br/>Other things it might be include.<br /><br />• A requirements issue.<br />• An issue with the deployment environment.<br />• Configuration Issues<br /><br/>What you are left with is a list of issues that were really caused because of bad code. <br /><div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-xKcTS25_4qM/TxBa11EjvzI/AAAAAAAAAHw/nqQiZC9oXgQ/s1600/code-error.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="56" src="http://3.bp.blogspot.com/-xKcTS25_4qM/TxBa11EjvzI/AAAAAAAAAHw/nqQiZC9oXgQ/s640/code-error.jpg" width="640" /></a></div><br /><h2>Identify the problematic code. </h2>You now need to map your list of issues back to the relevant source.<br />You will not be able to do this unless you have been disciplined with your check in comments.  In most places I have worked, when checking in a bug fix you always start it with a reference to the problem it fixes.  <br />Assuming you have been commenting your commits with the reference,  you can do a simple query to see which code was affected.  This can be done in fisheye, tortoise etc to get the required code<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-Bo249xK_mIU/TxBbHomqokI/AAAAAAAAAH4/1JODPpjdPH0/s1600/fix.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="184" src="http://2.bp.blogspot.com/-Bo249xK_mIU/TxBbHomqokI/AAAAAAAAAH4/1JODPpjdPH0/s640/fix.jpg" width="640" /></a></div><br /><h2>Get to the root cause.</h2>Finally you have something to look at, so what do you do with it?  Well first you have to understand how the fix works and decide if it was a code quality issue.  Perhaps the issue was a simple error rather than something a metric would have caught.<br />However you might open the code and find like this.  The average complexity in our system is 10.  This piece of code has a complexity of 106!<br/>This was an accident waiting to happen!<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-E7LEU8SKCeY/TxBbcRYaTkI/AAAAAAAAAIA/AmGt8d_DfFk/s1600/code.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="324" src="http://3.bp.blogspot.com/-E7LEU8SKCeY/TxBbcRYaTkI/AAAAAAAAAIA/AmGt8d_DfFk/s640/code.jpg" width="640" /></a></div><br /><br />Clearly the bug would have been more likely to have been caught, had we failed the build because the code failed to meet expected quality standards.  This is a potentially avoidable error.<br /><h2>Another Angle.</h2>Another way to try and establish a link between poor code quality and defects is to take advantage of something such as the Sonar hotspot view to see the most complex classes in you system.<br /><br /><div class="separator" style="clear: both; text-align: center;"></div>&nbsp;<a href="http://1.bp.blogspot.com/-jMcGCdq-xM0/TxBcF3WiqnI/AAAAAAAAAIQ/khdlLsgCRAg/s1600/sonar_hotspot.jpg" imageanchor="1" style="clear: left; display: inline !important; margin-bottom: 1em; margin-right: 1em; text-align: center;"><img border="0" height="122" src="http://1.bp.blogspot.com/-jMcGCdq-xM0/TxBcF3WiqnI/AAAAAAAAAIQ/khdlLsgCRAg/s320/sonar_hotspot.jpg" width="320" /></a><br /><br /><br />You can then work backwards and examine the history of those files to see if those classes are causing issues in your codebase. <br />The trouble is that it is not that simple.  High complexity files, which are used infrequently, are less likely to cause you trouble than those which are more frequently used, but of a lower complexity.<br /><h2>Automating the process.</h2>For this to be any use it probably needs to be automated so that a large sample of data can be examined. Some tools already make this link between defects and the related fix source code. <br/>The next step is to pull that data back and run your metrics analysis on the files.  <br /><h2>Summary</h2>None of this is conclusive,  however I still think it's a useful technique.<br/><br/>What it is most likely to prove is that you have had past problems which you could have avoided with metrics.  It should also give you an idea of which metrics to use.<br /><br/>It's likely also to show that most problems are not caused by poor code quality,  but other factors instead.<br /><div class="blogger-post-footer"><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6293455831777973426-8539279418450966297?l=johndobie.blogspot.com" alt="" /></div>    ]]></content>
  </entry>
  <entry>
    <title>Unit Test Code Coverage With Jacoco</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8291" />
    <id>http://www.javaworld.com/community/node/8291</id>
    <published>2012-01-16T06:09:00-05:00</published>
    <updated>2012-02-06T07:00:47-05:00</updated>
    <author>
      <name>John Dobie</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><title>Insert title here</title>It’s easy to collect unit test code coverage because all of the common tools are geared up for it.<br />This article will explain how you can add unit test coverage to your Maven application in 10 minutes.<br>We will use the excellent Jacoco code coverage library to show how easy it is.<br /><h2>Examples</h2>All of the examples come from this article.<br /><a href="http://johndobie.blogspot.com/2011/11/test-doubles-with-mockito.html">http://johndobie.blogspot.com/2011/11/test-doubles-with-mockito.html</a><br /><br />You can check them out from here    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><title>Insert title here</title>It’s easy to collect unit test code coverage because all of the common tools are geared up for it.<br />This article will explain how you can add unit test coverage to your Maven application in 10 minutes.<br>We will use the excellent Jacoco code coverage library to show how easy it is.<br /><h2>Examples</h2>All of the examples come from this article.<br /><a href="http://johndobie.blogspot.com/2011/11/test-doubles-with-mockito.html">http://johndobie.blogspot.com/2011/11/test-doubles-with-mockito.html</a><br /><br />You can check them out from here<br /><pre class="brush:java">svn co<br /><a href="https://designbycontract.googlecode.com/svn/trunk/examples/testing/test-doubles" title="https://designbycontract.googlecode.com/svn/trunk/examples/testing/test-doubles">https://designbycontract.googlecode.com/svn/trunk/examples/testing/test-...</a><br /><br /><br /></pre>With Maven 3 installed,  you can run them with this command.<br /><pre class="brush:java">mvn clean package<br /></pre><h2>What is Jacoco</h2><div>Jacoco is a free code coverage library for Java.  <a href="http://www.eclemma.org/jacoco/">http://www.eclemma.org/jacoco/</a></div>I use it because it is very simple to add to all types of build including ANT and Maven, and it is also very simple to add to Java containers or a standalone JVM.<br /><h2>How Does it Work?</h2><img border="0" src="http://2.bp.blogspot.com/-icRrq-avBn0/TxBVxEv9WjI/AAAAAAAAAHQ/94jp0T5Gv54/s1600/jacoco.jpg" /><br />Jacoco uses the standard JVM Tool Interface. <a href="http://java.sun.com/developer/technicalArticles/J2SE/jvm_ti/">http://java.sun.com/developer/technicalArticles/J2SE/jvm_ti/</a> <br />In simple terms you attach a Jacoco agent to a JVM when it starts. It was introduced in JDK 5 for monitoring and profiling JVMs and being able to dynamically modify Java classes as they're being loaded.<br/>Whenever a class is loaded Jacoco can instrument the class so it can see when the class is called and what lines are called.  That’s how it builds up the coverage statistics.  This is all done on the fly. <br/>By default the results file is created when the JVM terminates.<br />You can also run the agent in server mode which allows you to trigger a dump of the results.<br /><h2>How do you attach the agent to the JVM?</h2>This is a very simple process.  You must specify where the jacoco jar is located and then you pass some parameters to define how the agent is to run.<br /><pre class="brush:xml">-javaagent:[yourpath/]jacocoagent.jar=[option1]=[value1],[option2]=[value2]<br /><br /></pre>A typical run might look like this<br /><pre class="brush:xml">-javaagent:jacoco.jar=destfile=${sonar.jacoco.itReportPath},includes=com.dbc.*<br /></pre>A full reference is found here.<a href="http://www.eclemma.org/jacoco/trunk/doc/agent.html">http://www.eclemma.org/jacoco/trunk/doc/agent.html</a>   <br /><h2>Jacoco Support For Maven</h2>The docs for the maven plugin are defined here. <a href="http://www.eclemma.org/jacoco/trunk/doc/maven.html">http://www.eclemma.org/jacoco/trunk/doc/maven.html</a><br />First we need to add the plugin itself.<br /><pre class="brush:xml"><plugin><br />  <groupid>org.jacoco</groupid><br />  <artifactid>jacoco-maven-plugin</artifactid><br />  <version>0.5.5.201112152213</version><br /></plugin><br /></pre>We can then define where the jacoco reports are output.<br /><pre class="brush:xml"><configuration><br />  <destfile>${basedir}/target/coverage-reports/jacoco-unit.exec</destfile><br />  <datafile>${basedir}/target/coverage-reports/jacoco-unit.exec</datafile><br /></configuration><br /></pre>Finally we need to define the following 2 executions to make the agent run before the tests are run and also to make sure that the jacoco report task is run when package is executed.<br /><pre class="brush:xml"><executions><br />  <execution><br />    <id>jacoco-initialize</id><br />    <goals><br />      <goal>prepare-agent</goal><br />    </goals><br />  </execution><br />  <execution><br />    <id>jacoco-site</id><br />    <phase>package</phase><br />    <goals><br />      <goal>report</goal><br />    </goals><br />  </execution><br /></executions><br /></pre><br/><a name="pom"></a>All this together is shown here<pre class="brush:xml"><br /><plugins><br /> <plugin><br />  <groupId>org.jacoco</groupId><br />  <artifactId>jacoco-maven-plugin</artifactId><br />  <version>0.5.5.201112152213</version><br />  <configuration><br />   <destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile><br />   <dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile><br />  </configuration><br />  <executions><br />   <execution><br />    <id>jacoco-initialize</id><br />    <goals><br />     <goal>prepare-agent</goal><br />    </goals><br />   </execution><br />   <execution><br />    <id>jacoco-site</id><br />    <phase>package</phase><br />    <goals><br />     <goal>report</goal><br />    </goals><br />   </execution><br />  </executions><br /> </plugin><br /> <plugin><br />  <groupId>org.apache.maven.plugins</groupId><br />  <artifactId>maven-compiler-plugin</artifactId><br />  <configuration><br />   <source>1.5</source><br />   <target>1.5</target><br />  </configuration><br /> </plugin><br /></plugins><br /><br /></pre><br />To run the examples execute the following command.<br /><pre class="brush:xml">mvn clean package<br /><br /></pre><h1>Results.</h1>The results are published in /target/site/jacoco.<br /><img border="0" height="148" src="http://3.bp.blogspot.com/-1tk_giJBIJQ/TxBXxYsv8cI/AAAAAAAAAHg/z54sLZwJ4R4/s640/results.jpg" width="640" /><div class="blogger-post-footer"><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6293455831777973426-2896813945194994928?l=johndobie.blogspot.com" alt="" /></div>    ]]></content>
  </entry>
  <entry>
    <title>Revealing Project Naughtiness with Tattletale</title>
    <link rel="alternate" type="text/html" href="http://www.javaworld.com/community/node/8290" />
    <id>http://www.javaworld.com/community/node/8290</id>
    <published>2012-01-12T23:46:00-05:00</published>
    <updated>2012-01-13T00:01:21-05:00</updated>
    <author>
      <name>Dustin Marx</name>
    </author>
    <summary type="html"><![CDATA[<!--paging_filter--><!--paging_filter--><p><a href="http://www.jboss.org/tattletale">Tattletale</a> is a highly useful development tool that not only has a catchy name, but also has a clever slogan: "Betraying your project's naughty little secrets." <a href="http://docs.jboss.org/tattletale/presentations/tattletale-1.0.pdf">Tattletale</a> scours JAR files to find various naught little secrets about dependencies, multiple versions, extraneous versions of classes, JARs in multiple locations, and so forth.    ]]></summary>
    <content type="html"><![CDATA[<!--paging_filter--><p><a href="http://www.jboss.org/tattletale">Tattletale</a> is a highly useful development tool that not only has a catchy name, but also has a clever slogan: "Betraying your project's naughty little secrets." <a href="http://docs.jboss.org/tattletale/presentations/tattletale-1.0.pdf">Tattletale</a> scours JAR files to find various naught little secrets about dependencies, multiple versions, extraneous versions of classes, JARs in multiple locations, and so forth. It is a simple tool that can be run from the command-line to generate simple HTML reports of multiple characteristics about JARs and classes.</p>

<p>To demonstrate Tattletale, I will execute it against a <a href="http://www.springsource.org/node/813">Spring Framework 2.5.6</a> installation. It is simple to run Tattletale and this is demonstrated in the next screen snapshot.</p>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-eqN4gzxP2Sg/Tw-xfhpJznI/AAAAAAAAC8I/pYRRmvM6QcA/s1600/runningTattletaleAgainstSpring256.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="189" width="320" src="http://1.bp.blogspot.com/-eqN4gzxP2Sg/Tw-xfhpJznI/AAAAAAAAC8I/pYRRmvM6QcA/s320/runningTattletaleAgainstSpring256.png" /></a></div>

<p>The <code>tattletale.jar</code> is an executable JAR and so is run with <code>java -jar tattletale.jar</code>. The first argument passed to it is the directory to be recursively searched (Spring 2.5.6 distribution in this case) and the second argument is the directory to which the HTML reports should be written (<code>spring-output</code> in this example). The directory listing of the <code>spring-output</code> directory is shown next.</p>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-eXOSBnipvvE/Tw-yghzAsSI/AAAAAAAAC8U/ChzDen9T1co/s1600/tattletaleSpring256OutputDirectoryListing.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="240" width="320" src="http://4.bp.blogspot.com/-eXOSBnipvvE/Tw-yghzAsSI/AAAAAAAAC8U/ChzDen9T1co/s320/tattletaleSpring256OutputDirectoryListing.png" /></a></div>

<p>As the two previous snapshots indicate, it is very straightforward to run Tattletale against a desired directory. A web browser can be used to open the <code>index.html</code> page as the starting page. This is shown in the next screen snapshot.</p>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-T_1m75Y9buo/Tw-y3xW5jGI/AAAAAAAAC8g/Cf02TBGUslo/s1600/topOfTattletaleOutputForSpring256.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="320" width="203" src="http://2.bp.blogspot.com/-T_1m75Y9buo/Tw-y3xW5jGI/AAAAAAAAC8g/Cf02TBGUslo/s320/topOfTattletaleOutputForSpring256.png" /></a></div>

<p>Only a subset of the available reports are shown in the above snapshot. Clicking on links brings up the individual reports. I show portions of select reports (circular dependencies, class locations, multiple copies of JARs, transitive dependencies, and transitive dependents) next.</p>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-uSFumGcmsHc/Tw-zoi4l5KI/AAAAAAAAC8s/jZfnIAv2oDY/s1600/tattletaleSpring256CircularDependency.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="135" width="320" src="http://1.bp.blogspot.com/-uSFumGcmsHc/Tw-zoi4l5KI/AAAAAAAAC8s/jZfnIAv2oDY/s320/tattletaleSpring256CircularDependency.png" /></a></div>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-L4868wc7_Kw/Tw-z1l8qmKI/AAAAAAAAC84/vkS0NC4heQU/s1600/tattletaleSpring256ClassListing.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="139" width="320" src="http://2.bp.blogspot.com/-L4868wc7_Kw/Tw-z1l8qmKI/AAAAAAAAC84/vkS0NC4heQU/s320/tattletaleSpring256ClassListing.png" /></a></div>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-dJMlkW5xaF8/Tw-0EU0EdGI/AAAAAAAAC9E/rEwCvZVasQU/s1600/tattletaleSpring256MultipleJars.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="145" width="320" src="http://3.bp.blogspot.com/-dJMlkW5xaF8/Tw-0EU0EdGI/AAAAAAAAC9E/rEwCvZVasQU/s320/tattletaleSpring256MultipleJars.png" /></a></div>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-GE83tFkgUUw/Tw-0R5UV8WI/AAAAAAAAC9Q/Qcuxe4vZDgw/s1600/tattletaleSpring256TransitiveDependsOn.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="179" width="320" src="http://2.bp.blogspot.com/-GE83tFkgUUw/Tw-0R5UV8WI/AAAAAAAAC9Q/Qcuxe4vZDgw/s320/tattletaleSpring256TransitiveDependsOn.png" /></a></div>

<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-csT6vLa2Qps/Tw-0V0QOD6I/AAAAAAAAC9c/O_LKquA8oS8/s1600/tattletaleSpring256TransitiveDependents.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="109" width="320" src="http://3.bp.blogspot.com/-csT6vLa2Qps/Tw-0V0QOD6I/AAAAAAAAC9c/O_LKquA8oS8/s320/tattletaleSpring256TransitiveDependents.png" /></a></div>

<p>Tattletale is so easy to use, very little <a href="http://www.jboss.org/tattletale/docs">documentation</a> is necessary. However, there is a <a href="http://docs.jboss.org/tattletale/presentations/tattletale-1.0.pdf">slide presentation</a> and a <a href="http://docs.jboss.org/tattletale/userguide/1.1/pdf/JBossTattletale-UsersGuide.pdf">User's Guide</a> with introductory information. The 32-page User Guide covers running Tattletale (similar to this post) along with providing details on how to configure the tool via <code>jboss-tattletale.properties</code> and providing an overview of the many reports that <a href="http://blog.carlossanchez.eu/2011/03/23/finding-duplicate-classes-in-your-war-files-with-tattletale/">Tattletale</a> provides about one's project.</p>

<p>To address and correct a project's naughtiest little secrets, one must know what they are. Tattletale is an easy-to-use tool that exposes these naughty secrets so that they can be addressed.</p><div class="blogger-post-footer"><p>Original posting available at <a href="http://marxsoftware.blogspot.com/">http://marxsoftware.blogspot.com/</a> (Inspired by Actual Events)</p><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/6517450204508339514-8318244361010602655?l=marxsoftware.blogspot.com" alt="" /></div><img src="http://feeds.feedburner.com/~r/InspiredByActualEvents/~4/DF6sfRDApP4" height="1" width="1" />    ]]></content>
  </entry>
</feed>

