如何在Eclipse中嵌入外部工具

原文链接如下:

http://www.ibm.com/developerworks/opensource/tutorials/os-eclipse-tools/

很早的一篇文章,使用的是Eclipse Europa


Integrate external tools and builders in Eclipse


Before you start

About this tutorial

One of the nice things about an IDE is that you can do the majority of your development tasks in one application — hence, integrated. It takes time away from your work to have to switch from your IDE to another program. The more often you have to switch among applications, the more you have, well, just aDE. That's not much of a step above a text editor.

Using launch configurations in Eclipse Europa, you can run external programs from within the development environment. Launch configurations also allow you to save settings for how you want to call an external program, including parameters you would like to send it, environment variables you want to set, or even what to do in the IDE before and after you execute the command. What's more, if you want to run the command each time you build your project — before or after — you can import the launch configuration into a builder and use it in Eclipse.

This tutorial introduces two main scenarios: One uses the venerable Apache Ant build tool that comes with Eclipse; the other is an example of a script that executes from within the IDE.

Objectives

In this tutorial, you learn how to build and use launch configurations. Learn how to launch both Ant build scripts and an example script you can use to view parameter values. Get a detailed look at the types of automatic parameters available to you and learn how to use these parameters with your external tools.

System requirements

To get the most out of this tutorial, all you need is Eclipse Europa. The sample script used later in this tutorial is written both in batch (used for DOS) and Bash shell scripting (used for Linux® and Mac OS X).

And before you get started, add a new Java™ project to an Eclipse workspace and put at least one Java file in the project. It doesn't really matter what the Java class does or contains, but I recommend that it be a project you don't mind using for testing.

To follow the examples, you need Eclipse Europa and one of the operating systems Eclipse supports — Mac OS X, Microsoft® Windows®, or Linux. You also need a Java Runtime Environment (JRE) — JRE for Java V5 is recommended.

Setting up a new Ant configuration

The first example is an Ant build file that does nothing but create a Java Archive (JAR) of some compiled Java code, builds a JAR that contains the Java source, and moves both JARs to a specified location.

Note: Ant is a build tool — somewhat like a Java version of make (that's extremely simplifying things) — that uses a build file in XML format (by default, build.xml). If you haven't used Ant before, you'll still be able to follow along, but you may want to spend some time later reading more about it. (See the sidebar "Learning more about Ant" for more information.)

Why use Ant?

Although you can create JARs and move them to a different location using a batch (.bat) or shell (.sh) script, there are a couple of reasons for doing it with Ant. One reason is because the Ant build is portable — an important consideration if you plan to use the configuration from Eclipse on different operating systems. Because Eclipse runs on Windows, Mac, and Linux, the possibility for portability is certainly higher than IDEs that only run on one operating system.

Learning more about Ant

According to the Ant site, Ant is a build tool that seeks to be a replacement for make. It supports different targets and dependencies between them and has a fairly large list of supported tasks. See Resources for more information about Ant.

The second reason to use Ant for building is that Ant is a common tool — at least in the Java community. Eclipse Europa has a special editor for Ant build files that has syntax highlighting and templates built in, so you get some extra help from the IDE if you're new to build.xml files. And because Ant is fairly widely used, the probability may be higher that other people on your team can understand Ant build.xml files instead of .bat or .sh files, particularly if the files are complex.

Create the JARs

The sample Ant build file is shown in Listing 1. You will use this build file throughout the tutorial to explore the features of Eclipse Europa.

Listing 1. Sample Ant build.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project name="myAntExample" default="publish">
    <description>
        Short description here.
    </description>

    <property name="version" value="1.0.0" />
    <property name="dist.dir" value="dist" />
    <property name="publish.dir" value="published" />
    <property name="classes.jar" value="${dist.dir}/classes.jar" />
    <property name="sources.jar" value="${dist.dir}/sources.jar" />

    <target name="publish" depends="package" description="Published the files">
        <copy file="${classes.jar}" tofile="${publish.dir}/classes-${version}.jar" />
        <copy file="${sources.jar}" tofile="${publish.dir}/sources-${version.jar}" />
    </target>

    <target name="package" depends="prepare" description="Packages the jars">
        <jar destfile="${classes.jar}">
            <fileset dir="${classes.dir}">
                <include name="**/*.class" />
            </fileset>
        </jar>
        <jar destfile="${sources.jar}">
            <fileset dir="${sources.dir}">
                <include name="**/*.java" />
            </fileset>
        </jar>
    </target>

    <target name="prepare">
        <mkdir dir="${dist.dir}" />
        <mkdir dir="${publish.dir}" />
    </target>

</project>

To add a new Ant launch configuration, in Eclipse, choose Run > External Tools > Open External Tools Dialog to access the External Tools window, shown in Figure 1. In the left pane, click Ant Build, then click New to create a new configuration. The Main configuration tab is highlighted and enabled, and Eclipse adds a default name for the configuration.

Figure 1. External Tools window
External Tools window
Main configuration tab

The Main configuration tab contains some of the basic information about the Ant launch configuration, including the name of the Ant build file and any arguments you'd like to pass to it. Figure 2 shows the Main tab in Eclipse.

Figure 2. Main configuration tab
Main configuration tab

Set up the build file

You can type the name of the build file, but to eliminate mistakes, I've found it much easier to use click Browse Workspace or Browse File System (see Figure 2) to find the file and select it. The build file shown in Listing 1 was put into the root of the new project, so use Browse Workspace to find the file. A listing of the projects in the workspace appears from which you can select the location of the file.

When you are done browsing and have selected your build file, click OK. The value that is now in the Buildfile box looks like this:${workspace_loc:/exampleAntBuilder/build.xml}.

By updating only the Buildfile value, you can click Apply or Run, save the configuration, and use it. If you don't want to do anything more complicated than run a single target, you're done. However, you can supply more information to the Ant build process to further customize the launch configuration.

Pass in custom arguments

From the Main configuration tab, you can send arguments in the Ant configuration, which is just one way of sending in values Ant can use to build your project differently. For example, in Listing 1, the build.xml file includes several properties defined using the <property> tag. However, instead of defining these properties in the build file, you could pass them in.

One reason for passing in custom parameters is that it allows you to use the same build file in different projects, even if they have directory and file names that differ. This could be a better alternative than using the same copy of an Ant build script, but tweaking it for each project.

Ant takes overridden properties given to it in the form -D<property name>=<value>, so if you want to see verbose output and override the name of the dist.dir variable, which is where the JARs reside, you would pass in -v -Ddist.dir=out. This would set the name of the directory to out. Click Apply, then click Run if you want to run it right away.

Note: The Ant build configuration is also available from the toolbar.

In addition to supplying static strings of data, you can click Variables on the Main tab to automatically insert variables that can be passed to Ant. The available variables are covered in Table 1, but to quickly test supplying a version, use the built-in variable called ${string_prompt}, which prompts you for a value. The Arguments value on the Main tab is now -v -Ddist.dir=out -Dversion=${string_prompt}.

When you're finished inserting the variable, click Apply, then click Run to run the Ant launch configuration. You will be prompted for a value, as shown in Figure 3.

Figure 3. Prompt for string input
Prompt for string input
Table 1. Variables for launch configurations
Variable Description
build_files If automatic building is turned on, this variable includes the absolute paths of the files that triggered the build. It support parameters to narrow the choices, such as f for files only.
build_project This is the absolute path of the project currently being built.
build_type This variable represents the type of build being executed (incremental, full, auto, or none). The value isnone if you try to use this variable when your launch configuration is not a builder.
container_loc This is the absolute name of the current resource's container, which is the folder or directory.
container_name This is the name of the container in which the current resource resides.
container_path This variable represents the path of the container relative to the workspace.
eclipse_home This is the location in which Eclipse is installed.
env_var This variable inputs the value of the given environment variable, where the name of the variable can be supplied as an argument to the variable.
file_prompt When Eclipse launches the program, it displays a file selector. The name of the file you select when prompted is put into the value of the variable.
folder_prompt This variable is the same as the file prompt, but is limited to folders.
java_extensions_regex This is a regex-matching registered Java-like file extensions.
java_type_name This variable is the fully qualified Java type name of the primary type in the selected resource.
project_loc This is the absolute path of the project on the file system.
project_name This is the name of the project.
project_path This is the path of the current project relative to the workspace.
resource_loc This variable represents the absolute path of the current resource on the file system.
resource_name This is the name of the resource.
resource_path This is the path of the current resource relative to the workspace.
selected_text This is the value of the text that is selected, if any.
string_prompt If used, Eclipse prompts you for a string value. Whatever you type in the prompt is substituted into the variable.
system This is the value of an Eclipse system variable (ARCH, ECLIPSE_HOME, NL, OS, WS).
system_path This variable is the absolute path of a tool — supplied as an argument — in the file system.
system_property This is the value of a system property from the Eclipse runtime, where the name of the property is an argument to the variable.
target.arch This variable represents the target processor architecture (for example, x86 for Intel® processors).
target.nl This is the target locale (for example, en_US or fr_FR).
target.os This is the target operating system (for example, macosx).
target.ws This variable represents the target windowing system (for example, Carbon for Mac).
target_home This is the target home, which is the same as the Eclipse home.
workspace_loc This is the absolute path of the workspace on the file system.
Other useful arguments

Along with sending in overridden values for properties, other useful arguments to send into the Ant configuration are those that allow you to adjust logging. For example, using -logfile <filename> allows you to log the output to a file. The -q-v, and -d parameters allow you to tailor the level of output to quiet, verbose, and debug, respectively.

Refreshing and defining what to build

Up to this point, you've been running the Ant build and refreshing the workspace in Eclipse Europa by choosing File > Refresh or clicking Refreshin Project Explorer. This isn't difficult, but it is a hassle and can throw you for a loop sometimes if you look at Project Explorer and expect the new JARs to be listed in the folders.

Define what Eclipse should refresh

You can have Eclipse automatically refresh all or parts of the workspace when the build configuration is complete. On the Refresh tab of the External Tools window, shown in Figure 4, select the Refresh resources upon completion checkbox.

Figure 4. Refresh tab
Refresh tab

Eclipse now enables the rest of the options on the tab, which allow you to customize exactly what is being refreshed.

The entire workspace
When selected, Eclipse refreshes every resource in the workspace. If you have a large workspace, you may not want to select this checkbox for performance reasons if you don't absolutely need it.
The selected resource
For the example Ant build in this tutorial, this refresh wouldn't be very effective. The selected resource could often be the build file.
The project containing the selected resource
This option would effectively refresh the project containing the build file (if the build file were selected), but would not be useful if a resource in another project were selected, instead.
The folder containing the selected resource
The same applies here for the Ant build, but this option could be useful with other launch configurations.
Specific resources
This allows you to select specific resources to be refreshed. For this example, select this option, then click  Specify Resources. Select the out, published, and dist directories.

Finally, you can choose to refresh folders inside folders by selecting the Recursively include sub-folders checkbox.

Define targets and classpaths

The sample Ant build file in Listing 1 is simple, having only a few targets. Some Ant files can become very large, though, and have many targets. And there are some times you'd like to execute only one or two targets.

On the Targets tab (see Figure 5) of the External Tools window, you can select which targets to execute. When you first set up the Ant launch configuration, Eclipse chose the default target, but you can change it to whichever target you like. To see this in action, clear the default publishtarget, then select the package target only. Now run the Ant configuration, and you will notice in the console output that the publish target is not executed.

Figure 5. Select targets for execution
Select targets for execution

The build file in Listing 1 contains simple tasks within the three targets. All of them —<jar><move>, and <mkdir>— come with Ant by default. But you may decide to use external tools that support Ant. A few such tools are listed in Resources.

Ant needs to have a reference to the classes of these extra tools. If you've used Ant outside the context of Eclipse, you may have simply copied the JARs from the external tools into the Ant directories. I don't recommend this practice, particularly with the distribution of Ant that comes with Eclipse. Instead, you can specify the classpath of the external tools or Ant tasks on the Classpath tab.

Up
Moves the selected entry up the list, placing it before the entries below it.
Down
Moves the selected entry down the list, placing it after the entries above it.
Remove
Completely removes the selected entry from the classpath list.
Add JARs
Limits you to selecting JARs from inside your workspace.
Add External JARs
Eclipse opens a file browser window appropriate for your operating system that looks outside your workspace for a JAR to add.
Add Folders
Adds an entire folder to be used in the classpath.
Add Variable
Adds a new custom variable.
Restore Default Entries
Restores the classpath settings to their original values.
Ant Home
Allows you to change the Ant implementation.

On the Classpath tab, shown in Figure 6, you can also switch the Ant home directory. I used this in earlier versions of Eclipse when I wanted to use Ant V1.7 instead of V1.6, but because Eclipse Europa comes with Ant V1.7, I have not changed the Ant home. However, you may have a need to change the Ant home so it executes a version of Ant that doesn't come bundled with Eclipse. To change the Ant home, click Ant Home on theClasspath tab, select the location of the version of Ant you want to use and click OK. You can always go back to the default by clicking Restore Default Entries.

Figure 6. Classpath tab
Classpath tab

Set properties and environment variables

Environment variables are useful if you want to be able to pass arguments to your Ant build, but don't want to pass in arguments to the build file. Environment variables can also be used by other types of executable processes, like the scripts covered in "The main script configuration," later in this tutorial. The Environment tab, shown in Figure 7, provides the ability to set and use environment variables.

Figure 7. Environment tab
Environment tab

To use an existing environment variable, you can add it by clicking Select to see a list of environment variables that Eclipse knows about. You can change the values of these variables by clicking Edit after adding them.

To add a new environment variable, click New on the Environment tab. After typing the name of the variable and its value, click OK to add the variable to the list. If you need to change it later, click Edit to change the name or value.

When you're editing the environment variables, you can insert the Eclipse variables into the value, just like the arguments in "Pass in custom arguments."

Setting up an example script

The example script used for this tutorial is shown in Listing 2 (Windows batch file) and Listing 3 (Bash shell). The script is a simple example, intended to show that you can add any executable in the launch configuration. The script does nothing more than print the variables sent to it, which is a handy script to have to be able to see what types of values are inserted into the Eclipse variables. (See Downloads).

Listing 2. Example batch file
@time /t
@echo "%*"
Listing 3. Example Bash shell script
#!/bin/sh
echo `date`
echo "$@"

The main script configuration

The Main tab for the program launcher configuration does not look much different from the Main tab in the Ant launch configuration. The only real differences are the names given for the input fields (Working Directory rather than Base Directory) and that you can't use an input handler for the program launch configuration.

Put the executable script in your home directory and reference the script by using the ${env_var} variable with the HOME argument. Eclipse substitutes the location of your home folder into the name of the program.

To see what the values of the variables are when Eclipse sends them, add some of them into the Arguments area. It's best if you label them so you know what you're looking at in the output.

Listing 4. Values of variables Eclipse sends
"container_loc:${container_loc}" "container_name:${container_name}"
"container_path:${container_path}"

When you're done, click Apply, then click Run to run the program. In this case, the script outputs to the console, so the Console view displays the output of the command. The output of running the program with this example is shown below.

Listing 5. Output from running program
"container_loc:C:\Documents and Settings\nagood\workspace\exampleAntBuilder"
container_name:exampleAntBuilder "container_path:\exampleAntBuilder"

Automatically displaying console output

The console may not be automatically displayed when you run the external tools. Whether Eclipse automatically displays the console when something writes to it is a configurable setting in Europa. To change it, find the Console preference page underRun/Debug, and select the Show when program writes to standard out and Show when program writes to standard error checkboxes. You can have them print in different colors, such as red for standard error. To find the preference page even faster, pressCtrl+3, then type Console.

Although this is a simple script, you can have many programs configured to run within Eclipse. In one project I was on, we used a program called HTML Tidy (see Resources) to format and clean up our HTML files and convert them to Extensible HTML (XHTML) V1.0 Strict. Also, I've added the configuration for other editing applications in the rare cases a plug-in wasn't available to easily edit a particular file type.

Share the launch configuration

By default, the launch configuration is stored locally. You can change this value by selecting theShared file option on the Common tab of the External Tools window, shown in Figure 8. You must select a directory in which to save the file. Eclipse automatically names the file for you with the convention <configuration name>.launch. One of the benefits of saving the launch configuration in the project is that you can share the project in a team setting, and other people can launch the configuration you set up. However, this accessibility forces you to pay closer attention to using variables because all paths and program locations must be common between your computer and the other people with whom you share the configuration.

Figure 8. Common tab
Common tab

Using the launch configuration in building

You can configure Eclipse to build your project for you automatically, whenever something in the workspace changes. In Java projects, this build process consists of compiling your Java code with the standard Java project builder. Other project types sometimes have their own builders that run when a resource in the workspace changes or when you instantiate the build manually.

After setting up external tools in launch configurations, you can import these same launch configurations as a builder, which means that whenever Eclipse runs the build process, it also automatically executes the program set up in your launch configuration.

Import the builder

To run your launch configuration whenever Eclipse builds your project, you must import the launch configuration as a builder in the project's properties. To import the builder, open the properties for your project, as shown in Figure 9, then click Builders in the left pane.

Figure 9. Available builders on the project property page
Available builders

Click Import, and Eclipse displays the Import launch configuration window (see Figure 10) with the list of launch configurations that you have set up. For the example in this tutorial, select your configuration from the list, then click OK.

Figure 10. Importing a launch configuration
Importing launch configuration

Click OK again to close the project properties page. Now when you build your project, Eclipse also executes your launch configuration. To change the properties of the builder after importing it, select it from the list of builders and click Edit. An extra tab is displayed that wasn't in the launch configuration window: the Build Options tab, which is shown below.

Figure 11. Build Options tab
Build Options

Specify the build order

Editing configurations after importing

After you import your launch configuration into Eclipse as a builder, when you make changes to the launch configuration, they don't necessarily update into the builder configuration — almost as if Eclipse takes a snapshot of your launch configuration and uses that as the builder. Be careful that when you modify your original launch configuration, you aren't taking it for granted that the builder is being modified at the same time.

Sometimes it's possible to have an Ant build script or an external program that generates source code for you, formats it, or refines it. One example of a tool that generates source code is XDoclet (see Resources), a tool that uses annotations in a Javadoc-like format to generate code. In this case, you probably want the launch configuration to take place before the standard Java builder runs so you can compile the newly created source code along with the rest of the application.

To customize the order in which builders execute, open the project's properties, then clickBuilders, just like you would if you imported a new builder. By using the Up and Downbuttons, you can change the order in which the builders run. (Figure 12 shows an example after moving the new custom builder up.) Eclipse starts at the top and goes down the list. You may want to edit the builder properties (using the Edit button) and force a refresh of the workspace upon completion of the builder. You may also want to clear the Launch in background checkbox on the Build Options tab to make sure Eclipse waits for the builder to finish executing before moving on.

Figure 12. After moving the builder up
After moving the builder up

Troubleshooting

Fortunately, the standard error and standard output when written to the console usually provide the information you need to determine what went wrong during a launch configuration. If they don't give you any information, consider using one of the two scripts supplied with this tutorial to print the values of the arguments to the Console view. I've found that most of my errors came from incorrect variables used for arguments.

Summary

Integrating external tools into Eclipse allows you to do even more from within Eclipse. Using the extensive collection of variables available, you can pass values dynamically into the external tools as arguments or environment variables, allowing the tools to be aware of files you have selected, text you have selected, or the location of your workspace.

When you import the launch configurations as builders in Eclipse, the external tools run automatically whenever Eclipse builds your project. If that's too often, you can customize the settings to only execute during manual builds or even after or before you clean a project.

When plug-ins aren't available that provide tighter integration with Eclipse, integrating external tools is the next best thing.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值