10 Running and Debugging Java Application Projects

This chapter describes how you can use the running and debugging features in NetBeans to create and perfect your projects.

This chapter contains the following sections:

10.1 About Running Java Application Projects

As you are developing your application, you can run the application in the IDE to test the application's behavior. When you run a project in the IDE, the IDE runs the application from the files in the project's build/classes folder.

Typically, the project that contains the program's main class is set as the main project. You can then run the entire application with the Run Main Project command (F6). You can also run any executable class by choosing Run > Run File > Run my_class (Shift+F6). Alternatively, you can run any project that has a main class by right-clicking its project node in the Projects window and choosing Run Project.

When you run the project the IDE displays any compilation errors and output in the Output window.

Note:

If Compile on Save is enabled for a project, the Run Project command operates on class files that have been created when you have saved those files. The Ant build script is not used. If you have defined custom steps in the build script, those steps are not followed. If you would like the full build process to occur when you use Run Project, Debug Project, and Profile Project, disable Compile on Save. The Compile on Save feature can be toggled from the Run category in the Project Properties window.

10.1.1 Running Standard Projects

For standard projects, the IDE uses settings that you specify in project's Project Properties dialog box. You can set the project's main class, runtime arguments, VM arguments, and working directory.

To run the application outside of the IDE, you must first use the Clean and Build command so that the project's JAR file is built or updated. For standard projects that have a main class specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib folder. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf file. This simplifies running the application outside the IDE. For more information, see Section 8.9, "Preparing a JAR File for Deployment Outside the IDE."

10.1.2 Running Free-form Projects

For free-form projects, the IDE uses an existing Ant script to run your class. You can write a target that executes the currently selected file in the IDE and map it to the Run File command.

10.2 Working with Project Execution

Once you have created and built your project, you must perform the following operations to configure the run process for your project:

  • Set your project as the main project in the IDE.

  • Set the project's main class.

  • Modify the runtime classpath, as needed, to include any special libraries, project dependencies, or specific JAR files.

  • Specify any runtime and Java VM arguments the project requires.

When you have the runtime configurations set, you can either run individual project files or run the entire the project. Each of these operations is discussed in more detail in the following sections.

10.3 Running an Application

With standard projects, you typically have one project that contains the application main class and several projects containing class libraries. You can run the project or run any individual project that contains an executable class. For information on setting the main class, see Section 10.6, "Setting the Main Class and Runtime Arguments."

To run a project:

  1. Select the project that you want to run in the Projects window.

  2. Choose Run > Run Project (F6).

When running an application, be aware of the following considerations:

  • If you have the Compile on Save option selected in the Compiling section of the Project Properties window, the project is run directly from the build/classes directory of your project. If Compile on Save is not selected, the project is run using the project's build script.

  • If you run a project for which you have not specified a main class, the IDE prompts you for the main class. You can change this setting in the Run panel of the project's Project Properties dialog box. Each project can contain only one main class. For information on setting the classpath, see Section 10.5, "Setting the Runtime Classpath."

  • If you are running a project often, you can set a project as the main project by choosing Run > Set Main Project from the main menu and selecting the project in the submenu or by right-clicking the project node in the Projects window and choosing Set as Main Project.

  • You can select multiple projects in the Projects window and run them at once by choosing Run > Run (number of selected projects) Projects (F6) from the main IDE's menu.

10.4 Running a Single File

You might have a file in your project that you want to test before running the entire project. You can run a single file in the IDE and see any warning or error messages that might occur during the run in the Output window.

To run a single file:

  1. Select the file in the Source Editor or Projects window.

  2. Choose Run > Run File > Run my_class.

    The IDE initiates execution of the selected file.

Note:

In free-form projects, this command is disabled by default. To enable this function, you have to write an Ant target for running the file in the IDE and map it to the IDE's Run Class command. This command is not available for EJB projects.

10.4.1 Writing a Target to Run/Debug/Test a Single File

The IDE does not generate targets for the Run File, Debug File, Test File, and Debug Test for File commands, but you can create your own targets and map them to the following predefined actions:

  • run.single - Run selected file

  • debug.single - Debug selected file

  • test.single - Run the JUnit test for selected file

  • debug.test.single - Debug the JUnit test for selected file

Each of these actions contains a context element that gets a reference to the currently selected files and stores it in a property of your choice. You use this property in your Ant targets to specify which files to process.

10.4.1.1 Running the Selected File

Let's demonstrate how this works when you run a class. A typical target for running a project looks something like the following:

<target name="run2" depends="...">
        <java fork="true" classname="MyMainClass" classpath="MyRunClasspath" />
</target>

The target runs the file specified by classname. To run the currently selected file in the IDE, you need to modify the above target to something like the following:

<target name="run-selected-file" depends="compile" description="Run Single File">
      <fail unless="runclass">Must set property 'classname'</fail>
      <java classname="${runclass}">
         <classpath refid="run.classpath"/>
      </java>
</target>

10.4.1.2 Getting a Reference to the Currently Selected File in the IDE

Once you have an Ant target for running the selected file, you have to get a reference to that file in the IDE and store it in a property. For example, the run-selected-file target above looks for the currently selected file in the runclass property.

You store this reference in the same place where you map the build target (run-selected-file) to the IDE action. First we will look at how to do this and then we will explain it in detail:

 <action name="run.single">
        <target>run-single</target>
        <context>
            <property>runclass</property>
            <folder>${src.dir}</folder>
            <pattern>\.java$</pattern>
            <format>java-name</format>
            <arity>
                <one-file-only/>
            </arity>
        </context>
    </action>

The runclass property is a newly defined property that holds the file that you want to run and is referenced by the java task.

Now let's take a look at the following lines to see how it works.

<action name="run.single">
      <target>run-selected-file</target>
      <context>
        <property>runclass</property>
  • <action name="run.single"> maps the Run File command and the F9 shortcut to the run-selected-file target.

  • <context> sets the context on which the Ant target is executed. In this case, it is the name of file that you want to run.

  • runclass is the name of the property that holds the context. You can choose any unique name for this property. This property must be set by the IDE before the target can be run.

  • <arity> specifies that runclass can hold only one file. If you want the property to be able to hold more than one file (such as for the Compile File target), you can use the following, where the comma (,) is the separator between file names:

    <arity>
              <separated-files>,</separated-files>
    </arity>
    
  • <format>java-name</format> specifies that the IDE should pass the relative file name to the target but delimited by periods (.) and without an extension. Other formatting options include the following:

    • relative-path - specifies that the IDE should pass the relative file name to the target

    • relative-path-noext - Same as relative-path, but the file's extension is removed

    • absolute-path - Absolute file name

    • absolute-path-noext - Same as absolute-path, but the file's extension is removed

  • <folder>${src.dir}</folder> specifies that the file name should be relative to the src.dir directory and that this action is only enabled for the src.dir directory.

    Note:

    The IDE does not define the ${src.dir} property for you. You have to define the property or import the .properties file that the Ant is using in project.xml. See Using Properties in the project.xml File for more information.
  • <pattern>\.java$</pattern> is the regular expression which the file names must pass. You use <pattern> to limit which files can be passed to the Ant target. In this case, you want the target be executed only with files that end in .java.

10.4.1.3 Debugging the Selected File

The process is basically the same for writing targets to debug and run a single file. The debug-selected-files target looks something like this:

 <target name="debug-selected-files" depends="compile" if="netbeans.home" description="Debug a Single File">
       <fail unless="classname">Must set property 'classname'</fail>
       <nbjpdastart name="${classname}" addressproperty="jpda.address" transport="dt_socket">
          <classpath refid="run.classpath"/>
          <!-- Optional - If source roots are properly declared in project, should
          work without setting source path.
          <sourcepath refid="debug.sourcepath"/> -->
       </nbjpdastart>
       <java classname="${classname}" fork="true">
          <jvmarg value="-Xdebug"/>
          <jvmarg value="-Xnoagent"/>
          <jvmarg value="-Djava.compiler=none"/>
          <jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
          <classpath refid="run.classpath"/>
       </java>
 </target>
  • This is basically the same as the debug target. Instead of passing the program main class to java, you pass the classname property, which is set by the IDE to the currently selected file.

Then you map the debug-selected-files target to the debug.single action:

<action name="debug.single">
      <target>debug-selected-files</target>
      <context>
         <property>classname</property>
         <folder>${src.dir}</folder>
         <pattern>\.java$</pattern>
         <format>java-name</format>
         <arity>
            <one-file-only/>
         </arity>
      </context>
</action>
  • <property> now stores the context in the classname property.

  • Since java can only take single file, you set <arity> to <one-file-only>.

  • Setting <format> to java-name and making it relative to src.dir creates a fully-qualified class name for the currently selected file.

    Note:

    The IDE does not define the ${src.dir} property for you. You have to define the property or import the .properties file that the Ant is using in project.xml. See Section 6.2.4.9.1, "Using Properties in the project.xml File" for more information.

10.5 Setting the Runtime Classpath

By default, the runtime classpath of each standard project contains the project's compiled classes and everything in the project's compilation classpath. For information on viewing the compilation classpath, see Section 6.2.3.1, "Managing the Classpath."

If your project uses special libraries dynamically at runtime through an indirect interface or reflection (like JDBC drivers or JAXP implementations), you have to add these libraries to the runtime classpath.

Note:

For standard projects that have a main class is specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib folder. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf file. This simplifies running the application outside the IDE. For more information, see Section 8.9, "Preparing a JAR File for Deployment Outside the IDE."

You also have to adjust your runtime classpath if the runtime dependencies between your projects do not match the compilation dependencies between the projects. For example, imagine that project A compiles against project B, and project B compiles against project C, but project A does not compile against project C. This means that project A only has project B on its runtime classpath. If project A requires both project B and project C during execution, you have to add project C to project A's runtime classpath.

To set the runtime classpath:

  1. Right-click the project node in the Projects window and choose Properties.

  2. In the Project Properties dialog box, select the Libraries node in the Categories pane.

  3. Select the Run tab in the dialog's right pane.

  4. Add the necessary elements to the project's runtime classpath by clicking the appropriate button. You can add any of the following:

    • Project. The build output, source files, and Javadoc files of another IDE project. Adding a project to the classpath makes it dependent on the present project. Whenever you clean or build the project, all of its dependent projects are also cleaned or built.

    • Library. A collection of binary files, source files, and Javadoc files.

    • JAR/Folder. A JAR file or folder somewhere on your system.

  5. (Optional) Click Move Up and Move Down to alter to the classpath priority.

Note:

In free-form projects, your Ant script handles the classpath for all of your source folders. The classpath settings for free-form projects only tell the IDE what classes to make available for code completion and refactoring. For more information, see Section 6.2.4.5, "Declaring the Classpath in a Free-Form Project."

10.6 Setting the Main Class and Runtime Arguments

By default, the IDE specifies neither a main class nor runtime arguments. The runtime classpath of each standard project contains the project's compiled classes and everything in the project's compilation classpath.

Indicate which class in your project is the entry point for the application by setting a main class.

To set the main class and runtime arguments:

  1. Right-click the project node in the Projects window and choose Project Properties.

  2. Select the Run node in the Categories pane of the dialog box.

  3. Type the fully qualified name of the main class in the Main Class field (for example, org.myCompany.myLib.MyLibClass). The main class must exist in the project or in one of the JAR files or libraries on the project's runtime classpath.

    Note:

    If you use the Browse button to choose the project main class, the file chooser only displays classes in your project source directory. If you want to specify a class in one the libraries on the classpath, you have to type the fully-qualified name of the class in the Main Class field.
  4. Enter any runtime arguments you require in the Arguments field.

    The IDE sets the project's main class and stores any newly-added arguments.

Note:

For standard projects that have a main class is specified, the IDE automatically copies any JAR files on the project's classpath to the dist/lib folder. The IDE also adds each of the JAR files to the Class-Path element in the application JAR's manifest.mf file. This simplifies running the application outside the IDE. For more information, see Section 8.9, "Preparing a JAR File for Deployment Outside the IDE."

If you use the Browse button to choose the project main class, the file chooser only shows classes in your project source directory. If you want to specify a class in one the libraries on the classpath, you have to type the fully-qualified name of the class in the Main Class field.

To change project runtime options:

  1. Right-click the project node in the Projects window and choose Properties.

  2. In the Project Properties dialog box, select the Libraries node in the Categories pane.

  3. Click the Run tab in the right pane of the dialog box.

    Note:

    To access settings for the main class, program arguments, the working directory for program execution and VM options, you have to select the Run node.

10.7 Setting JVM Arguments

JVM arguments and system properties can be set through the project's properties file through the IDE.

To set JVM arguments:

  1. Right-click the project node in the Projects window and choose Project Properties.

  2. Select the Run node in the Categories pane of the dialog box.

  3. Type a space-separated list of JVM arguments in the VM Options field.

To set system properties:

  • Specify the system property and its value in the VM Options field:

    -Dname=value
    

10.8 Debugging Applications

Debugging is the process of examining your application for errors. The process of debugging is accomplished by setting breakpoints and watches in your code and running it in the debugger. This enables you to execute your code one line at a time and examine the state of your application to discover any problems.

When you start a debugging session the Debugging window opens in the left pane of the IDE. Additional debugger windows also appear automatically at the bottom of your screen.

You can also debug applications that are running on a remote machine by attaching the debugger to the application process.

You can customize the Java debugger by choosing Tools > Options and clicking the Java Debugger tab. From this tab you can perform the following:

  • set custom breakpoint commands

  • set step filters to specify language constructs that are filtered while stepping

  • create and edit variable formatters

  • modify options for the Visual Debugger

10.8.1 Debugging Free-form Projects

Similar to commands for compiling and running, debugging commands rely on various information, such as the location of your sources, the location of the compiled classes and other items on the classpath, and name of the project's main class (for more information, see Section 10.5, "Setting the Runtime Classpath").

In free-form projects, the IDE does not "know" about any of these things. When you run a command in the IDE (such as Build), the IDE simply calls a target in your build script and lets the script handle the command. Therefore, for debugging to work, you also have to have a build script target for debugging. The IDE provides some custom Ant tasks to work with the debugger and also can generate a basic debug target, which attempts to fill in important details based on other targets in your script.

To set up debugging in a free-form project:

  • Make sure that your classes are compiled with debugging information included. For example, you might accomplish this in the compile target of your build script by including the argument debug="true" in the <javac> task.

  • Set the output of the free-form project. If the output of a free-form project is on the classpath of another project, map the free-form project's source packages to their outputs. This ensures that you can use the debugger to step into the project's sources when you start a debugging session in a project that has a dependency on the free-form project. To declare the output files, right-click the free-form project node and choose Properties. Then click the Output category in the Properties window and specify the output file for each source folder.

  • Confirm that the target JDK is set in your Ant script and the source level is specified in the Project Properties dialog box. When you step into JDK classes, the IDE searches the platforms registered in the Java Platform Manager for a Java platform with a matching source level. If no matching Java platform is found, the IDE opens the source code for the IDE's default platform.

  • Create a target in your build script for debugging and map that target to the IDE's Debug Project command. The IDE can assist you by generating a basic target and mapping, but you might have to modify the target. For more information, see Section 10.8.1.1, "How to Create a Debug Target for a Free-form Java Project."

For information on mapping an Ant target to a debugging command, see Section 6.2.4.6, "Mapping an Ant Target to an IDE Command."

10.8.1.1 How to Create a Debug Target for a Free-form Java Project

To run a free-form project in the IDE's debugger, you have to have a special target in your project's build script. That target needs to be mapped to the IDE's Debug Project command.

If you do not have a debug target written for your project, the IDE offers to generate a basic target for you when you first try to debug the project. You can then inspect the target and customize it for the project's specific requirements.

Note:

When the IDE generates a debug target, it looks for information in the target you have mapped to the Run Project command to determine such things such as the run classpath and the project's main class. If you have a target mapped to the Run Project command, there is a good chance that the generated debug target works without further customization.

To create a debug target for a free-form project:

  1. Set the free-form project as the main project by choosing Run > Set Main Project in the main menu and selecting the project.

  2. Choose Debug > Debug Main Project from the main menu.

  3. Click Generate in the Debug Project dialog box.

    When you click Generate, a target named debug-nb is created in a file named ide-targets.xml. The generated ide-targets.xml file is a build script that imports your main build.xml file, so your debug target can take advantage of targets and properties set by or referenced by your main build script.

    In addition, a mapping for this target is created in the project.xml file so that the target is called whenever you choose the Debug Project command in the IDE. If you write the target from scratch, you must also create this mapping yourself. For more information, see Section 10.8.1.1.2, "Manually Mapping a Target to a Menu Item."

  4. Verify that the generated debug-nb target properly takes into account all of the elements of your project.

    In particular, you might have to modify the <classpath> argument in the target if it does not include all of the items in your run classpath.

After the target is created, you can begin debugging the project.

To debug the project:

  1. Set a breakpoint in your main class by clicking in the left margin of the line where you want to set the breakpoint.

    The line with the breakpoint is highlighted in pink.

  2. Right-click the project's node again and choose Debug Project.

    The target should run and start execution of the program. Progress of the running target is shown in the Output window and the status of the debugger is shown in the status bar at the bottom of the Output window.

10.8.1.1.1 A Typical Free-form Project Debug Target

The generated Ant target does the following:

  • Starts the debugger with the nbjpdastart task.

  • Stores the address at which the debugger listens for the application in the jpda.address property (addressproperty="jpda.address"). You do not have to define the jpda.address property in your Ant script or properties file. It is defined by the IDE.

  • Establishes the runtime classpath. If the IDE is not able to determine your runtime classpath, placeholders are put in the script, which you must fill in yourself.

  • Runs the application in debug mode, passing the jpda.address property as the address at which to connect to the debugger. Setting fork="true" ensures the process is launched in a separate virtual machine.

Note:

You can add any additional JVM arguments or program arguments in the java task as well.

For example, if the IDE is able to guess the runtime classpath, the debug-nb target that the IDE generates in ide-targets.xml might look similar to Example 10-1:

Example 10-1 Defining a Free-form Debug Target

<?xml version="1.0" encoding="UTF-8"?>
    <project basedir=".." name="YourProjectName">
        <import file="../build.xml"/>
        <!-- TODO: edit the following target according to your needs -->
        <!-- (more info: http://www.netbeans.org/kb/articles/freeform-config.html#debugj2se) -->
        <target name="debug-nb" depends="init,compile">
            <nbjpdastart addressproperty="jpda.address" name="NameOfProject" transport="dt_socket">
            <classpath path="ClasspathSpecifiedInYourRunTarget"/>
            </nbjpdastart>
            <java classname="MainClassSpecifiedInRunTarget" classpath="ClasspathSpecifiedInYourRunTarget" fork="true">
               <jvmarg value="-Xdebug"/>
                <jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
            </java>
        </target>
    </project>

If you do not have a run target mapped or the IDE otherwise cannot determine the project's classpath or main class, the generated debug target includes "TODO" placeholders for you to fill in these values as shown in Example 10-2.

Example 10-2 Generated debug target with ”TODO” placeholders

<?xml version="1.0" encoding="UTF-8"?>
    <project basedir=".." name="YourProjectName">
        <!-- TODO: edit the following target according to your needs -->
        <!-- (more info: https://netbeans.org/kb/articles/freeform-config.html) -->
        <target name="debug-nb">
            <path id="cp">
                <!-- TODO configure the runtime classpath for your project here: -->
            </path>
            <nbjpdastart addressproperty="jpda.address" name="NameOfProject" transport="dt_socket">
                <classpath refid="cp"/>
            </nbjpdastart>
            <!-- TODO configure the main class for your project here: -->
            <java classname="some.main.Class" fork="true">
                <classpath refid="cp"/>
                <jvmarg value="-Xdebug"/>
                <jvmarg value="-Xnoagent"/>
                <jvmarg value="-Djava.compiler=none"/>
                <jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
            </java>
        </target>
    </project>

To specify the runtime classpath, insert pathelement elements within the path element and point them to the directories that contain the items in your classpath. For example, you can use the location attribute of pathelement to specify the location of the classpath items relative to your project directory as shown in Example 10-3. The project directory is usually the one that contains the project's build.xml file.

Example 10-3 Specifying location of classpath items relative to a project directory

<path id="cp">
    <pathelement location="libs">
    <pathelement location="build">
</path>
10.8.1.1.2 Manually Mapping a Target to a Menu Item

When you have the IDE generate a target, the IDE automatically provides the mapping between the target and the IDE command's menu item. However, if you have created the target manually, you must also create the mapping manually.

To map the Debug Project command to a target in an external Ant script:

  1. Open the project's project.xml file and add the following to ide-actions:

      <action name="debug">
            <script>path_to_Ant_script</script>
            <target>target_name</target>
            </action> 
    
  2. Add the command to the project node's context menu, by adding the following line to the <context-menu> target:

      <ide-action name="debug"/>
    

    The IDE maps the Debug Project action to the specified target in the project's Ant script. For information on how to map a target to a debugging command, see Section 6.2.4.6, "Mapping an Ant Target to an IDE Command."

10.8.1.1.3 Troubleshooting

If you have successfully created a debug target and started the debugger, but the debugger does not stop at breakpoints, the IDE is probably lacking debugging information or knowledge of where your sources are. For more information, see Section 10.8.1, "Debugging Free-form Projects."

10.8.1.2 How to Create a Debug Target for a Free-form Web Project

In a free-form project, you must set up your own Ant target to run a project in the debugger. However, you can use the IDE to generate a debug target for you. When you do so, the IDE maps the debug target to the Debug Project command. Alternatively, if you have your own debug target, you must map it to the Debug Project command yourself.

To generate a debug target:

  1. Set the project as the main project and choose Debug > Debug Main Project (Ctrl+F5) from the main menu or right-click the project in the Projects window and choose Debug.

    If no target is mapped to the Debug Project command, you are prompted to let the IDE generate an IDE-specific debug target in nbproject/ide-targets.xml.

  2. Click Generate.

    The IDE does the following:

    • Generates a target named debug-nb. The target is generated in the new nbproject/ide-targets.xml file, together with other targets that support it, such as the -load-props, -check-props, -init, and debug-display-browser targets. These targets do the following:

      • Checks whether Ant is running inside the IDE (if="netbeans.home").

      • Starts the debugger with the nbjpdaconnect task.

      • Connects the debugger to the application to be debugged at the specified host (jpda.host) and port number (jpda.address).

      • Opens the IDE's web browser at the URL specified by the client.url property.

      Note:

      These targets are not generated in the IDE. Therefore, you need to change the generated code so that it looks as follows:
      <target name="-load-props">
             <property file="nbproject/project.properties"/>
      </target>
      
      <target name="-check-props">
             <fail unless="session.name"/>
             <fail unless="jpda.host"/>
             <fail unless="jpda.address"/>
             <fail unless="jpda.transport"/>
             <fail unless="web.docbase.dir"/>
             <fail unless="debug.sourcepath"/>
             <fail unless="client.url"/>
      </target>
       
      <target depends="-load-props, -check-props" name="-init"/>
      
      <target depends="-init" name="debug-nb" description="Debug Project">
             <nbjpdaconnect address="${jpda.address}" host="${jpda.host}"
              name="${session.name}" transport="${jpda.transport}">
                  <sourcepath>
                      <path path="${debug.sourcepath}"/>
                  </sourcepath>
             </nbjpdaconnect>
             <antcall target="debug-display-browser"/>
      </target>
      
      <target name="debug-display-browser">
             <nbbrowse url="${client.url}"/>
      </target>
      

      There's no need for you to customize the generated targets. All you have to do is set the properties that the IDE requires to use the targets it generated. For example, you need to tell the IDE where your application's sources are. To do this, you will set properties in the nbproject/debug.properties file that the IDE created for you when it generated the debug-nb target above. Using the -load-props target above, the IDE will load the properties when you run the debug-nb target.

    • Generates and defines debug properties. The properties are defined in the new nbproject/debug.properties file. The properties define the following:

      • The sources that are to be debugged.

      • The server to which the application to be debugged is to be deployed.

      • The port number and address to be used.

      • The client URL.

    • Maps the debug-nb target to the Debug Project command.

  3. In the Files window, go to the nbproject/debug.properties file and edit the debug properties as shown in Example 10-3, if necessary.

    Example 10-4 Adding properties to a new debug.properties file

      jpda.session.name=MyProject
      jpda.host=localhost
     
      # Sun Java System Application Server using shared memory (on Windows)
      # jpda.address=localhost4848
      # jpda.transport=dt_shmem
     
      # Sun Java System Application Server using a socket
      # jpda.address=9009
      # jpda.transport=dt_socket
     
      # Tomcat using shared memory (on Windows)
       jpda.address=tomcat_shared_memory_id
       jpda.transport=dt_shmem
     
      # Tomcat using a socket
      #jpda.address=11555
      #jpda.transport=dt_socket
     
      src.folders=src
      web.docbase.dir=web
     
      # you can change this property to a list of your source folders
      debug.sourcepath=${src.folders}:${web.docbase.dir}
     
      # Client URL for Tomcat
      client.url=http://localhost:8084/MyProject
     
      # Client URL for Sun Java System Application Server
      # client.url=http://localhost:8080
    
    Property Value Notes
    jpda.session.name   The display name given in the Sessions window when you debug the project.
    jpda.host   The host that the application to be debugged uses to connect to the debugger, such as localhost.
    jpda.address The bundled Tomcat Web Server defaults are 11555 for socket connections and tomcat_shared_memory_id for shared memory connections. To set a different address, right-click the Tomcat node in the Services window and choose Properties. In the Properties sheet, change the Debugging Port property (for socket connections) or Name property (for shared memory connections). Then close the Properties sheet. Now stop and restart the Tomcat Web Server, if you had already started it.
    jpda.transport dt_socket (for socket connections) or shmem (for shared memory connections). To set a different transport, right-click the Tomcat node in the Services window and choose Properties. In the Properties sheet, change the Debugging Type. Then close the Properties sheet. Now stop and restart the Tomcat Web Server, if you had already started it.
    web.docbase.dir

    src.folders

    The location of your web root (web.docbase.dir) and Java source files (src.folders). Multiple source roots can be included in the sourcepath by means of the ":" delimiter. Note that the Java source folders must be specified as Source Package Folders in the Java Sources panel of the Project Properties dialog box. (Right click the project, choose Properties, then click Java Sources in the Project Properties dialog box.)
    client.url   The URL that should be opened in the IDE's default browser, such as http://localhost:8084/MyProject.

If you use the IDE to generate the debug target, as described in the previous section, the target is automatically mapped to the Debug Project command. However, if your debug target was not generated by the IDE, you must map it to the Debug Project command manually.

To map a debug target to the Debug Project command:

  1. In the Projects window, right-click the project node and choose Properties.

  2. Click Build and Run in the left panel of the Project Properties dialog box.

  3. Click Add, select your debug target, and type a label, such as "Debug Project."

If you want to map the debug action to a target in a separate Ant script, open the project's project.xml file and add the following to <ide-actions>:

  <action name="debug">
    <script>path_to_Ant_script</script>
    <target>name_of_target</target>
  </action> 

To add the command to the project node's contextual menu, add the following to <context-menu>:

  <ide-action name="debug"/>
10.8.1.2.1 Using the Debug Target

Before you can use your debug target, you need to deploy your application. Therefore, start the server and run deploy the application. Note that the first time that you run the application per session, the Tomcat Web Server asks you for a username and password. The only acceptable username and password is that of a user with a "manager" role. This is defined in the conf/tomcat-users.xml file in the Tomcat Web Server's base directory. To identify the location of this directory, right-click the Tomcat Web Server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to the Tomcat Web Server's base directory.

Once the application is deployed, stop the server and restart it in debug mode. The way this is done depends on the server:

  • Bundled Tomcat Web Server

    Expand the Servers node in the Services window, right-click the Bundled Tomcat node, choose Start/Stop Server, and click Start Server (Debug).

  • External Tomcat Web Server

    Run the catalina jpda start command.

Once the server has started in debug mode, choose Run > Debug Main Project. The application is deployed and is attached to the debugger. The debugger stops at the first breakpoint, after which you can Step into or Step over the code.

To use a debug target in a free-form web project:

  1. Set breakpoints in your source files.

  2. Right-click the project node in the Projects window, choose Properties, click Java Sources in the Project Properties dialog box, and make sure that all the source files you want to debug are listed in the Source Package Folders list.

  3. In the Services window, expand the Servers node, right-click the server instance and choose Start/Stop Server.

  4. Click Start Server (Debug).

  5. Make sure that you have a debug target and that it is mapped to the Debug command, as described in the previous sections.

  6. Choose Debug > Debug Main Project (Ctrl+F5).

For more information debugging features that you can use for web applications in the IDE, see Section 12.12, "Debugging a Web Application."

10.8.1.2.2 Troubleshooting the Debug Target

Even though the IDE does its best to generate a complete debug target for you, with properties that are tailored to your specific environment, you should always analyze and fine tune the debug process. Work through the questions below when you encounter problems while using an Ant debug target from NetBeans IDE:

  • Has the web application been correctly deployed?

    Check that the web application has been deployed:

    1. In the Services window, expand the Servers node, start the server (if not started), expand the server's instance node, and expand the Web Applications node.

    2. If you do not see your application's context (/MyProject, for the application in this document), it has not been correctly deployed.

    3. Deploy the application.

  • Are you behind a firewall?

    Check that your proxy settings are correct. Depending on your proxy type do the following:

    • HTTP Proxy. Choose Tools > Setup Wizard. In the wizard, select the Use HTTP Proxy Server checkbox. Type the proxy host name in the Proxy Server Name field and the port number in the Port field. Click Finish.

    • SOCKS Proxy. You must pass the SOCKS proxy host and proxy port parameters to the JVM software when you start the IDE. On Microsoft Windows machines, use the IDE-HOME/etc/netbeans.conf file to pass the parameters. On UNIX and Linux machines, you can write a wrapper shell script. Go to Help > Help Contents for details.

  • Is the server running in debug mode?

    Check that the server has been started in debug mode:

    1. In the Services window, expand the Servers node and check that the server is running. Note that even if it is running, it may not be running in debug mode.

    2. If it is not running, right-click it, choose Start/Stop Server, and click Start Server (Debug). If it is running, but you are not sure that it is running in debug mode, stop the server and restart it in debug mode.

  • Are the server's port and address set correctly?

    Check that the jpda.address set in debug.properties matches the server's settings:

    1. Right-click the server's node in the Services window and choose Properties.

    2. In the Properties sheet:

      • Check the Debugging Port property (for socket connections). By default, it should be 9009 for the SJS Application Server or 11555 for the Tomcat Web Server.

      • Check the Name property (for shared memory connections). By default, it should be localhost4848 for the SJS Application Server or tomcat_shared_memory_id for the Tomcat Web Server.

      If you change the server's Debugging Port property or Name property, make sure that it matches the related property in the debug.properties file.

    3. Close the Properties sheet and stop and restart the server, if you had already started it.

    Check that the jpda.transport set in debug.properties matches the server's settings:

    1. Right-click the server's node in the Services window and choose Properties.

    2. In the Properties sheet, check the Debugging Type property:

      • dt_socket for socket connections

      • dt_shmem for shared memory (Windows)

      If you change the server's Debugging Type property, make sure that it matches the related property in the debug.properties file.

    3. Close the Properties sheet and stop and restart the server, if you had already started it.

  • Unable to step through your code?

    If you are unable to step from line to line in your code, but only from breakpoint to breakpoint, the IDE has not been able to find your sources. This is because you have not specified your sources correctly.

    • Servlets: Choose Window > Debugging > Sources. The Sources window displays all the Java source folders that are available for debugging. If you want to debug a source folder that is not available in the Sources window, specify it in the Project Properties dialog box:

      • Right-click the project node, choose Properties, click Java Sources.

      • Add the source folders to be debugged to the Source Package Folders table or to the Test Package Folders table.

        Note:

        The target you use for compiling servlets must specify debug="true" when calling the javac task. If a servlet is compiled without debug info, the debugger will not stop on its breakpoints.
    • JSP pages: Make sure that you have defined a context path for the project:

      • Right-click the project node, choose Properties, click Web Sources.

      • Type the context path. For example, type /MyProject in the Context Path field.

        Note:

        If you have set your breakpoints before specifying the context path, you must remove and reset the breakpoints after specifying the context path. In other words, the context path must be set first.

    Also make sure that the sources are correctly specified in the debug.properties file and in the debug-nb target. Note that if your nbproject folder is not housed within the folder that houses your sources folder, you should set the following properties for your src.folder and web.docbase.folders properties:

    • src.folders=${project.dir}/src

    • web.docbase.dir=${project.dir}/web

10.8.2 Debugging GUI Projects

You can use the visual debugger to help you locate and debug the code for visual elements in your Java and JavaFX GUI applications.

10.8.2.1 GUI Snapshots

After you create a project you can start a debugging session, take a GUI snapshot of the application, and then work with the snapshot to locate source code, add listeners to events and view the event log of GUI components.

To take a GUI snapshot:

  1. Click the Debug button in the toolbar to start a debugging session.

    Alternatively, right-click the project node in the Projects window and choose Debug.

    When you start the session, the IDE will launch your application and open the Debugging window.

  2. Choose Debug > Take GUI Snapshot from the main menu.

    When you choose Take GUI Snapshot, the IDE takes a snapshot of the GUI and opens the snapshot in the main window.

10.8.2.2 Working with the Visual Debugger

The GUI snapshot is a visual debugging tool that can help you locate the source code for GUI components. The source code for GUI components can sometimes be difficult to locate and the snapshot provides a way for you to locate the code based on the GUI instead of searching through the code. You can select components in the snapshot and invoke tasks from the context menu to view the source code for the component, show the listeners and set breakpoints on components.

10.8.2.2.1 Locating the Source Code for Components

to use the GUI snapshot to navigate to the lines in the source code where a component is declared and defined, you select a component in the GUI snapshot and use the context menu to invoke various commands.

Note:

you select a component in the GUI snapshot, you can use the context menu to invoke various commands.

To locate the declaration and source code for the component:

  1. In the GUI snapshot, select a component (for example, a button).

    When you select a component in the snapshot, the IDE displays details about the selected component in the Properties window. If the Properties window is not visible you can choose Window > Properties from the main menu to open the window.

    The IDE also displays the location of the component in the form hierarchy in the Navigator window.

  2. Right-click the component in the snapshot and choose Go to Component Declaration from the context menu.

    When you choose Go to Component Declaration, the IDE opens the source file in the editor and moves the cursor to the line in the code where the component is declared.

  3. Right-click the component in the snapshot again and choose Go to Component Source.

    When you choose Go to Component Source, the IDE opens the source file in the editor and moves the cursor to the line in the source code for the component.

To locate the line in the source code where a component is added to its container:

  1. Open the Options window.

  2. Click the Java Debugger tab in the Java category in the Options window.

  3. Select Visual Debugging in the list of categories and select Track locations of component hierarchy changes. Click OK.

  4. Stop your debugging session (if one is running).

    Note:

    After you enable the command in the Options window you will need to restart your debugging session and take a new GUI snapshot before you can use the Go to Hierarchy Addition command.
  5. Start a new debugging session and take a GUI snapshot.

  6. Right-click a component in the GUI snapshot and choose Go to Hierarchy Addition.

    The IDE will open the source code in the editor at the line where the component is added.

10.8.2.2.2 Exploring Component Events

you can use the GUI snapshot and the Events window to explore component events.

To locate component listeners and the events that are triggered by the components:

  1. Right-click a component in the snapshot and choose Show Listeners from the context menu.

    When you choose Show Listeners, the IDE opens the Events window with the expanded Custom Listeners node.

  2. Right-click an item below the Custom Listeners node and choose Go to Component Source in the context menu.

    The source code opens in the editor at the line where the listener is defined.

  3. Select another component in the snapshot.

    Alternatively, you can select a component in the Navigator window.

    When you select another component, the items in the Events window will change automatically to display the listeners for the selected component.

  4. In the Events window, double-click the Event Log node to open the Select Listener window.

    Alternatively, you can right-click the Event Log node and choose Set Logging Events from the context menu.

  5. Select a required listener from the dialog (for example, java.awt.event.KeyListener). Click OK.

  6. In your application, complete an event (for example, type a character in a text field).

    The event is recorded in the events log. (For example, if you expand the Event Log node you can see that each keystroke is now logged). New events appear each time that you complete an event. If you expand an individual event, you can see the properties of that event in the log.

    If you expand the Called From node for an event you can see the stack trace for the event.

10.8.2.3 How to Configure Java Debugger Options

You can configure the options for debugging Java applications in the Options window.

To configure Java debugging options:

  1. Open the Options window by choosing Tools > Options from the main menu. (If you are running on Mac OS X, choose NetBeans > Preferences.)

  2. Select the Java Debugger tab in the Java category of the Options window.

  3. Select a category in the Java Debugger tab to configure the global settings for the behavior of the Java debugger.

  4. Click apply in the Options window to apply the changes.

10.9 Using the Debugger Windows

When you start a debugging session the IDE opens some debugging windows by default. In addition to the main Debugging window in the left pane of the IDE, other debugger windows open as tabs below the editor. You can open any debugger window by choosing Window > Debugging > window-name (for example, Window > Debugging > Breakpoints).

Each debugger window displays a variety of icons to relay information about the object. For example, the Breakpoints window uses a small red square to indicate a breakpoint set on a line. Some windows also include a node expansion control to the left of the icon. Clicking this control expands and collapses the object.

The Debugging window opens in the left pane of the IDE and uses a tree structure to display the threads and calls in the current debugging session. The current thread and call are displayed in bold. You can expand the node for suspended threads to view the call stack.

In the debugger tabs, information is organized into lists. Each list item represents a single object. Each column represents a property of the object. Data displayed in blue underlined text is linked to the source code.

Some elements of lists in the debugger tabs have editable properties, such as the value property of a variable in the Variables window. If you select a property and the property has a white background you can edit the property. A selected property with a gray background cannot be edited.

10.9.1 Customizing a Debugger Window

You can rearrange elements of a debugger window or remove columns to display only the information of interest.

To add or remove a column to a window:

  1. Click Change Column icon (to the right of the column titles) or right-click in the window and choose List Options > Change Visible Columns.

  2. Click the appropriate checkbox to turn the display of information on or off.

  3. Click OK.

To rearrange the columns in a window:

  • Drag the column header to the right or left to place the column in the new location.

To set the sort order of a window:

  • Right-click anywhere in the window and choose List Options > Sort > sort-order.

    For all windows, you can sort the column in ascending or descending order. A triangle is displayed in the column header. The direction in which the triangle is pointing indicates whether the sort order is ascending or descending. Some windows provide additional sort orders.

10.9.2 Choosing Current Context in the Debugger

The current context is the portion of your program on which the debugger is currently focusing. When multiple sessions are running, only one session is current. Within the current session, the thread from which the debugger regained control is the default current thread. Inside the current thread, the most recent call is the default current call.

You can make any session, thread, or call current by right-clicking its node in the appropriate debugger window and choosing Make Current.

10.9.2.1 Debugger Windows and Context

Most debugger windows depend on the current context. When you change the current context, the contents of these windows are updated to reflect the new context.

For example, the Debugging window shows the threads in the current session, while the Call Stack window shows the call stack for the current thread. The Variables window shows the variables that are local to the current call, and the Loaded Classes window shows the classes that have been loaded by the current session. For more information on viewing classes and class instances, see Section 10.9.6, "Viewing Program Information When Debugging."

The exceptions are the Breakpoints and Watches windows. These windows list all breakpoints and watches set in the IDE. While the set of watches is shared by all sessions, an individual watch expression is evaluated and displayed based on the current context. For information on setting breakpoints, Section 10.9.4, "Managing Breakpoints."

For information on debugging threads, see Section 10.9.6.8, "Debugging Threads in the IDE."

For information on examining the call stack for the current thread, see Section 10.9.6.9, "Using the Call Stack."

10.9.2.2 The Source Editor and Context

When a variable is active in the current context, the Source Editor displays the value of the variable when you move the pointer over it. In cases where a program includes different variables with the same name, the Source Editor displays the value based on the current context, and not on the instance of the variable in the source code.

10.9.3 Attaching Source Code to a JAR File

When you add a JAR file or folder of compiled classes to a project's classpath, it is often useful to add the source files for those classes so that you can view their contents when working with them. Attaching source code to a JAR file or compiled classes folder lets the IDE know where to find the source code for those classes. You can then step into the source files when debugging and open the source files with the Go To Source command.

Note:

For code completion to work properly in the IDE, you must either attach a complete set of source files as a folder or add the available source files as a Zip archive.

To attach source code to a JAR file or compiled classes folder:

  1. Choose Tools > Libraries from the main menu.

  2. In the left pane of the Ant Library Manager, select the project library within which the JAR file you want to add the source code to is located.

    Only libraries already registered with the IDE are listed in the Ant Library Manager's Class Libraries list.

  3. If the JAR file or classes folder for which you want to add the source code has not already been added to a registered library, create a new empty library using the New Library button.

  4. In the Classpath tab click Add JAR/Folder and specify the location of the JAR file containing the compiled class files.

    A class library can contain multiple JAR files as well as their Javadoc documentation and source code.

  5. In the Sources tab, click Add JAR/Folder to add the folder or archive file containing the source code.

  6. Click OK to exit the Ant Library Manager.

    The IDE adds the selected JAR files and source code to the specified library and automatically registers the source code in every project that has that JAR file on its classpath.

When you create a Java class library for a single JAR file, you can simply add the JAR file to the project's classpath to make the associated Javadoc and source code available. If your Java library contains multiple JAR files, however, you must add the library itself to the classpath. Adding the library to the classpath also makes it easier to share the project with other developers. For information on setting the classpath, see Section 6.2.3.1, "Managing the Classpath."

You can also associate the sources with a JAR file using the project's Project Properties window. However, doing so creates the association only for that project.

To associate sources with a JAR file through the Project Properties window:

  1. Open the Project Properties dialog box by right-clicking the project node and choosing Properties.

  2. Select the Libraries node in the Categories pane.

  3. Select the JAR with which you want to associate the sources and click Edit.

  4. Specify the sources to be associated.

To attach source code for a Java platform:

  1. Choose Tools > Java Platforms from the main menu.

  2. Select the platform in the left pane of the dialog box.

  3. In the Sources tab, add the folders or archive files containing the source code.

For free-form projects, set the target JDK in your Ant script and specify the source level in the Project Properties dialog box (for more information, see Section 6.8, "Setting the Target JDK"). When you step into JDK classes, the IDE searches the platforms registered in the Java Platform Manager for a Java platform with a matching source level. If no matching Java platform is found, the IDE opens the source code for the IDE's default platform.

10.9.4 Managing Breakpoints

A breakpoint is a flag in the source code that tells the debugger to stop execution of the program. When your program stops on a breakpoint, you can perform actions like examining the value of variables and single-stepping through your program.

The IDE enables you to set several types of breakpoints using the New Breakpoint dialog. You can also set line breakpoints directly in the Source Editor. Breakpoints can be set for the following types of source elements:

  • Class. You can break when the class is loaded into the virtual machine, unloaded from the virtual machine, or both.

  • Exception. You can break whenever a specific exception is caught, whenever a specific exception is not handled in the source code, or whenever any exception is encountered regardless of whether the program handles the error or not.

  • Field. You can stop execution of your program whenever a field in a specific class is accessed (for example, the method was called with the variable as an argument), modified or both.

  • Method. Program execution stops every time the method is entered, exited or both.

  • Thread. You can break program execution whenever a thread starts, stops, or both.

The Source Editor indicates a breakpoint by highlighting the line at which the breakpoint is set in red and placing an annotation in the left margin. The following table describes the debugging annotations:

Table 10-1 Debugging Annotations

Annotation Description

Breakpoint icon

Breakpoint

Disabled Breakpoint icon

Disabled breakpoint

Invalid Breakpoint icon

Invalid breakpoint

Multiple Breakpoint icon

Multiple breakpoints

Field or Method Breakpoint icon

Method or field breakpoint

Disabled Field or Method Breakpoint icon

Disabled method or field breakpoint

Invalid Field or Method Breakpoint icon

Invalid method or field breakpoint

Conditional Breakpoint icon

Conditional breakpoint

Disabled Conditional Breakpoint icon

Disabled conditional breakpoint

Invalid Conditional Breakpoint icon

Invalid conditional breakpoint

Program Counter icon

Program counter

Program Counter and One Breakpoint icon

Program counter and one breakpoint

Program Counter and Multiple Breakpoints icon

Program counter and multiple breakpoints

Callsite icon

The call site or place in the source code from which the current call on the call stack was made

Suspended Threads icon

Suspended threads

Thread Suspended Hitting Breakpoint icon

Thread suspended by hitting a breakpoint


All Java breakpoints are defined globally and, therefore, affect all IDE projects that include the source on which a breakpoint is set. For example, if you set a class breakpoint on com.me.MyClass in one project, the IDE stops execution every time it encounters that class during a debugging session for other projects that include the class.

You can view and organize all IDE breakpoints by choosing Windows > Debugging > Breakpoints (Alt+Shift+5). If you open the Breakpoints window when a debugging session is running, it closes automatically when you end the debugging session. If you open the window when no debugging session is running, it stays open until you close it.

By default, each entry contains a short text description of the breakpoint and a checkbox indicating whether the breakpoint is enabled or disabled. You can enable or disable a breakpoint directly in the Breakpoints window by selecting or deselecting the checkbox.

10.9.4.1 How to Set a Java Breakpoint

All Java breakpoints are defined globally and therefore affect all IDE projects that include the source on which a breakpoint is set. For example, if you set a class breakpoint on com.me.MyClass in one project, the IDE stops execution every time it encounters that class during a debugging session for other projects that include the class.

To set a line, field or method breakpoint in the Source Editor:

  • Click in the left margin next to the line in the source code or put the insertion point in the line and choose Debug > New Breakpoint from the main menu.

A field, method or line breakpoint is created depending on if the line contains a field declaration, method declaration or other code. The corresponding breakpoint annotation is visible in the left margin next to the line of source code.

The IDE tests the validity of set breakpoints when the debugger session is starting or when a debugger session is already running. If a breakpoint is invalid the IDE uses a broken annotation to indicate the invalid breakpoint and displays an error message in the Debugger Console.

To set all other types of breakpoints:

  1. In the Source Editor, select the code element on which you want to set a breakpoint.

    For example, if you want to set a class breakpoint on the class BeanCounter, select the class name in the class declaration.

  2. Choose Debug > New Breakpoint (Ctrl+Shift+F8).

    The New Breakpoint dialog box opens with a suggested breakpoint type and target filled in.

  3. If necessary, adjust the suggested breakpoint type in the Breakpoint Type drop-down list.

  4. Enter the package and class name for which you want to set the breakpoint.

  5. Set any additional options you require in the New Breakpoint dialog and click OK.

    The IDE creates the new breakpoint for the selected source element.

To modify an existing breakpoint:

  1. Choose Window > Debugging > Breakpoints (Alt+Shift+5) to open the Breakpoints window.

  2. Right-click any breakpoint and choose Properties to open the Breakpoint Properties dialog box.

  3. Adjust any settings or actions you require and click OK.

    The IDE updates the breakpoint for the selected source element.

To enable and disable a breakpoint:

  • Right-click the breakpoint in the Breakpoints window and choose Enable or Disable.

You can modify and enable line, field and method breakpoints by right-clicking the breakpoint icon in the left margin of the Source Editor and choosing from the Breakpoint submenu.

When a debugging session is running, use code completion in the New Breakpoint dialog box.

10.9.4.2 How to Set a Conditional Breakpoint

You can set conditions on a breakpoint so that execution only breaks if the condition is true. Set conditions on any breakpoint except thread breakpoints by selecting the Conditions checkbox and entering the condition. For all breakpoints you can specify how often the breakpoint is triggered by selecting the Break When Hit Count checkbox and choosing a criteria from the drop-down list and specifying a numerical value.

Class breakpoints and exception breakpoints enable you to set the following conditions:

  • For class breakpoints, you can exclude classes triggering the breakpoint by selecting the Exclude classes checkbox and specifying the classes to exclude.

  • For exception breakpoints, you can filter the classes triggering the breakpoint by selecting the Filter on Classes Throwing the Exception checkbox and specifying the names of classes to match or exclude.

To set a conditions on a breakpoint:

  1. Create a new breakpoint or open an existing breakpoint's customizer by right-clicking its name in the Breakpoints window and choosing Customize.

  2. Select the Condition checkbox and type the condition in the Condition field. The condition must follow the Java syntax rules. The condition can include anything that can be on the right side of the equal sign (=). The condition can also include variables and methods that are within the current context. The following are exceptions:

    • Imports are ignored. You must use fully qualified names, such as obj instanceof java.lang.String.

    • You cannot access outerclass methods and variables directly. Use this.variableName or this$1.

    • (Optional) Select the Break When Hit Count checkbox and choose a criteria from the drop-down list and specify a numerical value.

    Conditional line breakpoints have a Conditional Breakpoint icon icon in the left margin of the Source Editor.

10.9.4.3 How to Organize Breakpoints Into a Group

The Breakpoints window lists all of the breakpoints defined for all of your IDE projects. If you have numerous breakpoints set in the IDE, it is useful to organize these breakpoints into groups. Once your breakpoints are placed into groups, you can enable, disable, and delete them as a single unit.

To add a breakpoint to a custom group:

  1. Choose Windows > Debugging > Breakpoints (Alt+Shift+5) to open the Breakpoints window.

  2. Right-click the breakpoint and choose Move Into Group and select a custom group from the list.

    Note:

    To create a custom group, right-click the breakpoint and choose Move Into Group > New and type the name of the new group in the dialog box.

To remove a breakpoint from a custom group:

  • In the Breakpoints window, right-click the breakpoint and choose Move Into Group > Default.

Alternatively, you can modify how breakpoints are organized from the Breakpoints window by clicking Breakpoint Groups ( Breakpoints Group icon.) and selecting a grouping strategy from the context window. If you choose Nested you can specify the specific groups and the order of the groups that are displayed.

10.9.4.4 About Source Maps Support

Web client JavaScript debugger and node.js debugger use generated source maps to allow debugging in the original source files.

To debug the code you wrote but not the code that is executed as compressed or translated, the IDE scans your project files to find any present source map and assure that any breakpoint set in the files which were translated for execution (for example, compressed or transpiled), are submitted to the target files. During stepping through the application, the code positions and variable names are translated according to the existing source maps.

10.9.5 Managing Debugging Sessions

Debugging is the process of examining your application for errors. The process of debugging is accomplished by setting breakpoints and watches in your code and running it in the debugger. This enables you to execute your code one line at a time and examine the state of your application to discover any problems.

When you start a debugging session the Debugging window opens in the left pane of the IDE. Additional debugger windows also appear automatically at the bottom of your screen.

You can also debug applications that are running on a remote machine by attaching the debugger to the application process.

10.9.5.1 How to Manage a Local Debugging Session

Local debugging is the process of debugging a program that is running on the same computer as the IDE. The IDE starts the debugger, then runs the application inside the debugger. When you start a debugging session, the IDE automatically opens the debugger windows and prints debugger output to the Output window.

10.9.5.1.1 Debugging the Main Project

Debugging commands in the Debug menu are generally run on the main project, and when debugging a project it is recommended that you set the project as the main project.

If no project is set as the main project the Debug Project command is run on the project that is selected in the Projects window and the commands begin the debugging session in the main class of the selected project. For information on how to set a main project, see Section 6.4, "Setting the Main Project."

Table 10-2 displays the commands in the Debug menu and the corresponding toolbar icons for starting and stopping the debugger.

Table 10-2 Basic Debugging Commands and Icons

Command Icon Description

Debug Project

(Ctrl+F5)

Start Debugging icon.

Starts the debugger and runs the program until it reaches a breakpoint or exception or until the program terminates normally.

Finish Debugger Session

(Ctrl+F5)

Stop Debugging icon

Stops the debugger.

Continue

(F5)

Continue Debugging icon

Runs the program until it reaches the next breakpoint or until the program terminates normally.


To debug an individual project:

  • Right-click the project in the Projects window and choose Debug.

    Alternatively, select the project in the projects window and choose Debug > Debug Project in the main menu.

    The IDE runs the project in the debugger until execution stops or a breakpoint is reached.

To debug an individual file:

  • Select any runnable file in the Projects window and choose Debug > Debug my_file.

    The IDE runs the file in the debugger until execution stops or a breakpoint is reached.

10.9.5.2 How to Manage a Remote Debugging Session

Remote debugging is the process of debugging an application that is running on a different computer. This technique is useful when you are developing an application that runs on a web server or in a different environment than the computer on which you are developing the application.

To start a remote debugging session:

  1. On the computer where the application is located, start the application in debugging mode.

  2. On the computer where the IDE is running, open the projects that contain the source for the application.

  3. Choose Debug > Attach Debugger to open the Attach dialog box.

  4. Select the appropriate Connector from the drop-down list, enter any required process information, and click OK.

For details on the transport and connector options, see the JPDA documentation, Connection and Invocation Details, for your version of the JDK from the Java Platform Debugger Architecture home page at http://docs.oracle.com/javase/7/docs/technotes/guides/jpda/conninv.html.

The instructions for starting an application in debugging mode and the method for connecting to the VM depends on your VM. See your VM documentation for further details.

Note:

You can view and select from the four most recent Attach configurations by expanding the menu under the Debug button in the toolbar.

10.9.5.3 How to Step Through Your Program

After execution of your program is halted, step through your lines of code using the commands listed in Table 10-3 in the Debug menu or the corresponding icons in the toolbar:

Table 10-3 Debugging Step Commands and Icons

Command Icon Description

Step Over

(F8)

Step Over icon

Executes one source line. If the source line contains a call, executes the entire routine without stepping through the individual instructions.

Step Over Expression

(Shift+F8)

Step Over Expression icon

Executes one method call in an expression. If an expression has multiple method calls, you can use Step Over Expression to step through an expression and view the value of each method call in the expression in the Variables window. Each time you use the Step Over Expression command, the debugger advances to the next method call in the expression and the completed method call is underlined. Step Over Expression behaves like Step Over when there are no additional method calls.

For more information, see Section 10.9.6.11, "How to Step Through an Expression."

Step Into

(F7)

Step Into icon

Executes one method call in a source line. If the line has more than one method call you can choose which method call to step into by using the arrow keys or mouse in the source editor to select the method call. The selected method call to step into is indicated by a box around the method call in the source editor. The most likely method call in the line is selected by default.

Step Into Next Method

(Shift+F7)

(no icon for this command)

Executes one source line. If the source line contains a call, the IDE stops just before executing the first statement of the routine. You can also start a debugging session with the Step Into command. Program execution stops on the first line after the main routine before any changes have been made to the state of the program.

Step Out

(Ctrl+F7)

Step Out icon

Executes one source line. If the source line is part of a routine, executes the remaining lines of the routine and returns control to the caller of the routine. The completed method call is highlighted in the Source Editor.

Run to Cursor

(F4)

Run to Cursor icon

Runs the program to the cursor location in the Source Editor and pauses the program. The file you have selected in the Source Editor must be called from the main class of the main project.


To view source code files potentially available to the Debugger:

  • Choose Window > Debugging > Sources (Alt+Shift+8) to open the Sources window.

    The Sources window lists the source directories on your project classpath. The current source file is checked by default, meaning that the Debugger uses it during the debugging session. If you want the Debugger to be able to step into source files other than the current one, you can select those files in this window.

10.9.5.4 How to Fix and Continue in a Debugging Session

If you find a problem while debugging, you can use the Apply Code Changes command to fix your source and then continue debugging with the changed code without restarting your program.

It is not possible to use the Apply Code Changes command to do the following:

  • Change a modifier of a field, a method, or a class

  • Add or remove methods or fields

  • Change the hierarchy of classes

  • Change classes that have not been loaded into the virtual machine

To fix your code:

  1. From the main menu, choose Debug > Apply Code Changes to recompile and begin repairing your source code.

    • If there are errors during compilation, nothing is changed in your program. Edit your source code as needed, then execute the Apply Code Changes command again.

    • If there are no errors, the resulting object code is swapped into the currently executing program. However, all calls on the call stack continue running the unfixed code. To use the modified code, you must pop from the call stack any calls that contain modified code. When the calls are reentered, they use the modified code.

      Note:

      If you modify the currently running method, the IDE displays an alert box. If you click Pop Call, the most recent call is removed from the current call stack. If you click Leave Call, the program executes with the original version of the code. If there is only one call in the stack, you cannot pop the call and continue. For more information on popping the call stack, see Section 10.9.6.9, "Using the Call Stack."
  2. Continue the program to verify that the fixed version of your code works correctly.

The Apply Code Changes command does not automatically rebuild JAR files, executable files, or similar files. You must rebuild these files if you want to debug them in a new session.

10.9.5.5 How to Finish a Debugging Session

If necessary, stop the current debugging session using the Shift-F5 shortcut. You can also close a specific debugging session using the Sessions window.

To finish the current debugging session:

  • Choose Debug > Finish Debugger Session (Shift+F5).

To finish one of several debugging sessions:

  1. Open the Sessions window by choosing Window > Debugging > Sessions (Alt+Shift+6).

    The information given for each session includes the session name and state. In most cases, the state corresponds to the state of the process associated with the session. One session is always considered the current session, unless no sessions are running. By default, the current session is the session that you most recently started.

  2. Right-click the debugging session you want to stop and choose Finish.

For information on local debugging sessions, see Section 10.9.5.1, "How to Manage a Local Debugging Session."

For information on remote debugging sessions, see Section 10.9.5.2, "How to Manage a Remote Debugging Session."

10.9.6 Viewing Program Information When Debugging

In the IDE, local variables are listed in the Variables window, however, it is also possible to evaluate variables directly in the Source Editor. You can view the values returned by each method call in an expression by stepping through an expression.

10.9.6.1 Using the Variables Window

For each variable within the current call, the Variables window displays information including the variable name, type, and value. Choose Window >Debugging > Variables to open this window.

The Variables window also displays all of the static fields from the present class and all superclasses for each variable, as well as all of the inherited fields from all superclasses. For information on how to a call the current call, see Section 10.9.2, "Choosing Current Context in the Debugger."

You can change the value of a local variable directly in the Variables window and then continue running your program with the new value in place.

In some cases, the debugger assigns a pound sign (#) and a number as the variable's value. This number is an unique identifier of the given instance. You can use this identifier to determine if a variable points to the same instance or to a different instance. You cannot edit this value.

10.9.6.2 Using the Loaded Classes Window

The Loaded Classes window displays the classes loaded on the heap and the percentage and number of object instances. You can sort the classes by class name or the number or percentage of instances. You can also use the filter box at the bottom of the window to filter the list by class name. If you open the Loaded Classes window when a debugging session is running, it closes automatically when you end the debugging session. If you open the window when no debugging session is running, it stays open until you close it.

The contents of the Loaded Classes window is dependent on the current context. When you change the current session, the Loaded Classes window is updated to show the classes for that session. Choose Window > Debugging > Loaded Classes to open this window.

To view information for a particular class, right-click a class in the Loaded Classes window and select Show in Instances. The Instances window displays the number of class instances, fields, and references to the class that occur in the current context.

10.9.6.3 Using the Events Window

The Events window displays the events associated with GUI form elements according to the triggering order and also displays the listeners that are associated with the event. Open the Events window by right-clicking a component in the Visual Debugger and choosing Show Listeners in the context menu.

Expand the Custom Listeners node or the Internal SWT/Swing Listeners node to view a list of listeners in the project. Right-click a listener and choose Go to Component Source to open the source file at the line where the listener is defined.

10.9.6.4 Evaluating Variables in the Source Editor

You can also evaluate a variable directly in the Source Editor by moving the insertion point over the variable. If the variable is active in the current context, the value of the variable is displayed in a tool tip. In cases where a program includes different variables with the same name, the Source Editor displays the value based on the current context, and not on the instance of the variable in the source code. Structured values can be expanded into a detailed view. Expandable tooltips feature an Expand icon ( Expand icon) on the left. Alternatively, you can expand a tooltip by pressing the Space bar.

You can track the changes in the value of a variable during program execution by setting a watch on the variable. When you create a watch, the value of the variable is immediately evaluated and displayed in the Watches window.

10.9.6.5 How to Create a Watch

A watch enables you to track the changes in the value of a variable or expression during program execution. The Watches window lists all of the watches you have defined for all of your IDE projects.

To open the Watches window:

  • Choose Window > Debugging > Watches (Alt+Shift+2).

To create a watch from the Source Editor:

  1. Select the variable or expression in the Source Editor, right-click, and choose New Watch (Ctrl+Shift+F7).

    The New Watch dialog box opens with the variable or expression entered in the text field.

  2. Click OK.

    The Watches window opens with the new watch selected.

To create a watch from the Variables window:

  1. Choose Window > Debugging > Variables.

  2. Click the Create New Watch icon ( Create New Watch icon) in the toolbar.

You can click in the Value cell to edit the value directly in the Watches window.

If you specify an expression, follow the syntax rules of the debugger that you are using.

When you create a watch, the value of the variable or expression is immediately evaluated and displayed in the Watches window. The value of the watch is based on the current context. When you change the current context, the Watches window is updated to show the value of the watch for that context.

When a debugging session is running, you can use code completion in the New Watch dialog box.

For information on how to view variable values during a debugging session, see Section 10.9.6, "Viewing Program Information When Debugging."

10.9.6.6 How to Create a Fixed Watch

A fixed watch describes the object that is currently assigned to a variable while a normal watch describes the content of the variable. Fixed watches are specific to the Java 2 debugger.

For example, consider the following code:

java.awt.Dimension dim=new java.awt.Dimension(10,20);
java.awt.Dimension newDim=dim;
dim=new java.awt.Dimension(20,30);
newDim.height=15

With the debugger stopped on the second line, you can create a normal watch on the variable dim. If you create a fixed watch on the variable dim, the watch describes the object that is currently assigned to the variable, which is java.awt.Dimension(10,20). If you press F8 to step over the code three times, the value of the normal watch becomes java.awt.Dimension(20,30). This change occurred on the third line of source code. The value of the fixed watch is java.awt.Dimension(15,20). The fixed watch was created on the object with a height of 10, but the fourth line changed the height of this object to 15.

To create a fixed watch:

  • In the Variables or Watches window, right-click a variable and choose Create Fixed Watch.

    The fixed watch is added to the Watches window.

10.9.6.7 How to Pin a Watch

You can set a watch or multiple watches in your code to review a variable value in the Source Editor. The pinned watch updates its value like a watch in the Watches window and keeps the last known value even after the debugging session finishes.

To pin a watch:

  1. Hover a mouse over a variable or a selected expression in the Source Editor area until the IDE displays the tooltip with the value of the variable or your selection.

  2. Press the Enter key or click the Pin icon ( pin icon) in the tooltip.

    The IDE adds a watch pinned into the Source Editor and displays a pinned watch window with two icons on the right side - the Comment ( comment icon) and Close ( close icon) icons. You can drag the pinned watch window with the mouse.

To display the pinned watches in the Variables and Watches windows, right-click in either window and choose Show Pinned Watches from the context menu.

10.9.6.8 Debugging Threads in the IDE

All the threads created in the current session are displayed in the Debugging window. Choose Window > Debugging > Debugging (Alt+Shift+9) to open the Debugging window. You can also see the list of threads in the current session in the Threads window. Choose Window > Debugging > Threads (Alt+Shift+7) to open the Threads window.

The information given for each thread is the thread name, state and if the thread is suspended. One thread is the current thread. By default, the current thread is the thread in the current session from which the debugger gained control. When you select a different current session, the Threads window is updated to show the threads for that session.

10.9.6.8.1 Changing the Current Thread

Only one thread is the current thread at any given time. By default, the current thread is the thread within the current session from which the debugger gained control. When you switch between threads to debug, the Variables window is automatically updated to reflect the data applicable to that thread.

To change the current thread:

  • Double-click any thread in the Debugging window to make it the current thread.

10.9.6.8.2 Suspending and Resuming Threads

You can suspend execution of a thread if you think it is causing problems and then later resume the thread once the problem is solved. The Debugging window enables you to easily see the threads in the debugging session and identify the running and suspended threads. The icon to the left of the thread name indicates whether the thread is suspended or waiting to be resumed.

You can suspend, interrupt and resume application threads by right-clicking a thread in the Debugging window and choosing an action from the context menu.

Alternatively, you can click the Resume ( Resume Button icon) and Suspend ( Suspend Button icon) buttons in the right side of the Debugging window. Hide the Suspend and Resume buttons by clicking the Show suspend/resume table button ( Show Suspend Resume Table Button icon) in the Debugging window toolbar.

You can also resume and suspend threads in the Threads window.

10.9.6.8.3 Editor window icons

A thread icon in the left margin of the source editor indicates that there is a suspended thread at that line. The following table describes the icons representing the thread states that appear in the source editor during a debugging session.

Table 10-4 Thread State Icons

Icons Description

Suspended Thread icon

Other suspended threads

Suspended Thread Due to Breakpoint icon

Other threads suspended by hitting a breakpoint


To switch a suspended thread to the current thread:

  • In the source editor, right-click the suspended thread icon and choose Set Current Thread To > new_current_thread.

10.9.6.8.4 Multi-threaded Applications

When debugging a multi-threaded application, a step in a particular thread can be interrupted by a breakpoint encountered in some other thread. When this occurs, the IDE gives you the option to switch threads. The IDE does not automatically switch the context to the new thread.

When a breakpoint in another thread is encountered, you are notified by a panel that appears in the Debugging window. The current thread remains the current thread until you explicitly switch it or the thread stops. Click the arrow in the panel in the Debugging window and choose a thread to switch to that thread at any time. This action enables you to continue debugging the current thread and when it is convenient you can switch to the thread that hit a breakpoint.

You can use the Current Thread Chooser (Ctrl+8) to select the thread you want to be the current thread.

10.9.6.8.5 Viewing Source Code for a Thread

If you suspect the source code of a thread is causing problems, you can examine it in the Source Editor.

To view a thread's source:

  • Right-click the thread in the Threads window and choose Go To Source.

    If the source of the thread is available, the Source Editor jumps to the current call on the thread's call stack.

10.9.6.9 Using the Call Stack

In a debugging session, you can see the call stack for the current thread in the Debugging window (opened automatically whenever you start a debugging session). If you expand the node for the current thread you can see a list of the sequence of calls made during the execution of the thread.

The information given for each call (marked by a Call Stack icon icon) includes the name of the call, followed by the file name and line number of the call's currently executing statement. If the sources are available, you can right-click the call and choose Go To Source to go to the source code of the call.

Alternatively, you can open the Call Stack window by choosing Window > Debugging > Call Stack (Alt +Shift+3).

10.9.6.9.1 Changing the Current Call

The current call (indicated in bold) is the most recent call made by the current thread. When you select a different current thread, the window is updated to show the calls for that thread. The Variables window is also updated to display the values of variables for the current call.

To browse the call stack, do any of the following:

  • To move one level away from the main routine, choose Debug > Stack > Make Callee Current (Ctrl+Alt+up arrow).

  • To move one level toward the main routine, choose Debug > Stack > Make Caller Current (Ctrl+Alt-+down arrow).

  • To make a call current, double-click the call in the Call Stack window.

You can capture a textual representation of the call stack by right-clicking a a call and choosing Copy Stack from the context menu. When you copy the call stack, the text is copied to the clipboard. You can then paste the call stack into a text file.

10.9.6.9.2 Popping a Call From the Call Stack

You can change the execution of your program so that the next statement to be executed is one of the calls made earlier on the stack. In general, popping, or removing, a call from the call stack does not undo any effects that the call caused. For example, if a call opened a database connection and then that call is removed, the database connection remains open.

Note:

You can only pop a call if the program being debugged is paused.

To pop the most recent call from the call stack:

  • From the main menu, choose Debug > Stack > Pop Topmost Call.

    The call is removed from the call stack. The program counter is moved to the line before the instruction that made the removed call. If the source code is available, the focus of the Source Editor is set to that line. When you continue program execution, the call is repeated.

To pop multiple calls from the call stack:

  • In the Debugging window, right-click the call that you want to remain at the top of the call stack and choose Pop to Here.

    All of the calls above the selected call are removed from the call stack. The program counter is moved to the line before the instruction that made the removed call. If the source code is available, the program counter moves to that line. When you continue program execution, the call is repeated.

10.9.6.10 How to Evaluate Code

When you are in a debugging session, you can evaluate any code snippet to view the values of local variables for the current method, class variables, and method calls.

You can view the values returned by each method call in the expression by stepping through an expression.

To evaluate an expression:

  1. Start a debugging session.

  2. Choose Debug > Evaluate Expression (Ctrl+F9) from the main menu.

  3. Type a code snippet in the Evaluate Code window and click Evaluate icon in the bottom right corner of the window). The result is shown in the Variables view. The result with historical values is shown in the Evaluation Results view.

    Click the Create New Watch button ( Create New Watch icon) in the Variables view to set a watch for the expression. The watch is added to the Watches view.

If you evaluate a method that changes a global variable, the global variable's value is changed in the debugging session as well.

If you try to evaluate a variable that is outside the scope of the current method, a message displays "variable" is not a known variable in current context. Use the Call Stack window to change the current method context.

If you try to access a global variable before the file that contains the variable is instantiated, a message displays Cannot access instance variable "variable" from static context.

10.9.6.11 How to Step Through an Expression

When you are in a debugging session, use the Step Over Expression command to step through an expression and view the values returned by each method call in the expression.

Use the Step Over Expression command to achieve a more fine-grained stepping than other debugging steps. Step Over Expression enables you to proceed through each method call in an expression and view the input parameters and resulting output values of each method call. Invoke the Step Over Expression command just as you would any other step commands. If there are no further method calls, Step Over Expression behaves like the Step Over command.

Each method call in an expression has some input (parameters) and output values. Each time you use the Step Over Expression command in an expression, the debugger resumes VM execution and then stops before executing the next method call. You can inspect the output values for the previous method and the input parameters for the next method in the Variables window. Invoking Step Over Expression again resumes the VM execution until the next method call in the expression.

To step through an expression:

  1. Place a breakpoint in the line containing the expression you want to debug and start the debugging session.

    When you start the debugger, the VM stops before executing any of the method calls in the expression.

  2. Choose Debug > Step Over Expression (Shift+F8) from the main menu.

    The debugger steps to the first method call in the expression but does not execute the method. The Variables window displays the input parameters of the method.

  3. Invoke Step Over Expression again to execute the first method and step to the next method call in the expression.

    The Variables window displays the output values of the executed method and any input parameters for the next method in the expression.

    In the Source Editor, the executed method call is underlined and the next method call in the expression is highlighted. Mouse over the executed method to display a tooltip and view the output values.

  4. Invoke Step Over Expression again to step to the next method call in the expression.

    The Variables window displays the output values under the Return Values node.