Showing posts with label Java Tutorials. Show all posts
Showing posts with label Java Tutorials. Show all posts

Monday, September 14, 2009

Entrepreneur sees future - on his iPhone

Last year, just as Joe Michels' corporate career was crashing, he saw hope in the form of a tiny gadget: Apple's iPhone.

The software developer watched as dozens of jobs at his Scottsdale firm were outsourced to India and more layoffs loomed.

So that April, he started Plan B. He spent months on nights and weekends writing My Eyes Only - an iPhone software application that would store log-ins, credit-card numbers and private information in a password-protected, encrypted area.

Three months after it hit Apple's online App Store, sales seemed on pace to replace his six-figure income.

"I realized I had nowhere to go but up because I could build more apps," said Michels, 47.

Apple boasts that there is an app for almost everything. There are apps that process credit-card sales, check medical symptoms, find cheaper gas stations and even show the value of your neighbor's house.

Michels is among the tech-savvy masses hoping to cash in on app mania. He's also a member of the Phoenix iPhone Developer Group. Nicknamed Pi, the group claims more than 100 mostly seasoned programmers who have soldiered on through the demise of earlier technological frontiers, from the death of the floppy disk to the dot-com burst.

They are all adamant that the iPhone - a mini-computer that is also a phone - is the next big wave of technological innovation. Sure, they would love to win the app lottery and become millionaires. But most of these men (so far there are no women) just hope to quit their day jobs and make a good living building a long-term business.

But with more than 75,000 apps, an explosion from the 500 that debuted 14 months ago, competition is towering, and app millionaires rare.

"For every one of those, there were 10,000 others that put a bunch of work into something that didn't make much money," said Brad O'Hearne, owner of Gilbert-based Big Hill Software LLC and founder of Pi. Wearing a Pi symbol T-shirt, he joked with the group at a recent meeting about many of their dual lives.

"We sound like a support group for superheroes: 'By day I do this, and by night . . . .' "

A month into his new venture, Michels' app was doing well, but he couldn't predict how long sales would keep rolling in. Or if it would be possible to one day quit his job.

Sales roll in

Like many good inventions, Michels' idea started with a need.

Two years ago, he ditched work early to buy an iPhone the day the price dropped to $399.

"I knew from the minute I saw it, it was going to be a big hit," he said. "I wanted to absorb it for a while."

Michels quickly found he needed a secure area to store passwords and credit-card numbers. At the time, Apple hadn't released its iPhone Software Development Kit allowing anyone to write applications. So he waited. And in March 2008, he was among more than 100,000 to download the kit within its first four days. The kit gave developers the tools, techniques and permission to create apps.

Even if by trial and error, Michels knew he could write a program to protect sensitive numbers and passwords.

So he got to work. For the next four months, he spent three hours after work every night, and about eight to 10 hours every weekend, hurrying to get the program right and to be among the first to offer such an app.

He missed out on movie nights and time with his wife and two kids. But he persevered, knowing he might be able to create a better future for his family.

When his app finally hit iTunes in late July, it was one of only about three of its kind on the market. It sold for $8.99.

Michels eagerly awaited sales. The first two days were slow, but by week's end, he was ecstatic.

"My God, this could actually work out!" he remembers thinking. "I wanted to quit my job instantly."

His wife, Lynn, convinced him to wait a few months to see if the sales would continue.

Michels kept busy answering customers' questions and thinking about his next app idea.

By October, seven months of 70-plus-hour weeks were taking their toll. And enough sales were rolling in that Lynn, also the family bookkeeper, was on board for taking a leap of faith.

"She's my hero," Michels said. "She has been 100 percent behind me. She knew I wasn't happy at work given the realities of the future."

Jobs left behind

As Michels was quitting his job last fall, O'Hearne was starting Pi, a group that now numbers nearly 150 from its initial 35.

The group formed after Apple lifted its ban on developers sharing ideas and information.

O'Hearne wrote GPS Mail, which lets users e-mail a map of their current location (and provide directions) instantly. He knew he and others could create better apps if they could exchange technical advice and brainstorm ways to improve and market them. The group talks code, debates the merits of Java vs. Objective-C programming language and generally talks in sentences that sound foreign to non-developers.

For the most part, Pi is not packed with wide-eyed teens or 20-somethings writing code in their dorm rooms. The core members are in their 30s and 40s, having seen plenty of innovations come and go. They've worked as Web and software developers at large firms, many using Microsoft-based programs after Apple's popularity dipped in the 1990s.

Seasoned as they are, it's easy to catch the whole brainy Pi group marvel over the iPhone, sometimes sounding like awestruck 10-year-olds.

"This is a Star Trek device," said Gilbert-based developer Jiva DeVoe. "We live in the future."

The iPhone celebrated only its second birthday on June 29. Today, more than 45 million iPhones and iPod Touch devices (which also use apps) have been sold, and more than 1.5 billion apps have been downloaded.

There's Shazam, a popular app that will identify a song playing in the background and even let you buy it from Apple's iTunes store. Urbanspoon suggests a nearby restaurant for dinner. Shake your iPhone, and options on the screen spin like a slot machine.

The selection grows daily.

That's part of what iPhone developers love and hate.

Specifically, they love the App Store for giving them direct access to customers but hate being lost among the tens of thousands of apps with little way to get noticed if they aren't a staff pick or a top seller. Many software developers have gone from writing code to answering international customer e-mails (some have to be translated) to trying to boost sales - all while coming up with new apps.

They are inspired by those such as Michels and DeVoe, who wrote iZen Garden. The meditation app lets users "rake" sand with their finger and place stones and plants while listening to soothing tunes. DeVoe's app was one of the first 500 to be offered at the App Store's July 11, 2008, debut, and earned kudos as a staff pick.

A computer programmer for a defense contractor, DeVoe also was able to give up his job and dive into full-time app development.

"It felt fantastic and liberating," he said, adding it was also a bit lonely and scary at first. "Even if all of this ended tomorrow, I wouldn't trade my time I've had being independent for anything - being able to do what I want, when I want."

Like all the local app developers, Michels is still trying to figure out a way to beat the competition, especially as the app offerings explode and prices stay low. iTunes is filled with apps that are either free or 99 cents.

"Most of the people I know who have 99-cent apps are not able to support themselves," Michels said.

All the while, more are joining the competition.

Recently, Pi's youngest member, 17-year-old Craig Bishop, gave the gang a tutorial to a complex programming tool that left some amazed.

"Right now, it beats flipping hamburgers," said Bishop, a senior at Desert Vista High School in Phoenix.

He wrote an app called Homework to help students manage their deadlines, but he's focused now on creating an iPhone game.

"I'm up against this!" Michels said after hearing Bishop, then promptly counseled the teen to take business classes, too.

A hopeful future

Although Michels has fared better than many other developers, it's not easy.

Last November, a glitch in his program forced him to stop sales for two weeks.

"Half a month's sales are pretty critical when you just quit your job," he said.

Once his initial glitch was fixed, the recession hit. Michels had some sleepless nights until sales picked up again in January and February only to drop off again by spring.

At that time, the development team he had supervised at his former job was laid-off, and his old boss was on his way out, too.

He thought he made the right decision.

"It has been a roller coaster, without question," he said. In June, he even considered looking for a job if business didn't pick up.

He kept pushing ahead.

This summer, his second app, My Eyes Only Photo, was released. It protects and encrypts photos. He priced it at $3.99, $5 less than his first program. Sales right now "are enough to make a good living," he said.

Today, he spends his days in a small office next to the master bedroom in his Scottsdale home. He has a good view of the backyard above his three Apple computers and is generally content but not stress-free.

He admits he misjudged the app explosion.

"I missed how many developers would try to develop for this platform," he said. "I thought I could get a foothold before it caught on."

Now, his whole family sees his business, called Software Ops, as an opportunity. His wife and 12-year-old daughter are helping him create an entertainment app. And most nights and weekends are family time again.

"The biggest thing is, I see the future, and the future is hopeful, whereas the other future wasn't," he said. "You can handle the stress if you have a hopeful future."

Thursday, September 10, 2009

Checking a File or Directory

Checking File Accessibility

You have a Path instance representing a file or directory, but does that file exist on the file system? Is it readable? Writable? Executable?

To verify that a file exists and that the program can access it as needed, you can use the checkAccess(AccessMode...) method. The varargs argument can be any combination of these AccessMode options:

  • READ – Checks that the file exists and that the program has permission to read the file. On UNIX systems, this option tests the file owner READ bit
  • WRITE – Checks that the file exists and that the program has permission to write to the file. On UNIX systems, this tests the file owner WRITE bit
  • EXECUTE – Checks that the file exists and that the program has permission to execute the file. For directories on UNIX file systems, the execute bit must be set in order to access files or subdirectories. On UNIX system, this option tests the file owner EXECUTE bit

If checkAccess is called with no argument, the file's existence is checked. If all you need to do is verify the file's existence, you could use the exists or notExists methods, as described in Verifying the Existence of a File or Directory.

The following code snippet verifies that a particular file exists and that the program has the ability to execute the file. Note that this snippet assumes that the Path is a file and not a directory. You can use the java.nio.file.attributes package to learn more about the Path: is it a directory? A regular file? A symbolic link? Later, in Basic File Attributes, this code snippet is extended to verify that the Path locates a regular executable file and only a regular executable file.

import static java.nio.file.AccessMode.*;

Path file = ...;
try {
file.checkAccess(READ, EXECUTE);
} catch (IOException x) {
//Logic for error condition...
return;
}

//Logic for executable file...

Note: Once the checkAccess method completes, there is no guarantee that the file can be accessed. A common security flaw in many applications is to perform a check and then access the file. For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too).

Checking Whether Two Paths Locate the Same File

When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. The isSameFile(Path) method compares two paths to determine if they locate the same file on the file system. For example:

Path p1 = ...;
Path p2 = ...;

try {
if (p1.isSameFile(p2)) {
//Logic when the paths locate the same file
}
} catch (IOException x) {
//Logic for error condition...
return;
}

File Operations

The Path class offers a rich set of methods for reading, writing, and manipulating files and directories. Before proceeding to the remaining sections, you should familiarize yourself with the following common concepts:

Catching Exceptions

With file I/O, unexpected conditions are a fact of life: a file exists (or doesn't exist) when expected, the program doesn't have access to the file system, the default file system implementation does not support a particular function, and so on. Numerous errors can be encountered.

All methods that access the file system can throw an IOException. It is best practice to catch these exceptions by embedding these methods into a try block and to catch any exceptions in a catch block. Most of the examples in this lesson follow this protocol. Also, if your code has opened any streams or channels, you should close them in a finally block.

In addition to IOException, many specific exceptions extend FileSystemException. This class has some useful methods that return the file involved (getFile), the detailed message string (getMessage), the reason why the file system operation failed (getReason), and the "other" file involved, if any (getOtherFile).

The following code snippet shows how the getFile method might be used:

try {
...
} catch (NoSuchFileException x) {
System.err.format("%s does not exist\n", x.getFile());
}

For more information, see Catching and Handling Exceptions.

Varargs

Several Path methods accept an arbitrary number of arguments when flags are specified. For example, in the following method signature, the ellipses notation after the CopyOption argument indicates that the method accepts a variable number of arguments, or varargs, as they are typically called:

Path moveTo(Path, CopyOption...)

When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array (CopyOption[]) of values.

In the moveTo example, the method can be invoked as follows:

import static java.nio.file.StandardCopyOption.*;

Path orig = ...;
Path new = ...;
orig.moveTo(new, REPLACE_EXISTING, ATOMIC_MOVE);

For more information about varargs syntax, see Arbitrary Number of Arguments.

Atomic Operations

Several Path methods, such as moveTo, can perform certain operations atomically in some file systems.

An atomic file operation is an operation that cannot be interrupted or "partially" performed. Either the entire operation is performed or the operation fails. This is important when you have multiple processes operating on the same area of the file system, and you need to guarantee that each process accesses a complete file.

Method Chaining

Many of the file I/O methods support the concept of method chaining.

You first invoke a method that returns an object. You then immediately invoke a method on that object, which returns yet another object, and so on. Many of the I/O examples use the following technique:

String value = Charset.defaultCharset().decode(buf).toString();
UserPrincipal group = file.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("me");

This technique produces compact code and enables you to avoid declaring temporary variables that you don't need.

FileRef Interface

The Path class implements the FileRef interface. The FileRef interface includes methods for locating a file and accessing that file. Coverage for the FileRef methods is woven into the lesson where relevant.

What Is a Glob?

Two methods in the Path class accept a glob argument, but what is a glob?

You can use glob syntax to specify pattern-matching behavior.

A glob pattern is specified as a string and is matched against other strings, such as directory or file names. Glob syntax follows several simple rules:

  • An asterisk, *, matches any number of characters (including none).
  • Two asterisks, **, works like * but crosses directory boundaries. This syntax is generally used for matching complete paths.
  • A question mark, ?, matches exactly one character.
  • Braces specify a collection of subpatterns. For example:
    • {sun,moon,stars} matches "sun", "moon", or "stars."
    • {temp*,tmp*} matches all strings beginning with "temp" or "tmp."
  • Square brackets convey a set of single characters or, when the hyphen character (-) is used, a range of characters. For example:
    • [aeiou] matches any lowercase vowel.
    • [0-9] matches any digit.
    • [A-Z] matches any uppercase letter.
    • [a-z,A-Z} matches any uppercase or lowercase letter.
    Within the square brackets, *, ?, and \ match themselves.
  • All other characters match themselves.
  • To match *, ?, or the other special characters, you can escape them by using the backslash character, \. For example: \\ matches a single backslash, and \? matches the question mark.

Here are some examples of glob syntax:

  • *.html – Matches all strings that end in .html
  • ??? – Matches all strings with exactly three letters or digits
  • *[0-9]* – Matches all strings containing a numeric value
  • *.{htm,html,pdf} – Matches any string ending with .htm, .html or .pdf
  • a?*.java – Matches any string beginning with a, followed by at least one letter or digit, and ending with .java
  • {foo*,*[0-9]*} – Matches any string beginning with foo or any string containing a numeric value


Note: If you are typing the glob pattern at the keyboard and it contains one of the special characters, you must put the pattern in quotes ("*"), use the backslash (\*), or use whatever escape mechanism is supported at the command line.

The glob syntax is powerful and easy to use. However, if it is not sufficient for your needs, you can also use a regular expression. For more information, see the Regular Expressions lesson.

For more information about the glob sytnax, see the API specification for the getPathMatcher method in the FileSystem class.

Path Operations

The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path. There are also methods for matching the path string and methods for removing redundancies in a path. This lesson addresses these Path methods, sometimes called syntactic operations, because they operate on the path itself and don't necessarily access the file system.

This section covers the following:

Creating a Path

A Path instance contains the information used to specify the location of a file or directory. At the time it is defined, a Path is provided with a series of one or more names. A root element or a file name might be included, but neither are required. A Path might consist of just a single directory or file name.

You can easily create a Path object by using one of the following get methods from the Paths (note the plural) helper class:

Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get(args[0]);
Path p3 = Paths.get("file:///Users/joe/FileTest.java");

The Paths.get method is shorthand for the following code:

Path p4 = FileSystems.getDefault().getPath("/users/sally");

Retrieving Information about a Path

You can think of the Path as storing these name elements as a sequence. The highest element in the directory structure would be located at index 0. The lowest element in the directory structure would be located at index [n-1], where n is the number of name elements in the Path. Methods are available for retrieving individual elements or a subsequence of the Path using these indexes.

The examples in this lesson use the following directory structure.

Sample directory structure

Sample Directory Structure

The following code snippet defines a Path instance and then invokes several methods to obtain information about the path:

// None of these methods requires that the file corresponding
// to the Path exists, with the possible exception of isHidden.
Path path = Paths.get("C:\\home\\joe\\foo"); // Microsoft Windows syntax
//Path path = Paths.get("/home/joe/foo"); // Solaris syntax
System.out.format("toString: %s%n", path.toString());
System.out.format("getName: %s%n", path.getName());
System.out.format("getName(0): %s%n", path.getName(0));
System.out.format("getNameCount: %d%n", path.getNameCount());
System.out.format("subpath(0,2): %d%n", path.subpath(0,2));
System.out.format("getParent: %s%n", path.getParent());
System.out.format("getRoot: %s%n", path.getRoot());
System.out.format("isHidden: %s%n", path.isHidden());
Here is the output for both Windows and the Solaris OS:

Method Invoked Returns in the Solaris OS Returns in Microsoft Windows Comment
toString /home/joe/foo C:\home\joe\foo Returns the string representation of the Path. If the path was created using Filesystems.getDefault().getPath(String) or Paths.get (the latter is a convenience method for getPath), the method performs minor syntactic cleanup. For example, in a UNIX operating system, it will correct the input string //home/joe/foo to /home/joe/foo.
getName foo foo Returns the file name or the last element of the sequence of name elements.
getName(0) home home Returns the path element corresponding to the specified index. The 0th element is the path element closest to the root.
getNameCount 3 3 Returns the number of elements in the path.
subpath(0,2) home/joe home\joe Returns the subsequence of the Path (not including a root element) as specified by the beginning and ending indexes.
getParent /home/joe \home\joe Returns the path of the parent directory.
getRoot / C:\ Returns the root of the path.
isHidden false false Returns true if the file is considered hidden for a particular file system. In the Solaris OS, hidden files are prefixed by a dot ("."). In Microsoft Windows, hidden files are specified by a file attribute, so accessing the file system is necessary to check the HIDDEN attribute.

The previous example shows the output for an absolute path. In the following example, a relative path is specified:

Path path = Paths.get("sally/bar");     // Solaris syntax
or
Path path = Paths.get("sally\\bar"); // Microsoft Windows syntax

Here is the output for Windows and the Solaris OS:

Method Invoked Returns in the Solaris OS Returns in Microsoft Windows
toString sally/bar sally\bar
getName bar bar
getName(0) sally sally
getNameCount 2 2
subpath(0,1) sally sally
getParent sally sally
getRoot null null
isHidden false false

Removing Redundancies From a Path

Many file systems use "." notation to denote the current directory and ".." to denote the parent directory. You might have a situation where a Path contains redundant directory information. Perhaps a server is configured to save its log files in the "/dir/logs/." directory, and you want to delete the trailing "/." notation from the path.

The following examples both include redundancies:

/home/./joe/foo
/home/sally/../joe/foo
The normalize method removes any redundant elements, which includes any "." or "directory/.." occurrences. Both of the preceding examples normalize to /home/joe/foo.

It is important to note that normalize doesn't check at the file system when it cleans up a path. It is a purely syntactic operation. In the second example, if sally were a symbolic link, removing sally/.. might result in a Path that no longer locates the intended file.

To clean up a path while ensuring that the result locates the correct file, you can use the toRealPath method. This method is described in the next section, Converting a Path.

Converting a Path

You can use three methods to convert the Path. If you need to convert the path to a string that can be opened from a browser, you can use toUri. For example:
Path p1 = Paths.get("/home/logfile");
System.out.format("%s%n", p1.toUri()); // Result is file:///home/logfile

The toAbsolutePath method converts a path to an absolute path. If the passed-in path is already absolute, it returns the same Path object. The toAbsolutePath method can be very helpful when processing user-entered file names. For example:

public class FileTest {
public static void main(String[] args) throws IOException {

if (args.length < 1) {
System.out.println("usage: FileTest file");
System.exit(-1);
}

// Converts the input string to a Path object.
Path inputPath = Paths.get(args[0]);

// Converts the input Path to an absolute path.
// Generally, this means prepending the current working
// directory. If this example were called like this:
// java FileTest foo
// the getRoot and getParent methods would return null
// on the original "inputPath" instance. Invoking getRoot and
// getParent on the "fullPath" instance returns expected values.
Path fullPath = inputPath.toAbsolutePath();

}
}

The toAbsolutePath method converts the user input and returns a Path that returns useful values when queried. The file does not need to exist for this method to work.

The toRealPath method returns the real path of an existing file. This method performs several operations in one:

  • If true is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.
  • If the Path is relative, it returns an absolute path.
  • If the Path contains any redundant elements, it returns a path with those elements removed.

This method throws an exception if the file does not exist or cannot be accessed. You can catch the exception when you want to handle any of these cases. For example:

try {
Path fp = path.ToRealPath(true);
} catch (NoSuchFileException x) {
System.err.format("%s: no such file or directory%n", path);
//Logic for case when file doesn't exist.
} catch (IOException x) {
System.err.format("%s%n", x);
//Logic for other sort of file error.
}

Joining Two Paths

You can combine paths by using the resolve method. You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.

For example, consider the following code snippet:

Path p1 = Paths.get("/home/joe/foo");          // Solaris
System.out.format("%s%n", p1.resolve("bar")); // Result is /home/joe/foo/bar

or

Path p1 = Paths.get("C:\\home\\joe\\foo"); // Microsoft Windows
System.out.format("%s%n", p1.resolve("bar")); // Result is C:\home\joe\foo\bar
Passing an absolute path to the resolve method returns the passed-in path:
Paths.get("foo").resolve("/home/joe");       // Result is /home/joe

Creating a Path Between Two Paths

A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. You can meet this using the relativize method. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.

For example, consider two relative paths defined as joe and sally:

Path p1 = Paths.get("joe");
Path p2 = Paths.get("sally");
In the absence of any other information, it is assumed that joe and sally are siblings, meaning nodes that reside at the same level in the tree structure. To navigate from joe to sally, you would expect to first navigate one level up to the parent node and then down to sally:
Path p1_to_p2 = p1.relativize(p2);   // Result is ../sally
Path p2_to_p1 = p2.relativize(p1); // Result is ../joe
Consider a slightly more complicated example:
Path p1 = Paths.get("home");
Path p3 = Paths.get("home/sally/bar");
Path p1_to_p3 = p1.relativize(p3); // Result is sally/bar
Path p3_to_p1 = p3.relativize(p1); // Result is ../..
In this example, the two paths share the same node, home. To navigate from home to bar, you first navigate one level down to sally and then one more level down to bar. Navigating from bar to sally requires moving up two levels.

A relative path cannot be constructed if only one of the paths includes a root element. If both paths include a root element, the capability to construct a relative path is system dependent.

The recursive Copy example uses the relativize and resolve methods.

Comparing Two Paths

The Path class supports equals, enabling you to test two paths for equality. The startsWith and endsWith methods enable you to test whether a path begins or ends with a particular string. These methods are easy to use. For example:

Path path = ...;
Path p1 = ...;
Path p2 = Paths.get("/home");
Path p3 = Paths.get("foo");

if (path.equals(p3)) {
//equality logic here
} else if (path.startsWith(p1)) {
//path begins with "/home"
} else if (path.endsWith(p2)) {
//path ends with "foo"
}

The Path class implements the Iterable interface. The iterator method returns an object that enables you to iterate over the name elements in the path. The first element returned is that closest to the root in the directory tree. The following code snippet iterates over a path, printing each name element:

Path path = ...;
for (Path name: path) {
System.out.println(name);
}

The Path class also implements the Comparable interface. You can compare Path objects by using compareTo which is useful for sorting.

You can also put Path objects into a Collection. See the Collections trail for more information about this powerful feature.

When you want to verify that two Path objects locate the same file, you can use the isSameFile method, as described in Checking Whether Two Paths Locate the Same File.

Verifying the Existence of a File or Directory

Most of the methods described in this page are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists and the notExists methods. Note that !path.exists() is not equivalent to path.notExists(). When you are testing a file's existence, three results are possible:
  • The file is verified to exist.
  • The file is verified to not exist.
  • The file's status is unknown. This result can occur when the program does not have access to the file.
If both exists and notExists return false, the existence of the file cannot be verified.

The Path class also supports a more powerful method to check accessibility, the checkAccess method. This method is described in Checking File Accessibility.

The Path Class

The Path class, introduced in the JDK7 release, is the cornerstone of the java.nio.file package. If your application uses file I/O, you will want to learn about the powerful features of this class.

Version Note: If you have pre-JDK7 code that uses java.io.File, you can still take advantage of the Path class functionality by using the File.toPath method. See Legacy File I/O Code for more information.

As its name implies, the Path class is a programmatic representation of a path in the file system. A Path object contains the file name and directory list used to construct the path, and is used to examine, locate, and manipulate files.

A Path instance reflects the underlying platform. In the Solaris OS, a Path uses the Solaris syntax (/home/joe/foo) and in Microsoft Windows, a Path uses the Windows syntax (C:\home\joe\foo). A Path is not system independent. You cannot compare a Path from a Solaris file system and expect it to match a Path from a Windows file system, even if the directory structure is identical and both instances locate the same relative file.

The file or directory corresponding to the Path might not exist. You can create a Path instance and manipulate it in various ways: you can append to it, extract pieces of it, compare it to another path. At the appropriate time, you can check the existence of the file corresponding to the Path, create the file, open it, delete it, change its permissions, and so on.

The Path class is "link aware." Every Path method either detects what to do when a symbolic link is encountered, or it provides an option enabling you to configure the behavior when a symbolic link is encountered.

The Path class offers a rich feature set and is very easy to use. Most methods in the Path class fall into one of the following two categories:

  • Path operations – Methods for returning parts of a path, such as the root, name, or parent directory and methods for manipulating a path
  • File operations – Methods for opening a file for I/O, creating a file, creating a directory, deleting a file, copying a file, and so on

What Is a Path? (And Other File System Facts)

A file system stores and organizes files on some form of media, generally one or more hard drives, in such a way that they can be easily retrieved. Most file systems in use today store the files in a tree (or hierarchical) structure. At the top of the tree is one (or more) root nodes. Under the root node, there are files and directories (folders in Microsoft Windows). Each directory can contain files and subdirectories, which in turn can contain files and subdirectories, and so on, potentially to an almost limitless depth.

This section covers the following:

What Is a Path?

The following figure shows a sample directory tree containing a single root node. Microsoft Windows supports multiple root nodes. Each root node maps to a volume, such as C:\ or D:\. The Solaris OS supports a single root node, which is denoted by the slash character, /.

Sample directory structure

Sample Directory Structure
A file is identified by its path through the file system, beginning from the root node. For example, the statusReport file in the previous figure is described by the following notation in the Solaris OS:
/home/sally/statusReport
In Microsoft Windows, statusReport is described by the following notation:
C:\home\sally\statusReport
The character used to separate the directory names (also called the delimiter) is specific to the file system: The Solaris OS uses the forward slash (/), and Microsoft Windows uses the backslash slash (\).

Relative or Absolute?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

A relative path needs to be combined with another path in order to access a file. For example, joe/foo is a relative path. Without more information, a program cannot reliably locate the joe/foo directory in the file system.

Symbolic Links

File system objects are most typically directories or files. Everyone is familiar with these objects. But some file systems also support the notion of symbolic links. A symbolic link is also referred to as a symlink or a soft link.

A symbolic link is a special file that serves as a reference to another file. For the most part, symbolic links are transparent to applications, and operations on symbolic links are automatically redirected to the target of the link. (The file or directory being pointed to is called the target of the link.) Exceptions are when a symbolic link is deleted, or renamed in which case the link itself is deleted, or renamed and not the target of the link.

In the following figure, logFile appears to be a regular file to the user, but it is actually a symbolic link to dir/logs/HomeLogFile. HomeLogFile is the target of the link.

Sample symbolic link

Example of a Symbolic Link.

A symbolic link is usually transparent to the user. Reading or writing to a symbolic link is the same as reading or writing to any other file or directory.

The phrase resolving a link means to substitute the actual location in the file system for the symbolic link. In the example, resolving logFile yields dir/logs/HomeLogFile.

In real-world scenarios, most file systems make liberal use of symbolic links. Occasionally, a carelessly created symbolic link can cause a circular reference. A circular reference occurs when the target of a link points back to the original link. The circular reference might be indirect: directory a points to directory b, which points to directory c, which contains a subdirectory pointing back to directory a. Circular references can cause havoc when a program is recursively walking a directory structure. However, this scenario has been accounted for and will not cause your program to loop infinitely.

File I/O (Featuring NIO.2)

This section is being updated to reflect features and conventions of the upcoming release, JDK7. You can download the current JDK7 Snapshot from java.net. We've published this preliminary version so you can get the most current information now, and so you can tell us about errors, omissions, or improvements we can make to this tutorial.


The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the default file system. Though the API has many classes, you need to focus on only a few entry points. You will see that this API is very intuitive and easy to use.

The tutorial starts by asking what is a path? Then, the Path class, the primary entry point for the package, is introduced. Methods in the Path class relating to syntactic operations are explained. The tutorial then moves on to Path methods that deal with file operations. First, some concepts common to many file operations are introduced. The tutorial then covers methods for checking, deleting, copying, and moving files.

The tutorial shows how metadata is managed, before moving on to file I/O and directory I/O. Random access files are explained and issues specific to symbolic and hard links are examined.

Next, some of the very powerful, but more advanced, topics are covered. First, the capability to recursively walk the file tree is demonstrated, followed by information about how to search for files using wild cards. Next, how to watch a directory for changes is explained and demonstrated. Then, methods that didn't fit elsewhere are given some attention.

Finally, if you have file I/O code written prior to the JDK7 release, there is a map from the old API to the new API, as well as important information about the File.toPath method for developers who would like to leverage the new API without rewriting existing code.

Inforama Document Automation System 1.3 Released

Version 1.3 inlcudes a more advanced mailshot dialog, the ability to save a mailshot script for reuse, more advanced plug-in architecture with a sample plug-in for Salesforce contact details.

Inforama is a Java based Document Automation system which allows document templates to be created quickly and easily using OpenOffice. Templates are populated with data from parameters, databases and other datasources before being generated into PDFs for printing and emailing. Version 1.3 includes some significant enhancements and bug fixes including the following...

New mailshot dialogThe new mailshot dialog gives users better control over how documents are emailed and printed during a mailshot. Preview generated documents before processing them and save the entire mailshot script for future use to save time. For more on this see the mailshot dialog tutorial at http://www.in4ama.org/web/guest/community/wiki/-/wiki/Main/1.3+Mailshot+Dialog

Enhanced plug-in architecture Create plug-ins which can be used to add menus dialogs and wizards to the Studio. You can also create dataset plug-ins to retrieve your data from custom data sources

Salesforce plug-inThis is a sample plug-in which can be used to merge Salesforce contact data with generated documents. The source code for this plug-in is available for download from the sourceforge project at http://sourceforge.net/projects/inforama. More information on how to use the plug-in can be found at http://www.in4ama.org/web/guest/community/wiki/-/wiki/Main/Salesforce+Plug-in+for+Inforama

Visit the Inforama website at http://www.in4ama.org For a quick overview of how Inforama works have a look at the webcasts at http://in4ama.org/web/guest/documentation/webcasts

Sony Ericsson Puts Developers at the Centre of User Experience with XPERIA X2

New Streamlined Development Tool Maximises Revenue Opportunities and Allows
Developers to Create the First Windows Mobile 6.5 Applications for the XPERIA X2
LUND, Sweden--(Business Wire)--
Sony Ericsson launches the Panel SDK in a drive to encourage developers to
create content for the XPERIA X2. The eye-catching interface includes a new
range of interactive Panels on the home screen offering business, fun and
communication features. By providing unparalleled real estate and marketing
visibility, the Panel interface makes the developer central to the user
experience.

The Panel SDK includes a Panelizer which turns existing Flash, Java and Windows
Mobile applications into Panels for the XPERIA X2 , and a native software
development kit which allows developers to be the first to create panels for the
Windows Mobile 6.5 platform.

Using the Panelizer, developers are able to maximise the investments they have
already made creating compelling applications. In just a couple of clicks and
with no separate tool purchase, the Panelizer gives developers a low-cost way to
turn their content into the unique Sony Ericsson Panel experience. Panels are
then just one touch away from the consumer`s home screen, allowing developers to
truly shape the user`s mobile entertainment experience.

Besides supporting Panels and native applications, the XPERIA X2 is also
equipped with a Java Runtime that makes Java/Capuchin applications run as well
integrated as native applications.

Applications accepted as panels will be made available on Sony Ericsson`s market
place, PlayNow arena, giving developers access to an even wider range of
consumers using other Sony Ericsson handsets. Developers from around the world
also benefit from the 70% net revenue share offered by PlayNow arena, which is
available in 18 countries.

"Putting developers` applications directly in front of consumers is a crucial
focus for us," says Christopher David, Head of Developer and Partner Engagement
at Sony Ericsson. "We created the Panel SDK to streamline the development
process, minimising the time it takes to get applications directly to the
consumer and providing developers with additional revenue opportunities."

How it works

Developers can submit their applications by following these simple steps:

* Go to Sony Ericsson`s Developer World website
http://developer.sonyericsson.com
* Download the Panel SDK and follow the short Panel SDK tutorial
* Go to http://submit.sonyericsson.com and upload `Panelized` applications
* Within 30 days the submission approval process will be complete. Successful
applications are automatically available for wider usage on PlayNow arena.

Sony Ericsson is a top, global industry player with sales of around 97million
phones in 2008.Diversity is one of the core strengths of the company, with
operations in over 80 countries including manufacturing in China and R&D sites
in China, Europe, India, Japan and North America.Sony Ericsson was established
as a 50:50 joint venture by Sony and Ericsson in October 2001, with global
corporate functions located in London.

Friday, April 3, 2009

Specifying the Exceptions Thrown by a Method

The previous section showed how to write an exception handler for the writeList method in the ListOfNumbers class. Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception. For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it.

If the writeList method doesn't catch the checked exceptions that can occur within it, the writeList method must specify that it can throw these exceptions. Let's modify the original writeList method to specify the exceptions it can throw instead of catching them. To remind you, here's the original version of the writeList method that won't compile.

// Note: This method won't compile by design!
public void writeList() {
PrintWriter out =
new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = "
+ vector.elementAt(i));
}
out.close();
}
To specify that writeList can throw two exceptions, add a throws clause to the method declaration for the writeList method. The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example.
public void writeList() throws IOException,
ArrayIndexOutOfBoundsException
{
Remember that ArrayIndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory. You could just write the following.
public void writeList() throws IOException {

Putting It All Together

The previous sections described how to construct the try, catch, and finally code blocks for the writeList method in the ListOfNumbers class. Now, let's walk through the code and investigate what can happen.

When all the components are put together, the writeList method looks like the following.

public void writeList() {
PrintWriter out = null;

try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++)
out.println("Value at: " + i + " = "
+ vector.elementAt(i));

} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught "
+ "ArrayIndexOutOfBoundsException: "
+ e.getMessage());

} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());

} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();

}
else {
System.out.println("PrintWriter not open");
}
}
}
As mentioned previously, this method's try block has three different exit possibilities; here are two of them.
  1. Code in the try statement fails and throws an exception. This could be an IOException caused by the new FileWriter statement or an ArrayIndexOutOfBoundsException caused by a wrong index value in the for loop.
  2. Everything succeeds and the try statement exits normally.
Let's look at what happens in the writeList method during these two exit possibilities.

Scenario 1: An Exception Occurs

The statement that creates a FileWriter can fail for a number of reasons. For example, the constructor for the FileWriter throws an IOException if the program cannot create or write to the file indicated.

When FileWriter throws an IOException, the runtime system immediately stops executing the try block; method calls being executed are not completed. The runtime system then starts searching at the top of the method call stack for an appropriate exception handler. In this example, when the IOException occurs, the FileWriter constructor is at the top of the call stack. However, the FileWriter constructor doesn't have an appropriate exception handler, so the runtime system checks the next method — the writeList method — in the method call stack. The writeList method has two exception handlers: one for IOException and one for ArrayIndexOutOfBoundsException.

The runtime system checks writeList's handlers in the order in which they appear after the try statement. The argument to the first exception handler is ArrayIndexOutOfBoundsException. This does not match the type of exception thrown, so the runtime system checks the next exception handler — IOException. This matches the type of exception that was thrown, so the runtime system ends its search for an appropriate exception handler. Now that the runtime has found an appropriate handler, the code in that catch block is executed.

After the exception handler executes, the runtime system passes control to the finally block. Code in the finally block executes regardless of the exception caught above it. In this scenario, the FileWriter was never opened and doesn't need to be closed. After the finally block finishes executing, the program continues with the first statement after the finally block.

Here's the complete output from the ListOfNumbers program that appears when an IOException is thrown.

Entering try statement
Caught IOException: OutFile.txt
PrintWriter not open
The boldface code in the following listing shows the statements that get executed during this scenario:
public void writeList() {
PrintWriter out = null;

try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));

for (int i = 0; i < SIZE; i++)
out.println("Value at: " + i
+ " = " + vector.elementAt(i));

} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught "
+ "ArrayIndexOutOfBoundsException: "
+ e.getMessage());

} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());

} finally {
if (out != null) {

System.out.println("Closing PrintWriter");
out.close();
}
else {
System.out.println("PrintWriter not open");
}

}
}

Scenario 2: The try Block Exits Normally

In this scenario, all the statements within the scope of the try block execute successfully and throw no exceptions. Execution falls off the end of the try block, and the runtime system passes control to the finally block. Because everything was successful, the PrintWriter is open when control reaches the finally block, which closes the PrintWriter. Again, after the finally block finishes executing, the program continues with the first statement after the finally block.

Here is the output from the ListOfNumbers program when no exceptions are thrown.

Entering try statement
Closing PrintWriter
The boldface code in the following sample shows the statements that get executed during this scenario.
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++)
out.println("Value at: " + i + " = "
+ vector.elementAt(i));

}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught "
+ "ArrayIndexOutOfBoundsException: "
+ e.getMessage());

} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());

} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
}

else {
System.out.println("PrintWriter not open");
}
}
}

The finally Block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Note: If the JVM exits while the try or catch code is being executed, then the finally block will not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block will not execute even though the application as a whole continues.

The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeList method. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.

  1. The new FileWriter statement fails and throws an IOException.
  2. The vector.elementAt(i) statement fails and throws an ArrayIndexOutOfBoundsException.
  3. Everything succeeds and the try block exits normally.
The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.

The following finally block for the writeList method cleans up and then closes the PrintWriter.

finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
In the writeList example, you could provide for cleanup without the intervention of a finally block. For example, you could put the code to close the PrintWriter at the end of the try block and again within the exception handler for ArrayIndexOutOfBoundsException, as follows.
try {

out.close(); //Don't do this; it duplicates code.

} catch (FileNotFoundException e) {
out.close(); //Don't do this; it duplicates code.
System.err.println("Caught: FileNotFoundException: "
+ e.getMessage());
throw new RuntimeException(e);

} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());

}
However, this duplicates code, thus making the code difficult to read and error-prone should you modify it later. For example, if you add code that can throw a new type of exception to the try block, you have to remember to close the PrintWriter within the new exception handler.

Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.

Sunday, March 29, 2009

The catch Blocks

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.

The following are two exception handlers for the writeList method — one for two types of checked exceptions that can be thrown within the try statement.

try {

} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: "
+ e.getMessage());
throw new SampleException(e);

} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
}
Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing.

The first handler, in addition to printing a message, throws a user-defined exception. (Throwing exceptions is covered in detail later in this chapter in the How to Throw Exceptions section.) In this example, when the FileNotFoundException is caught it causes a user-defined exception called SampleException to be thrown. You might want to do this if you want your program to handle an exception in this situation in a specific way.

Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the Chained Exceptions section.

The try Block

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following.
try {
code
}
catch and finally blocks . . .
The segment in the example labeled code contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)

To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.

private Vector vector;
private static final int SIZE = 10;

PrintWriter out = null;

try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = "
+ vector.elementAt(i));
}
}
catch and finally statements . . .
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it; the next section shows you how.

Catching and Handling Exceptions

This section describes how to use the three exception handler components — the try, catch, and finally blocks — to write an exception handler. The last part of this section walks through an example and analyzes what occurs during various scenarios.

The following example defines and implements a class named ListOfNumbers. When constructed, ListOfNumbers creates a Vector that contains 10 Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList, which writes the list of numbers into a text file called OutFile.txt. This example uses output classes defined in java.io, which are covered in Basic I/O.

//Note: This class won't compile by design!
import java.io.*;
import java.util.Vector;

public class ListOfNumbers {

private Vector vector;
private static final int SIZE = 10;

public ListOfNumbers () {
vector = new Vector(SIZE);
for (int i = 0; i < SIZE; i++) {
vector.addElement(new Integer(i));
}
}

public void writeList() {
PrintWriter out = new PrintWriter(
new FileWriter("OutFile.txt"));

for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " +
vector.elementAt(i));
}

out.close();
}
}
The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an IOException. The second boldface line is a call to the Vector class's elementAt method, which throws an ArrayIndexOutOfBoundsException if the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by the Vector).

If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor. However, it does not display an error message about the exception thrown by elementAt. The reason is that the exception thrown by the constructor, IOException, is a checked exception, and the one thrown by the elementAt method, ArrayIndexOutOfBoundsException, is an unchecked exception.

Now that you're familiar with the ListOfNumbers class and where the exceptions can be thrown within it, you're ready to write exception handlers to catch and handle those exceptions.

The Catch or Specify Requirement

Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following: Code that fails to honor the Catch or Specify Requirement will not compile.

Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement.

The Three Kinds of Exceptions

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.

Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.

Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.

Errors and runtime exceptions are collectively known as unchecked exceptions.

Bypassing Catch or Specify

Some programmers consider the Catch or Specify Requirement a serious flaw in the exception mechanism and bypass it by using unchecked exceptions in place of checked exceptions. In general, this is not recommended. The section Unchecked Exceptions — The Controversy talks about when it is appropriate to use unchecked exceptions.

What Is an Exception?

The term exception is shorthand for the phrase "exceptional event."

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).

The call stack showing three method calls, where the first method called has the exception handler.

The call stack.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

The call stack showing three method calls, where the first method called has the exception handler.

Searching the call stack for the exception handler.

Using exceptions to manage errors has some advantages over traditional error-management techniques. You can learn more in the Advantages of Exceptions section.

Thursday, March 26, 2009

Sun Microsystems Hosts CommunityOne Open Source Developer Conference for World's Technology Communities

Unveils Open Cloud Platform and Previews the Sun Cloud – Public Cloud for Developers Students and Startups
CommunityOne Open Source Developer Conference

NEW YORK--(BUSINESS WIRE)--In his opening keynote at the annual CommunityOne open source developer conference, David Douglas, senior vice president of Cloud Computing and chief sustainability officer at Sun Microsystems, Inc. (NASDAQ:JAVA), will discuss Sun's overall commitment to open source, building communities and will showcase the company's newly announced Open Cloud Platform. Sun will also preview plans to launch the Sun Cloud, its first public cloud service targeted at developers, student and startups. As part of its commitment to building communities, Sun will release a set of Open APIs, announce broad partner support for its cloud platform and demonstrate innovative features of the Sun Cloud.

Douglas' keynote will include a series of interactive interviews with community leaders from Eucalyptus, RightScale and Zmanda who will discuss opportunities that are created by the innovations of Sun's cloud platform. One of the demonstrations to be featured is an extension for Star Office(TM) and OpenOffice.org(TM). It will enable millions of users to easily save to and open documents from the cloud. In addition, Eucalyptus is expected to announce their open source cloud APIs supporting Sun's Cloud. The developers also intend to integrate Eucalyptus APIs in the next version of Ubuntu OS. These APIs will enable developers to easily create applications they can deploy on the Sun Cloud.

CommunityOne, a Sun-sponsored event, is a dynamic and diverse gathering of open source developer communities that includes thousands of developers and members from the Apache Software Foundation, Eclipse, GlassFish(TM), Grails, MySQL(TM), NetBeans(TM), ODF Alliance, OpenID, OpenOffice.org, OpenSolaris(TM), Python, Ruby and many others. Now in its second year, the CommunityOne gatherings have brought together more than 5,500 attendees, including students from 80 countries to share in the power of communities. Growing in popularity since its launch in San Francisco in 2007, this is the first time CommunityOne will be held on the East Coast.

On Thursday, March 19, expert educators from Sun Learning Services will lead deep technical tutorials on building dynamic Web 2.0 websites, designing robust enterprise applications and harnessing the power of the world's most popular open source database. CommunityOne will also offer hands-on technology demonstrations and an “open space” for open source groups to hold public discussions.

For those unable to attend CommunityOne in person Sun will Webcast the general sessions, as well as the technical sessions. Click here to view (http://sun.com/communityone). The replay of the general session will be available post conference here (http://developers.sun.com/events/communityone).

About Sun Microsystems, Inc.

Sun Microsystems develops the technologies that power the global marketplace. Guided by a singular vision -- "The Network is the Computer" (TM) -- Sun drives network participation through shared innovation, community development and open source leadership. Sun can be found in more than 100 countries and on the Web at http://sun.com.

Sun, Sun Microsystems, the Sun logo, Java, Solaris, OpenSolaris, GlassFish, MySQL, NetBeans and the Network is the Computer are trademarks or registered trademarks of Sun Microsystems, Inc. and its subsidiaries in the United States and other countries.

Big Software Names Coming to Sydney and Brisbane

Senior Architects from Yahoo, Microsoft, IBM and Google will be travelling from all over the world to present at this year’s JAOO conference held in Sydney and Brisbane in early May.
The strong partnership between the Queensland University of Technology, Dave Thomas of Bedarra Research Labs and JAOO Conferences has made the conference return to Australia in 2009, giving Australian software professionals the opportunity to learn from some of the world’s best IT gurus.

JAOO invites international product and application architects, thought leaders and authors with unique industry expertise to give in depth tutorials on current and emerging technologies and practices.

Attendees to JAOO can get ahead of their competitors by learning about the good, the bad and the ugly when it comes to methods, practices and experiences in design and architecture.

This year's program will focus on Web 2.0, Cloud Computing, Enterprise Platforms, Architect and Design and Agile Development Practices.

Australian software professionals will get the chance to interact with Clemens Szyperski, Software Architect Microsoft Olso modeling platform, Joshua J Bloch, Chief Java Architect at Google, Douglas Crockford, JavaScript Architect at Yahoo, Dan North inventor of Behaviour Driven Development and Principal Consultant from ThoughtWorks and Michael T Nygard, author of “Release It!”.

JAOO Australia gives attendees the chance to network with the best software developers from Australia and all over the world without the cost of overseas travel.

"The attendees will have the chance to really pick the brains of the presenters coming to the conference as they stay for the duration of the four day event", which is a unique aspect to JAOO according to Dave Thomas, Chairman Bedarra Research Labs Pty and co-organiser of JAOO Australia.

"A conference of this calibre rarely reaches Australia's shores, it's a once a year opportunity for the best of the best to meet up", said Mr Thomas.

Since 1996, Trifork has organized JAOO and by creating events "for developers, by developers" JAOO is highly regarded by both participants and speakers.

JAOO originally stood for "Java and Object-Oriented" but today JAOO has evolved into a more in-depth conference with a wider set of content than just Java-based technologies.

JAOO will be in Sydney May 5-8 and in Brisbane May 11-14.