BUY THIS BOOK
Add to Cart

Print Book $44.95


Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £31.95

What is this?

Looking to Reprint or License this content?


Eclipse
Eclipse

By Steve Holzner
Book Price: $44.95 USD
£31.95 GBP
PDF Price: $35.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Essential Eclipse
If you're reading this book, you're most likely a Java programmer, and you know how finicky Java can be at times. Missed import statements, forgotten variable declarations, omitted semicolons, garbled syntax, typos—all these problems will cause the Java command-line compiler, javac, to cough in your face and display pages of annoying error messages. The error messages tell you that javac knows what the error is, so why doesn't it just fix the problem and let you get on developing?
Because javac can't fix the problem; it isn't an editor. That makes long streams of errors scrolling off the page an all-too-common experience for Java developers, and leaves them with the feeling that Java is too prickly about what can go wrong. To change all that, you can use an integrated development environment (IDE), which will not only catch errors before you try to compile, but also suggest solutions. Java is badly in need of a good IDE, and a number of candidates are available, but the premiere Java IDE these days is the one this book is all about: Eclipse. You can see Eclipse in action in Figure 1-1.
Figure 1-1: Eclipse
Although Eclipse can act as an IDE for many different languages—IDEs are available from C/C++ to Cobol—its great popularity is as a Java IDE, and it comes with Java support built-in. Eclipse refers to itself as a universal tool platform, capable of handling IDEs for many different languages, but the Java IDE that comes with Eclipse is going to be our main focus, as it is for the great majority of Eclipse users.
The whole Eclipse magic is that it will take the rough edges off Java development in the way you've always imagined. The errors that would cause javac to stumble are usually handled before you even try to compile, and if there is an issue, Eclipse will suggest solutions. All you have to do is point and click—no need for serious head-scratching. If you're like most Java developers, you're going to find yourself thinking,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Eclipse and Java
Although Eclipse can act as an IDE for many different languages—IDEs are available from C/C++ to Cobol—its great popularity is as a Java IDE, and it comes with Java support built-in. Eclipse refers to itself as a universal tool platform, capable of handling IDEs for many different languages, but the Java IDE that comes with Eclipse is going to be our main focus, as it is for the great majority of Eclipse users.
The whole Eclipse magic is that it will take the rough edges off Java development in the way you've always imagined. The errors that would cause javac to stumble are usually handled before you even try to compile, and if there is an issue, Eclipse will suggest solutions. All you have to do is point and click—no need for serious head-scratching. If you're like most Java developers, you're going to find yourself thinking, This is great!
Eclipse is free for the downloading, like a number of other Java IDEs, but Eclipse has a serious advantage behind it: the power of IBM, which reportedly spent $40 million in the development of the IDE. The first version, Version 1.0, appeared in November 2001 and gradually became popular (although—as with any developer tool—there was a great deal of discussion of its faults).
In time, Eclipse has changed and improved, and the current version, 2.1.1, is getting much praise. In fact, it's become so popular that when Version 2.1 first appeared, the servers at http://www.eclipse.org were so busy that it was almost impossible to download a copy for the first few days.
Eclipse was created by IBM in a massive effort that has left Java programmers the winners. It's now an open source project, still largely under IBM's development, but part of a software consortium named eclipse.org. You can see the consortium's page, http://www.eclipse.org, in Figure 1-2.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Eclipse
How do you get and install Eclipse? Eclipse is free for the downloading—all you have to do is navigate to http://www.eclipse.org/downloads and select one of the download mirrors available on that page. When you do, you'll be presented with a list of the available downloads, which are of these types:
Release builds
The Eclipse team releases these versions for general use. Usually when you download Eclipse, you'll use one of the release versions. These builds have been thoroughly tested, and the chance of coming across serious bugs is minimal. This is a version of Eclipse comparable to the version that other companies would sell—if Eclipse were for sale.
Stable builds
These are comparable to beta versions. A stable build is a step along the way toward a release version. The Eclipse team considers this build to be relatively stable, but there may be problems. This is where you'll find the new features that are upcoming in Eclipse.
Integration builds
These builds are made up of components that have been fairly well tested, but their operation with other components may still have some issues. If things work out OK and the integration build proves itself, it may be elevated to a stable version.
Nightly builds
These are the most experimental of all publicly available Eclipse builds. They're created nightly by the Eclipse team, and there's really no guarantee that things will work well. Some experience with these builds indicates that they can actually have substantial problems.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Eclipse
So what is Eclipse itself? Most people think of Eclipse as a Java IDE, and when you download Eclipse, you get the Java IDE (this is the Java Development Toolkit, the JDT) and the Plug-in Development Environment (the PDE) with it. If you only want to develop Java, it's easy to think of Eclipse as a Java IDE because that's the main tool you'll be using.
Eclipse itself, however, is a universal tool platform. The JDT is really an addition to Eclipse—it's a plug-in, in fact. Eclipse itself is really the Eclipse platform, which provides support for tools beyond just the Java set you get on download. These tools are implemented as plug-ins, so the platform itself only needs to be a relatively small software package.
The platform provides the support the plug-ins need to run; if you want to develop Java, you use the JDT plug-in that comes with Eclipse; if you want to develop in other languages, you'll need to get other plug-ins, such as the CDT, which lets you develop C/C++ code. Installing a plug-in is easy, as we're going to see—all you have to do is drop it into the Eclipse plugins directory and restart Eclipse. Eclipse does some checking on each plug-in when it starts, but the plug-ins are not loaded until they're needed in order to save processing time and memory space.
It's also important to realize that although Eclipse is written in Java, it's intended to be language-neutral. To develop in any programming language, all you need is the corresponding plug-in. In fact, Eclipse is also intended to be spoken-language neutral, too—you can easily change the language that Eclipse uses. To change languages, you can use the same plug-in mechanism that supports plug-ins, except that languages are supported with what are called plug-in fragments. OTI has a language pack available that supports a number of languages—Japanese, Korean, German, French, Italian, Portuguese, Spanish, even traditional and simplified Chinese.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Views and Perspectives
When you're working with the workbench, you'll see a number of different internal windows, called views, and the idea is that they give you different "views" into your projects. For example, one view may give you an overview of the Java classes in your project, while another may let you navigate between projects. For example, back in Figure 1-1, you can see the Navigator view at the upper left in Eclipse—this is the view that will display all your projects and let you move from one to another.
Because screen space is always at a premium in GUIs, views are often stacked, one on top of another, and you select the one you want to see using tabs that appear on the edge of the stacked views.
If you ever want to reopen a view you've closed by mistake, select Window Show View, and select the view you want from the menu that appears.
The editor is one special type of window that usually appears in the center of the workbench. When you open up documents, code, or resources, they'll appear in an editor. Eclipse automatically selects the correct type of editor for the item you're opening: the Java editor for a Java source code file, a GUI you're developing using a plug-in with the editor supplied by the plug-in, and so on. You can even open Microsoft Word documents in the Editor (Eclipse displays an MS Word window in the editor space using Windows Object Linking and Embedding, OLE). In Figure 1-1, the space normally reserved for editors is showing the Eclipse Welcome text.
The editor window is where you do most of the work when developing your code; for example, it's where you enter and edit your code. As we're going to see, the JDT has an editor that is lavish with built-in details, such as syntax checking, code highlighting, and much more. You might have several editors open at once, in which case they'll be stacked with tabs showing at the top of the stack, and you can pick out the one you want by clicking the corresponding tab (or with the Window
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Eclipse
You use the Eclipse Java Development Tools (JDT), a series of six seamlessly integrated plug-ins, for Java development in Eclipse. Even if you've written Java for years, you're about to have a whole new experience, one that makes Java development so smooth that when you understand how to use the JDT, you'll wonder what took people so long to make this a reality.
Eclipse is all about code development, and the only way to really understand what's going on is by creating code, so we're going to start by using the JDT to create and run the amazingly useful application you see in Example 1-1. This Java application just displays the message "No worries." on the console.
Example 1-1. The Ch01_01.java example
public class Ch01_01
{
    public static void main(String[] args)
    {
        System.out.println("No worries.");
    }
}
How can you create this application using Eclipse, and how is Eclipse going to make your job easier? The answers are coming up right now. In Eclipse, all Java code must be inside a Java project, so the first step is to create a Java project.
To invoke the Java perspective, and enter the code for our first example, Ch01_01.java, start Eclipse and select the Window Open Perspective Java menu item to open the Java perspective using the JDT, as you see in Figure 1-6. This is the perspective you'll use over and over as you start relying on Eclipse for Java development.
Figure 1-6: The Eclipse Java perspective
It's worth getting to know the Java perspective before we start using it. At the top are the standard menu bars and toolbars, populated with new items for the Java perspective, which we'll become familiar with in the coming pages.
The left pane holds the Package Explorer and Hierarchy views, and you use the tabs at the bottom of this pane to flip between these views. The Package Explorer view gives you an overview of the package you're working on and lets you navigate through Java projects, selecting what files you want to open in the editor. The Hierarchy view lets you examine type hierarchies—you select an item in a code editor, right-click it, and select the Open Type Hierarchy context menu item. When you do, the hierarchy view will display the hierarchy of that item, giving you a clickable inheritance tree for the item, including all members. That can be a big help if you're trying to figure out the syntax of methods you want to override or which methods are available.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Quick Fix
Quick Fix lets the JDT suggest ways of fixing simple errors, and that's one of the things that Java should have had a long, long time ago. For example, say you change the Ch01_01 code to display the "No worries." message along with today's date:
public class Ch01_01 {
    public static void main(String[] args) {
        outString = "No Worries on ";
        Calendar rightNow = Calendar.getInstance( );
        System.out.println(outString + rightNow.getTime( ));
    }
}
You can probably spot a few errors here. The variable outString is not declared, which makes the first and last lines of code in main invalid, and the Calendar class has not been imported, making the middle line of code invalid. If you were using javac, you'd have to quit editing and run javac to catch those errors. But the second you enter these lines into Eclipse, they'll be flagged as errors with wavy red underlines, as you see in Figure 1-16.
Figure 1-16: Quick Fix indicators
Eclipse doesn't let you down by just showing you the errors—it also suggests solutions. Note the yellow light bulb and red X icons in the bar to the left of the code editor, which is called the marker bar. These icons tell you that Quick Fix is available for all the errors. Note also the hollow red rectangles in the bar on the right of the code editor view, called the overview ruler. These hollow red rectangles indicate statements that Quick Fix can fix—solid red rectangles flag compiler errors—and you can use these icons to navigate to problems to fix.
If you let the mouse cursor hover over the first light bulb icon in the marker bar, you'll see a tool tip appear with the description of the error ("outString cannot be resolved"), as in Figure 1-17.
Figure 1-17: Using Quick Fix
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Word About Project Management
As you create more projects like Ch01_01, you'll find Eclipse getting more and more crowded, since all your projects are displayed in the Java perspective's Package Explorer view, as well as the Navigator view (recall that the Navigator view is there to let you navigate between projects). If you have 30 projects, there will be 30 entries there. There are various ways to deal with this clutter (such as creating working sets, as we'll see in Chapter 2), but we'll take a look at the simplest one here.
To remove a project from the Package Explorer and Navigator views, you can simply delete it. This does not necessarily delete the actual files used for the project, and, whenever you want, you can add the project back to these views. For example, to remove the Ch01_01 project, just right-click its icon and select the Delete item. Eclipse will display the Confirm Project Delete dialog box, as you see in Figure 1-20.
Figure 1-20: Deleting a project
In this case, make sure that the "Do not delete contents" radio button is selected and click Yes to remove the project from Eclipse. The project will disappear from the Package Explorer and Navigator views. Clicking the other radio button will make Eclipse delete all the files and their contents in the project, so don't do that if you want to use the project again later.
When you want to work with the project again, you just import it. To do that, right-click the Package Explorer or Navigator and select the Import context menu item, or select the File Import menu item. This opens the Import dialog; select the "Existing Project into Workspace" item and click Next. In the next pane, click the Browse button, select the Ch01_01 folder, and click OK, giving you results like those shown in Figure 1-21.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Java Development
This chapter is where we get down to the business of developing Java using Eclipse. We're going to take a look at using Eclipse for Java development as well as project management, going from the basics to the fairly serious. Nearly everything in this chapter is essential knowledge for the Java developer using Eclipse, so let's jump in.
If there's anything that takes more time than it seems to be worth in Java, it's creating code from scratch. While the logic inside a method, interface, or class is unique, the modifiers of a method, the imports for a class, and the syntax involved with new packages is the same over and over again. This often results in a lot of repetitive typing, wasted time, and in many cases, annoying little typo-related bugs. Eclipse can help with all this and more.
Eclipse—through code assist—makes it easy to create new methods. As an example, we're going to create and call a new method named printer, which displays the message "No worries.", as you can see in Example 2-1.
Example 2-1. The Ch02_01.java example
public class Ch02_01
{
    public static void main(String[] args)
    {
        printer( );
    }

    private static void printer( )
    {
        System.out.println("No worries.");
    }
}
How do you create new methods? Start Eclipse now and create a new project named Ch02_01. Then create a new Java class named Ch02_01, making it part of the org.eclipsebook.ch02 package. Leave the checkbox for the creation of a stub for the main method checked when you create this new class. This gives you the code:
public class Ch02_01 {

        public static void main(String[] args) {
        }
}
You could simply type in the printer method, of course, but Eclipse can also be of assistance here. Move the cursor below the body of the main method and type private to make this new method a private method, and then type Ctrl+Space to open code assist, as you see in Figure 2-1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing Java Code
If there's anything that takes more time than it seems to be worth in Java, it's creating code from scratch. While the logic inside a method, interface, or class is unique, the modifiers of a method, the imports for a class, and the syntax involved with new packages is the same over and over again. This often results in a lot of repetitive typing, wasted time, and in many cases, annoying little typo-related bugs. Eclipse can help with all this and more.
Eclipse—through code assist—makes it easy to create new methods. As an example, we're going to create and call a new method named printer, which displays the message "No worries.", as you can see in Example 2-1.
Example 2-1. The Ch02_01.java example
public class Ch02_01
{
    public static void main(String[] args)
    {
        printer( );
    }

    private static void printer( )
    {
        System.out.println("No worries.");
    }
}
How do you create new methods? Start Eclipse now and create a new project named Ch02_01. Then create a new Java class named Ch02_01, making it part of the org.eclipsebook.ch02 package. Leave the checkbox for the creation of a stub for the main method checked when you create this new class. This gives you the code:
public class Ch02_01 {

        public static void main(String[] args) {
        }
}
You could simply type in the printer method, of course, but Eclipse can also be of assistance here. Move the cursor below the body of the main method and type private to make this new method a private method, and then type Ctrl+Space to open code assist, as you see in Figure 2-1.
Figure 2-1: Creating a private method
Code assist lets you select the type of private method you want to create—
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building and Running Code
How do you create the Java .class files that are the end result of developing a project? You use the items in the Project menu. The main menu item here is the Project Build Project menu item. This item will compile the source code files in your project and leave the resulting .class files in the same folder as the source code files by default. For example, if you are working with the Ch02_03 project and select Project Build Project, the .class files for this project will appear in the directory workspace/Ch02_03/org/eclipsebook/Ch02 (recall that the classes in this project are in the org.eclipsebook.Ch02 package, which the directory structure reflects). Once created, these .class files are ready for use and distribution.
It often makes sense to store all your project's source code in a folder named src and the binary output in a folder named bin. If you want to set things up this way when you create a new project, open the New Java Project dialog as usual, and, in the second pane, click the Source tab followed by the Add Folder button. Doing so opens the Source Folder Selection dialog; click the Create New Folder button and give the new folder the name src. Then click OK twice. Eclipse will recognize that you're creating a source code folder and automatically ask if you want to create a bin folder for the binary output, as you see in Figure 2-10.
Figure 2-10: Creating source and bin folders
Configuring a project this way automatically stores your source code in the folder named src and the binary output in a folder named bin (bin will not appear in the Package Explorer because it doesn't contain any source code).
Say that you're writing a Java servlet (for more details on servlets, see Chapter 9), shown in Example 2-4.
Example 2-4. The Ch02_04.java example
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Javadoc
Eclipse also makes it easy to develop Javadoc documentation, the standard Java documentation that accompanies Java programs. You'll notice that in the code it generates, Eclipse inserts some text for Javadoc, as you see in Ch02_05.java:
package org.eclipsebook.ch02;

/**
 * @author Steven Holzner
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
.
.
.
If you want to enter your own Javadoc, code assist helps you here, too; for example, if you enter @param and invoke code assist with Ctrl+Space, code assist will list the parameters a method takes. Typing @exception and using code assist will list the exceptions a method throws, and so on. Typing @ in a comment and pausing will make code assist display the Javadoc possibilities, like @author, @deprecated, and so on.
To generate Javadoc from your code, select the Project Generate Javadoc item, opening the Generate Javadoc dialog, which lets you select the project for which you want to create Javadocs. To browse a project's Javadocs, select the Navigate Open External Javadoc menu item. For example, you can see the generated Javadoc for the Ch02_05 project in Figure 2-19.
Figure 2-19: Browsing Javadoc
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Refactoring
One of the major advantages of using a good Java IDE like Eclipse is that it can let you rename and move Java elements around, and it will update all references to those items throughout your code automatically.
For example, take a look at the code in Example 2-6. Here, we've used code assist to create a new method to display a simple message, but we forgot to change the default name for the method that code assist supplied.
Example 2-6. The Ch02_06.java example
package org.eclipse.ch02;

/**
 * @author Steven Holzner
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class Ch0206 {

        public static void main(String[] args) {
                name( );
        }
        
        public static void name( ) {
                System.out.println("No worries.");
        }
}
This default name for the new method, name, is called in the main method, and it could be called from other locations in your code as well. How can you change the name of this method and automatically update all calls to it? Select name in the editor and then select the Refactor Rename menu item, opening the Rename Method dialog you see in Figure 2-20.
Figure 2-20: Refactoring a method
Enter the new name for the method, printer in this case, and click OK. When you do, the name of this method and all references to it will be updated throughout your code, including all code in the project, as you see here:
package org.eclipse.ch02;

/**
 * @author Steven Holzner
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class Ch0206 {

        public static void main(String[] args) {
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Some Essential Skills
There are some additional skills that are good to know about. For example, if you highlight an item in the JDT editor, right-click it, and select Open Declaration, the declaration of that item will open. This is great for tracking down where and how methods and fields were created. Several of those are detailed in this section and all are worth adding to your Eclipse toolbox.
Another menu item in the JDT editor's context menu is the Open Type Hierarchy; when you select an item in the editor and select this menu item, that item's type hierarchy appears in the Java perspective's hierarchy view, as you see at left in Figure 2-24.
Figure 2-24: The hierarchy view
This view acts like an object browser. It lets you explore a type's Java complete hierarchy, and double-clicking an item in this view opens its definition in the editor. That's useful if, for example, you want to see all the members of the System.out class—just highlight System.out in your code and open its hierarchy. You can also open this view by selecting an item in the editor and selecting the Navigate Open Type Hierarchy item.
The hierarchy view is not dissimilar from the outline view, which you see at right in Figure 2-24. However, the outline view is designed to show an automatic hierarchy of your code rather than the hierarchy of items you specifically select. As you work in the JDT editor, the outline view is updated automatically to show the hierarchy of the current type you're working with.
There's even another entire perspective dedicated to letting you browse through projects in a Java-oriented way: the Java Browsing perspective. To open this perspective, select Window
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customizing the Development Environment
Our last topic in this chapter is all about customizing your development environment. Eclipse is easy to customize, starting from the most basic—you can move any view, editor, or toolbar around simply by dragging it.
If you don't like to work in an environment where things can move around with mouse movements by mistake, you can lock the toolbars with the Window Lock the Toolbars menu item. And if a perspective gets all scrambled by inadvertent mouse movements, use Window Reset Perspective to restore things.
You can also customize how Eclipse will generate code for you. For example, the default code generation style doesn't place opening curly braces on their own lines:
            public void printer( ) {
        System.out.println("No worries.");
}
However, your programming style might be more like this, where each curly brace does get its own line:
public void printer( ) 
{
        System.out.println("No worries.");
}
You can customize this with the Windows Preferences item, opening the Preferences dialog you see in Figure 2-29. Select the Java Code Formatter item, which lets you specify options for code generation. Here, select the "Insert a new line before an opening brace" item, as you see in the figure; the sample code below will change to match.
Figure 2-29: Customizing code generation
Here's another way you can customize how Eclipse generates code. When you create a new file, this kind of comment is inserted automatically:
/*
 * Created on Oct 17, 2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
As this text says, you can change this with the Window
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Testing and Debugging
Testing and debugging are a way of life in Java development. Eclipse comes with built-in facilities for testing your code using its JUnit framework and some truly exceptional debugging capabilities.
JUnit is an open source testing framework that comes with Eclipse. You can create JUnit-based classes in the same project as other classes, and use this JUnit code to test the other classes in your project. Using JUnit in this way, you can construct a set of standard tests for everyone working on an application, and if they change the application's code, all they'll need is a few clicks to verify that the application still passes the standard set of tests.
JUnit is designed to test your code, and it's made up of assertion methods that can test various conditions. Here they are:
assertEquals(a, b)
Tests if a is equal to b (a and b are either primitive values or must have an equals method for comparison purposes)
assertFalse(a)
Tests if a is false, where a is a Boolean value
assertNotNull(a)
Tests if a is not null, where a is either an object or null
assertNotSame(a, b)
Tests if a and b both do not refer to the identical object
assertNull(a)
Tests if a is null, where a is either an object or
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Testing with JUnit
JUnit is an open source testing framework that comes with Eclipse. You can create JUnit-based classes in the same project as other classes, and use this JUnit code to test the other classes in your project. Using JUnit in this way, you can construct a set of standard tests for everyone working on an application, and if they change the application's code, all they'll need is a few clicks to verify that the application still passes the standard set of tests.
JUnit is designed to test your code, and it's made up of assertion methods that can test various conditions. Here they are:
assertEquals(a, b)
Tests if a is equal to b (a and b are either primitive values or must have an equals method for comparison purposes)
assertFalse(a)
Tests if a is false, where a is a Boolean value
assertNotNull(a)
Tests if a is not null, where a is either an object or null
assertNotSame(a, b)
Tests if a and b both do not refer to the identical object
assertNull(a)
Tests if a is null, where a is either an object or null
assertSame(a, b)
Tests if a and b both refer to the identical object
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Debugging
Eclipse's debugging capabilities are impressive, even for a fully featured IDE. To get started, we'll take a look at an example with a logic error that we can then track down. After the example, we'll look at more advanced debugging topics, like setting debug launch configurations, using hot code replacement, suspending a running program that isn't terminating (such as when you have an infinite loop), and more. Being able to interactively debug your code is something you should expect to find in a good IDE—and it's a brilliant improvement over trying to debug your code using only the tools that come with Java—but Eclipse has gone above and beyond the call.
Our buggy program appears in Example 3-3. The debugger in Eclipse is especially good at working with stack frames, which hold the local variable set for method calls. To get a handle on debugging, we're going to create an example that creates several layers of stack frames: a factorial example (e.g., the factorial of 6, denoted 6!, is equal to 6 * 5 * 4 * 3 * 2 * 1 = 720), which calls itself recursively in order to calculate factorials.
Example 3-3. The Ch03_02.java example
package org.eclipsebook.ch03;

public class Ch03_02 {

        public static void main(String[] args) {
                System.out.println(factorial(6));
        }
        
        public static int factorial(int value) {
                if(value == 0){
                        return value;
                }
                else {
                        return value * factorial(value - 1);                        
                }
        }
}
You calculate factorials like this: n! = n * (n - 1) * (n - 2) ... * 1. In our example, to calculate factorial(n), the factorial method multiplies n by factorial(n - 1), calling itself to determine the factorial of (n-1). To determine
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Working in Teams
We've been programming solo with Eclipse up to this point, but it's also designed to be used in team environments, and it supports Concurrent Versions System (CVS) to make teamwork go smoothly. Eclipse can be used by any Java developer, and developers often work in teams. This chapter is all about teamwork using Eclipse and CVS.
When you work in teams, you have to coordinate. That means discussing and planning, of course, but even with the best of intentions, you can still end up with conflicts. You may have made some brilliant changes to the code—only to find them all wiped out by mistake when another programmer uploads his new version of a file.
Source control stops those kinds of problems by controlling access to code and by maintaining a history of the changes that have been made so things aren't destroyed unintentionally. Storing a history of your code is very powerful—not only can you compare a new (buggy) file against an older one, you can also revert to a previous version in case things have gone awry.
Source control also gives you the ability to coordinate the simultaneous development of several different versions of your software—for example, you might want to work on both a release version and a new beta version. You can do that using branches, as we're going to see in this chapter.
CVS is an open source project; it started life as a set of Unix shell scripts in 1986 and came into its own with dedicated software in 1989. Support for CVS is available on many operating systems today—Unix, Linux, Windows, and others. For the full CVS story, take a look at http://www.cvshome.org.
The idea behind CVS, as with any repository software, is to manage and record changes to source code. In fact, there are many types of repository software available, and some are more powerful than CVS, but CVS is in the most widespread use (perhaps because you can get it for free).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Source Control Works
When you work in teams, you have to coordinate. That means discussing and planning, of course, but even with the best of intentions, you can still end up with conflicts. You may have made some brilliant changes to the code—only to find them all wiped out by mistake when another programmer uploads his new version of a file.
Source control stops those kinds of problems by controlling access to code and by maintaining a history of the changes that have been made so things aren't destroyed unintentionally. Storing a history of your code is very powerful—not only can you compare a new (buggy) file against an older one, you can also revert to a previous version in case things have gone awry.
Source control also gives you the ability to coordinate the simultaneous development of several different versions of your software—for example, you might want to work on both a release version and a new beta version. You can do that using branches, as we're going to see in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding CVS
CVS is an open source project; it started life as a set of Unix shell scripts in 1986 and came into its own with dedicated software in 1989. Support for CVS is available on many operating systems today—Unix, Linux, Windows, and others. For the full CVS story, take a look at http://www.cvshome.org.
The idea behind CVS, as with any repository software, is to manage and record changes to source code. In fact, there are many types of repository software available, and some are more powerful than CVS, but CVS is in the most widespread use (perhaps because you can get it for free).
In CVS, a module is the basic equivalent of an Eclipse project. Modules are represented by directories in CVS. Standard projects correspond to physical modules, while logical or virtual modules are collections of related resources.
The files you share are stored in the CVS repository. When you retrieve a file from the repository, you check the file out. After you've modified the file, you commit the changes to check it back in and send those changes to the repository. If you want to refresh your own copy of a file, you update it from the repository.
In general, there are two models for source code repositories:
Pessimistic locking
Only one developer can check out a particular file at once—after the file is checked out, the file is locked. It's possible for someone else to check out read-only copies of the file, but not to change it. Access is sequential.
Optimistic locking
Developers can check out and modify files freely. When you commit changed files, the repository software merges your changes automatically. If it can't do that by itself, it'll notify you that you have to resolve the issue yourself. Access is random.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Finding a CVS Server
To work with CVS, you need access to a CVS server. If you have access to a CVS server already, you're all set. Otherwise, take a look at the overview that follows.
Most Linux and Unix installations already come with a CVS server built-in. To test if you have a working CVS installation, type cvs --help at the prompt; you should see a list of help items. If you can't find a CVS server, you can download what you need from http://www.cvshome.org.
In Windows, the story is a little more complex. There are a variety of CVS servers for Windows, such as CVSNT, available for free from http://www.cvsnt.org. To install CVSNT, just download the executable file and run it.
You'll need to create a repository for your source code using the CVS server. In Linux and Unix, you do that with the command cvs -d path init, where path gives the location of the directory you want to use as the repository (the permissions and ownership for path should be set so all members of your development team can access it).
With CVSNT, you click the Repositories tab in the CVSNT control panel, click the Add button, enter the path of the new repository directory, such as c:\repository, and click OK.
In Linux and Unix, you use one of two possible options to reach CVS: SSH (secure shell) or pserver. We'll use pserver here, but you can use either protocol; just make sure that the correct protocol is running on your machine.
In Windows, CVSNT runs as a Windows service, which means it is accessible to Eclipse as soon as you run it. You can start it from the Start menu by selecting the Service control panel item from whatever program group you've added it to, which opens the CVSNT control panel. Click the Start button in both the CVS Service and CVS Lock Service boxes, which will make CVSNT display the message "Running" in both those boxes, as you see in Figure 4-1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding a Project to the CVS Repository
We'll start using CVS by seeing how to add a new project, Ch04_01, to the CVS repository. After this project is in the CVS repository, anyone with access to the repository can check it out and work on it. You can see this sample project in Example 4-1; this sample code does nothing more than display the word "Hello".
Example 4-1. A sample project
package org.eclipsebook.ch04;

public class Ch04_01 {

        public static void main(String[] args) {
                System.out.println("Hello");
        }
}
After you've created a project, how do you add it to the CVS repository? You first have to let Eclipse know about the repository, so select Window Open Perspective Other, and select the CVS Repository Exploring perspective (after you do this the first time, Eclipse will add this perspective to the Window Open Perspective, and will add a shortcut for this perspective to the other perspective shortcuts at the extreme left in Eclipse). When this perspective opens, right-click the blank CVS repositories view that appears at left and select New Repository Location, opening the Add CVS Repository dialog you see in Figure 4-2.
Figure 4-2: Connecting a CVS repository to Eclipse
Here, enter the name of the CVS server (usually the name of the computer that hosts the server), the repository path, the username and password, and specify the connection type (here, we'll be using the pserver protocol). Then click Finish to add the new repository to the CVS Repositories view, as you see in Figure 4-3.
Figure 4-3: A new repository in the CVS Repositories view
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Building Eclipse Projects Using Ant
Eclipse is great for building your code. But for more advanced project development, there's still something missing. For example, what if you want not only to compile several files at once, but also to copy files over to other build directories, create JAR files and Javadoc, create new directories, delete previous builds, and create deployment packages all at once?
You can do that with a build tool like Apache's Ant (http://ant.apache.org /). Ant is a Java-based build tool that can perform all these tasks and much more. You can download Ant and run it on the command line, automating your build tasks to not only compile code, but to create JAR files, move and create classes, delete and make directories, and a great deal more.
The good news here is that Ant comes built into Eclipse, ready to use. Ant is the premier build tool for Java development, and we'll get an idea why in this chapter. As your projects become more and more elaborate, Ant can automate dozens of tasks that you'd otherwise need to perform manually. When you have things set up to run with Ant, all you've got to do is point and click to perform a complete build without having to take dozens of separate steps, which can save many steps omitted in error over the development process.
The fact that Ant comes built into Eclipse means that it's easier to use for us than for all those developers who use it on the command line. To see how this works, we'll start with a quick example.
To use Ant from Eclipse, create a new project, Ch05_01, and add a new class to it, Ch05_01. In this class's main method, we'll just display the message "No worries.", as you see in Example 5-1.
Example 5-1. A sample project
package org.eclipsebook.ch05;

public class Ch05_01 {

        public static void main(String[] args) {
                System.out.println("No worries.");
        }
}
To work with Ant, we'll need an Ant build file, which is named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Ant
Content preview·<