Skip Headers
Oracle® Fusion Middleware User's Guide for Oracle JDeveloper
11g Release 2 (11.1.2.0.0)

Part Number E17455-01
Go to Documentation Home
Home
Go to Table of Contents
Contents
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
PDF · Mobi · ePub

18 Programming in Java

This chapter describes how to use the tools and features provided by JDeveloper to build Java applications. It explains how to define classes on a diagram. Class members, inheritance, and composition relationships are all derived directly from the Java source code for those classes.

This chapter includes the following sections:

18.1 About Programming in Java

JDeveloper enables you to build and assemble Java applets and client applications using JavaBeans, and interactive, desktop-based GUI applications using Swing and AWT components. You can also create and run Java client applications with Java Web Start within the JDeveloper IDE.

JDeveloper provides resources for performing the following tasks in the Java domain:

18.2 Navigating in Java Code

JDeveloper supports Java-aware features for locating and moving to the source code for your projects' classes and interfaces and their members.

18.2.1 How to Browse Classes or Interfaces

While working in JDeveloper, you can browse Java elements directly from the UI or directly from a file open in the Java Source Editor.

To browse a Java element directly from the UI:

  1. From the main menu, choose Navigate > Go to Java Type. Or, you can use the keyboard shortcut, Ctrl-minus.

  2. In the Go to Java Type dialog, enter the name of the Java type that you want to locate. When you begin entering text in this field, a list of Java entities matching the text is displayed.

  3. Double-click an entity in the list to open it in the source editor.

To browse a class or an interface for a file currently open in the editor:

  1. With the file open in the editor, ensure that the editor has focus.

  2. Select the class or interface name in the source file, right-click, and choose Go to Declaration.

    The source file opens in the Java Source Editor.

18.2.2 How to Locate the Declaration of a Variable, Class, or Method

When working in the Java Source Editor, you can quickly locate the declaration of any identifier.

To navigate to the declaration of a code element:

  • Right-click on the code element and choose Go to Declaration, or

  • Press the Control key and left-click on the code element.

The source code for that element opens, with the line on which it is declared highlighted.

18.2.3 How to Find the Usages of a Class or Interface

While working in the Java Source Editor, you can quickly locate references to a class or interface and its members. By default, usages in the current project and its dependency projects will be reported. You can extend the search to libraries if the source files for the libraries are accessible.

The Find Usages command can also be applied to individual methods and fields, and to local variables and parameters.

To find the usages of a class:

  1. Select the class or interface in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a navigator or the Structure window, select the class or interface.

  2. Invoke the command using one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

      The Usages of <Object> dialog will open

  3. In the Find box select the types of references that the search will return.

  4. In the Where box define the optional additional areas you want to search in.

  5. Direct the output of the search: select New Tab to direct the output to a new Usages Log. If not selected, the result of the previous search for usages, if any, will be discarded.

  6. Click OK.

    The search will commence, and the results will be displayed in the Usages Log window.

18.2.4 How to Find the Usages of a Method

While working in the Java Source Editor, you can quickly locate references to a method.

The search will show applications of the method to instances of the class or interface for which the method is defined and also for instances of its subclasses or subinterfaces, if any, that inherit the method.

The Find Usages command can also be applied to classes and interfaces, fields, and to local variables and parameters.

To find the usages of a method:

  1. Select the method in one of the following ways:

    • In a Java Source Editor, select the name.

    • In the Structure pane, select the field.

  2. Invoke the command in one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

      The Usages of <Method> dialog displays. This dialog provides various options that you can specify to search for usages.

    • Specify options in the dialog and click OK to begin the search.

18.2.5 How to Find the Usages of a Field

While working in the Java Source Editor, you can quickly locate references to a field.

The search will show references to the field in instances of the class or interface for which the field is defined and also for instances of its subclasses or subinterfaces, if any, that inherit the field.

The Find Usages command can also be applied to classes and interfaces, methods, and to local variables and parameters.

To find the usages of a field:

  1. Select the field in one of the following ways:

    • In a Java Source Editor, select the name.

    • In the Structure pane, select the field.

  2. Invoke the command in one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

  3. Complete the Usages of <Object> dialog and click OK. You can specify options to extend the search to other areas, define the scope of the search, and optionally specify that the results be displayed in a new tab in the Log window.

    The search will commence, and the results will be displayed in the Usages of <Object> Log window.

18.2.6 How to Find the Usages of a Local Variable or Parameter

While working in the Java Source Editor, you can quickly locate references to a local variable or a parameter in a method body.

The Find Usages command can also be applied to classes and interfaces, methods, and fields.

To find the usages of a local variable or parameter:

  1. Select the variable or parameter name in the Java Source Editor.

  2. Invoke the command in one of the following ways:

    • Choose Search > Find Usages.

    • Right-click and choose Find Usages.

    • Press Ctrl+Alt-U.

      The search will commence, and the results will be displayed in the Usages Log window.

18.2.7 How to Find Overridden Method Definitions

While working in the Java Source Editor, you can easily identify methods that override superclass definitions. Overriding definitions are marked with the Overrides up arrow icon in the Java Source Editor margin.

To view the overridden definition of a method, click the Overrides margin icon.

If you navigate to the override, then click the Back Main toolbar button to return to the previous view.

18.2.8 How to Find Implemented Method Declarations

While working in the Java Source Editor, you can easily identify methods that override superclass definitions. Overriding definitions are marked with the Implements down arrow icon in the Java Source Editor margin.

To view the overridden definition of a method, click the Implements margin icon.

If you navigate to the override, then click the Back Main toolbar button to return to the previous view.

18.2.9 How to View the Hierarchy of a Class or Interface

While working in the Java Source Editor, you can inspect the hierarchy of subtypes and supertypes of a class or interface. The Hierarchy window displays the hierarchy of the selected classes or interface.

To view the hierarchy of a class or interface in the Java Source Editor:

  1. Select the class or interface, then either right-click and choose Type Hierarchy or choose Navigate > Type Hierarchy.

    The Hierarchy window will open (if it is not already open) and the tree of either subtypes or supertypes will be shown.

  2. To toggle the display between subtypes and supertypes, click the Subtype Hierarchy or Supertype Hierarchy button.

To open a hierarchy initially in the Java Visual Editor:

  1. Select a node in the Navigator.

  2. Right-click and choose Edit, or use the View menu.

    The entire GUI hierarchy for the this node displays in the editor. The method of display depends upon whether this hierarchy consists of menu or nonmenu items.

18.2.10 Stepping Through the Members of a Class

You can use keyboard accelerators to step from member to member in a class definition in a Java Source Editor:

  • To step to the next member definition or declaration in the current Java source view, press Alt-Down, or choose Navigate > Go To Next Member.

  • To step to the previous member definition or declaration in the current Java source view, press Alt-Up, or choose Navigate, then Go To Previous Member.

These additional code-stepping commands are also defined, but are not assigned default accelerators:

  • Go to Next Class

  • Go to Next Field

  • Go to Next Method

  • Go to Previous Class

  • Go to Previous Field

  • Go to Previous Method

These commands are listed in the Navigate category of the Shortcut Keys page of the Preferences dialog. You can add or change accelerators.

18.3 Editing Java Code

JDeveloper provides many Java-aware editing features you can use to improve your productivity. As an alternative to text editing, you can also use the Java Visual Editor when developing graphical user interfaces. The Source Editor and Visual Editor are synchronized; a change in one is immediately reflected in the other. These Java editing features augment generic source editing features that support coding in any technology.

18.3.1 Editing Code with the Java Visual Editor

The Java Visual Editor displays the visual components of a user interface in Editing mode.

When a Java Visual Editor is open, its corresponding elements are displayed hierarchically in the Structure window. If the Property Inspector is open, selecting elements in either the Structure window or the Java Visual Editor changes the selection in the Inspector as well.

The Java Visual Editor displays a GUI hierarchy. If these are menu items, the hierarchy is displayed in one fashion; if these are nonmenu items, it is displayed in another. The mode of presentation differs, as the sort of editing that you are engaged in differs.

To open a hierarchy initially in the Java Visual Editor, you have only to select a node in the Navigator and then right-click and choose Edit, or use the View menu. The entire GUI hierarchy for the this node displays in the editor. The method of display depends upon whether this hierarchy consists of menu or nonmenu items.

When the node is selected in the Navigator, its GUI structure also displays in the Structure window. All nonmenu GUI items for this object appear under a node labeled UI. Any menu items appear under a node labeled Menu. Any non-GUI items appear under a node labeled Other. Once you have opened the Java Visual Editor for an object in the Navigator, to switch between the display of nonmenu GUI elements and menu elements you have only to click on a node below these UI or Menu nodes in the Structure window.

Because the display in the Java Visual Editor is rooted in the GUI hierarchy, when you click on a node (for all GUI objects) in the Structure window what loads into the editor is the visual representation of the root node and all its descendants: the entire hierarchy opens, regardless of which node in the hierarchy you selected. What displays in the editor reflects the complete GUI hierarchy; the specific element selected in the display reflects the specific node selected in the window. Selections in the Structure window and the Java Visual Editor are kept in synch.

If you have an orphan node in the Structure window, that node and its descendants comprise the entire hierarchy, with the orphan being the root of the hierarchy. The Java UI display will reflect this. If you had a control, for instance, that was not parented, and you selected the node for that control, the control and any descendants would now appear in the editor, without a container. Any changes you make to that control, however, will result in generated code.

Right-click anywhere within the Java Visual Editor to bring up a context-sensitive menu of commands. The context menus differ, depending upon whether you are editing nonmenu or menu items, and the commands available within the context menu depend on the selected object.

18.3.2 Opening the Java Visual Editor

Right-click the Java file in the Navigator that you want to modify and choose Open > click the Design tab.

The source code is accessible in the Code Editor (right-click the file in the Navigator and choose Open to view the source code) so you can view and edit your source code in parallel with designing your UI. Any changes made in the Java Visual Editor or Property Inspector are immediately reflected in the source code, and vice-versa.

The Java Visual Editor toolbar lets you easily work with components and duplicates commands that you can choose from the context sensitive menu displayed on a selected component. Among the component operations included are:

  • Constraints to specify component weight, fill, anchor position, padding, and inset.

  • Alignment to quickly position components relative to one another.

  • Z-Order to change the sequence of stacked components.

18.3.3 Understanding Java Visual Editor Proxy Classes

JDeveloper is a lightweight (JFC) application. As such, using heavyweight (AWT) controls directly in the Java Visual Editor will not work as expected. Heavyweight components always obscure lightweight components, including the lightweight JDeveloper environment (including the Code Editor and UML Modelers).

The Java Visual Editor includes a proxy mechanism for registering lightweight proxies to represent heavyweight controls for instantiation in the Java Visual Editor. By default JDeveloper includes lightweight proxies for all the standard AWT controls.

18.3.4 Registering a Java Visual Editor Proxy for Custom Components

JDeveloper supports lightweight views of heavyweight components that you register for use by the Java Visual Editor.

To register the proxy class:

Add a key-value definition to oracle.jdevimpl.uieditor.UIEditorAddin section in the JDeveloper\lib\addins.xml file, as shown in Example 18-1.

Example 18-1 Key-value Definition

<property>
   <key>PREFIX.CLASS_NAME</key> 
   <value>PROXY_CLASS_NAME</value> 
</property> 

where:

  • PREFIX is jdeveloper.concreteProxy

  • CLASS_NAME is the fully-qualified classname of the heavyweight component for which a proxy is being registered

  • PROXY_CLASS_NAME is the fully-qualified classname of the proxy class to register

For example; if you were to register a hypothetical heavyweight component implementation jdeveloper.concreteProxy.java.awt.Component using the oracle.jdevimpl.uieditor.proxy.Component proxy class, the property to add would look like Example 18-2.

Example 18-2 Heavyweight Component

<property>
   <key>jdeveloper.concreteProxy.java.awt.Component</key>
   <value>oracle.jdevimpl.uieditor.proxy.Component</value> 
</property> 

In order for the Java Visual Editor proxy class to be available from within the IDE, so that it will appear can be added to the Component Palette, the proxy class must be added to the IDEClasspath as a directive in JDeveloper\bin\jdev.conf file. For example:

AddJavaLibFile <myUiProxies.jar>

where myUiProxies.jar contains the compiled class file for your Java Visual Editor proxy implementation.

18.3.5 How to Create a New Java Class

Before creating a new class, note that you must first create an application and a project. As soon as you create the class, it is added to the active project.

To create a new class and add it to a project:

  1. In the Application Navigator, select the project you want to add the class to.

  2. Right-click and choose New.

  3. In the New Gallery, under the General category, select Java.

  4. Under Items, select Class.

  5. In the Create Java Class dialog, enter the class name, the package name, and the superclass that the new class will extend. Select attributes as needed.

  6. Click OK.

    The new class appears in the active project.

18.3.6 How to Create a New Java Interface

Before creating a new interface, note that you must first create an application and a project. As soon as you create the interface, it is added to the active project.

To create a new interface and add it to a project:

  1. In the Application Navigator, select the project you want to add the class to.

  2. Right-click and choose New.

  3. In the New Gallery, under the General category, select Java.

  4. Under Items, select Interface.

  5. In the Create Java Interface dialog, enter the interface name, the package name, and the superclass that the new class will extend. Select attributes as needed.

  6. Click OK.

    The new class appears in the active project.

18.3.7 How to Implement a Java Interface

In the source editor, you can quickly add framework code to modify a target class to implement an interface or to make a target interface extend another interface.

An implements or extends clause is added to the declaration for the target class or interface, and an import statement is added to the file. If the target is a class, stub definitions for the implemented interface's methods are appended to the class or interface body.

To implement an interface:

  1. Open a Java source file.

  2. From the main menu, choose Source > Implement Interface.

  3. On the Search or Hierarchy tab, locate the class that will implement the interface and select the names of the interfaces that are to be implemented.

  4. If you want documentation comments from the overridden methods to be included, select Copy Javadoc.

  5. Click OK.

18.3.8 How to Override Methods

In the source editor, you can quickly add stub definitions to a class to override methods inherited from superclasses.

To override methods:

  1. Open a Java source file.

  2. From the main menu, choose Source > Override Methods.

  3. In the Methods list, select the methods that are to be overridden.

    The list displays methods inherited from all superclasses. Abstract methods are shown in bold type.

  4. If you want documentation comments from the overridden methods to be included, select Copy Javadoc.

  5. Click OK.

    The stub method definitions are added to the class.

  6. Edit the stub definitions.

18.3.9 How to Use Code Templates

JDeveloper provides predefined code templates that you can use. Code templates assist you in writing code more quickly and efficiently by inserting text for commonly used statements. For example, the "Iterate over a list" (itli) template inserts the following code:

for (int i = 0; i < unknown.size(); i++) {
     Object object = (Object) unknown.get(i);
   }

Note:

If the template contains variables, the variables are highlighted. You can edit each variable to complete the template. Pressing Tab moves the caret to the next template variable.

In addition to the templates provided by JDeveloper, you can also define your own code templates in the Code Editor - Code Templates page of the Preferences dialog.

To evoke a defined code template:

  1. In the file open in the editor, put the cursor at the point where the template is to be inserted.

  2. Type the shortcut associated with the template and then press Ctrl+Enter.

    The code as defined in the template is inserted in the source file. Import statements needed for the template, if any, are inserted at the top of the file.

Note:

Ctrl+Enter is the accelerator assigned in the default keymap. You can assign an alternative.

18.3.10 Using Predefined Code Templates

This section lists the predefined code templates. The shortcut and the code that the template introduces are shown for each.

Array Iterator

ai
for (int $i$ = 0; $i$ < $array$.length; $i$++)
{
    $type$ $var$ = $array$[$i$];
    $end$
}

Data Action Event Handler

daev
public void on$end$(PageLifecycleContext ctx)
{
}

for loop

for
for ($end$ ; ; ) 
{
}

if statement

if
if ($end$) 
{
}

if else statement

ife
if ($end$) 
{

} else
{

}

integer based loop

fori
for (int $i$ = 0; $i$ < $lim$; $i$++) 
{
   $end$
}

integer based loop

forn

int $n$ = $lim$;
for (int $i$ = 0; $i$ < $n$; $i$++) 
{
   $end$
}

instanceof + cast

iofc
if ($var$ instanceof $type$)
{
     $type$ $casted$ = ($type$) $var$;
     $end$
}

Instantiate a BC4J application module

bc4jclient

String amDef = "test.TestModule";
String config = "TestModuleLocal";
ApplicationModule am =
Configuration.createRootApplicationModule(amDef,config);
ViewObject vo = am.findViewObject("TestView");
$end$// Work with your appmodule and view object here
Configuration.releaseRootApplicationModule(am,true); 

Iterate over array

itar

for (int $i$ = 0; $i$ < $array$.length; $i$++)
{
     $type$ $var$ = $array$[$i$]; 
     $end$
}

Iterate over a collection

itco

for(Iterator $iter$ = $col$.iterator();$iter$.hasNext();)

{
     $type$ $var$ = ($type$) $iter$.next();
     $end$ }

Iterate over a list

itli
for (int $i$ = 0; $i$ < $list$.size(); $i$++)
{
     $type$ $var$ = ($type$) $list$.get($i$);
     $end$
}

Iterate over map keys

itmk

Iterator $iter$ = $map$.keySet().iterator();
while ($iter$.hasNext())
{
     $type$ $var$ = ($type$) $iter$.next();
     $end$
}

Iterate over map values

itmv

Iterator $iter$ = $map$.values().iterator();
while ($iter$.hasNext())
{
     $type$ $var$ = ($type$) $iter$.next();
     $end$
}

JDBC Connection

conn

public static Connection getConnection() throws SQLException
{
     String username = "$end$scott";
     String password = "tiger";
     String thinConn = "jdbc:oracle:thin:@localhost:1521:ORCL";
     Driver d = new OracleDriver();
     Connection conn = 
DriverManager.getConnection(thinConn,username,password);
     conn.setAutoCommit(false);
     return conn;
}

List to array

ltoar

$type$ $var$ = new $typeelem$[$list$.size()];
$var$ = ($type$) $list$.toArray($var$);
$end$ 

main method

main

public static void main(String[] args)
{
     $end$
}

out.println()

outp

out.println($end$); 

private ArrayList

pral

private ArrayList _$end$ = new ArrayList(); 

private boolean

prb

private boolean _$end$; 

private HashMap

prhm

private HashMap _$end$ = new HashMap(); 

private int

pri

private int _$end$; 

private String

prs

private String _$end$; 

public static final

pusf

public static final $end$; 

public static final boolean

pusfb

public static final boolean $end$; 

public static final int

pusfi
public static final int $end$; 

public static final String

pusfs

public static final String $end$; 

Reverse array iterator

ritar

for (int $i$ = $array$.length; --$i$ >= 0 ;)
{
    $type$ $var$ = $array$[$i$];
    $end$
}

Reverse iteration over a list

ritli

for (int $i$ = $list$.size(); --$i$ >= 0 ; )
{
     $type$ $var$ = ($type$) $list$.get($i$);
     $end$
}

System.err.println

sep
System.err.println($end$); 

System.out.println

sop

System.out.println($end$); 

switch statement

sw

switch ($end$) 
{
    case XXX:
       {
       }
    break;
    default;
      {
      }
    break;
}

try statement

try

try
{
   $end$
} catch (Exception ex) 
{
  ex.printStackTrace();
} finally 
{
}

Insert a tag

tag

<$tag$>
  $end$
</$tag$>

while statement

wh

while ($end$) 
{

}

18.3.11 How to Expand or Narrow Selected Text

You can use the Expand/Narrow Selection option to successively expand or narrow a selected block of code, based on Java syntax.

To expand selected code:

  1. With the file open in the editor, ensure that the editor has focus.

  2. Put the cursor at the point where you want to expand the selection, or select a portion of the code.

  3. From the main menu, choose Source > Expand Selection, or press Ctrl+Shift+Equals.

    The selection expands to include the smallest logical unit containing the element previously selected or within which the cursor previously resided.

With each successive application of the option, the selection expands to include the next logical step up in the Java hierarchy, based on the starting point, until the entire file is selected. For example: method name, qualified method call, assignment, definition, and so on.

Use the Narrow Selection option (or press Ctrl+Shift+Minus) to successively reduce selected code in the same fashion.

18.3.12 How to Surround Code with Coding Constructs

You can easily surround Java statements and blocks with coding constructs in the Java Source Editor.

To surround a block of code with a construct:

  1. With the file open in the editor, right-click within a statement, or select a block of code, and choose Surround. Alternatively, you can click the Surround ({ }) icon the Source Editor toolbar.

    Note:

    This icon is only enabled when the selected code is a valid code block to which the Surround With feature can be applied.
  2. In the Surround With dialog, select the coding construct.

18.3.13 Adding an Import Statement

You can add needed import statements while working in the Java Source Editor. If, as you are typing in the Source Editor, you introduce a reference to a class that has not yet been imported, a ragged line will appear below it. A popup will open showing that an import is needed, giving the fully-qualified name of the class. JDeveloper will automatically add an import if it can find only one exact match for an unresolved reference to a class.

JDeveloper will automatically add an import if it can find only one exact match for an unresolved reference to a class. If the import assistance matches more than one possible match, then a popup list appears that lists all possible matches from the class path. The user can then choose the appropriate import and the import statement is automatically added.

The import assistance popup can be triggered at any time by pressing Alt+Enter.

The gutter-based code assistance can be used to add an import statement. If the editor doesn't recognize a class, a lightbulb appears in the gutter when the line is highlighted and various import options are displayed.

To configure or disable Import assistance, you can set Import Statement Options in the Java Source Editor.

18.3.14 How to Organize Import Statements

You can organize import statements easily in the Java Source Editor. Set the options for organizing imports to your liking in the Preferences dialog. The following options are provided:

  • Sort and group the import statements alphabetically by package and class name.

  • Narrow the imports by replacing type-import-on-demand statements for packages with single-type-import statements for individual classes.

  • Widen the imports by replacing two or more single-type-import statements for classes from a common package with a single type-import-on-demand statement for the package.

  • Remove import statements for classes that are not referenced.

You can configure or disable import organizing options. For more information, see Section 17.4.3, "How to Enable Automatic Import Assistance for the Java Source Editor."

To organize import statements in a source file:

With the file open in the editor, right-click and choose Organize Imports.

18.4 Adding Documentation Comments

You can use JDeveloper's editing commands to create and maintain documentation comments.

18.4.1 How to Add Documentation Comments

You can add documentation comments to your source files in the Java Source Editor.

To add documentation comments to a source file:

  • Place the cursor just above the declaration of the class, field, or method to be documented, type the start of a documentation comment (/**), and press Enter.

  • With the code element selected in the Structure window, right-click and choose Add Javadoc Comments.

A template for the documentation comment will be inserted in the file. Add information to the template to describe the element.

18.4.2 How to Edit Documentation Comments

You can customize the use of documentation comment tags in the Java code editor. You can define custom tags, and choose which tags will be automatically included when a documentation comment is created. These choices apply to all projects.

To define a custom tag:

  1. From the main menu, choose Tools > Preferences.

  2. In the Preferences dialog, choose the Code Editor > Java > Javadoc page.

  3. Click Add. A tag with the default name new will be added to the list.

  4. In the Tag Properties box change the name of the tag and set its other properties.

  5. When finished, click OK.

18.4.3 How to Update Documentation Comments

You can update documentation comments in the Java Source Editor.

To update documentation comments in a source file:

  1. In the Structure window, place the cursor on the element for which comments are to be updated.

  2. Right-click and choose Add Javadoc Comments.

    Tags will be added to or removed from the documentation comment to reflect changes you have made to the element. Add descriptions for the new tags.

18.4.4 How to Audit Documentation Comments

You can validate documentation comments in your source files. The audit will report formatting errors and missing or extraneous tags.

To check documentation comments in a source file:

  1. In the Application Navigator, select the file to be checked.

  2. From the main menu, choose Build > Audit <filename>.

  3. In the Audit dialog, select Javadoc Rules from the Profile dropdown list.

  4. If you want configure the audit, to choose which types of errors to search for or to ignore, click Edit.

    The Audit Profile dialog opens.

  5. Click Run.

    The results of the audit appear in the Log window.

18.5 How to Customize Javadoc Options for the Java Source Editor

You can add new Javadoc tags and customize the attributes of some existing tags. When creating custom tags, you can associate the tag with code elements, define it as required or not, assign it a default value, and give it an order in the tag list.

To customize the options for Javadoc in the Java Source Editor:

  1. From the main menu, choose Tools > Preferences.

  2. In the Preferences dialog, expand the Code Editor node.

  3. Expand the Java node and select Javadoc.

  4. On the Javadoc page, select an item in the Tags list to see its attributes displayed to the right. Tags appearing in bold are customizable.

  5. To add a tag, click Add and fill in the information.

  6. To change a tag's position in the Tags list, select the tag and click the up or down button.

    To do this without using the mouse, tab to the button and press the spacebar.

  7. To delete a tag, select it in the Tags list and click Remove.

  8. When finished, click OK.

18.5.1 How to Add Documentation Comments

You can add documentation comments to your source files in the Java Source Editor.

To add documentation comments to a source file:

  • Place the cursor just above the declaration of the class, field, or method to be documented, type the start of a documentation comment (/**), and press Enter.

  • With the code element selected in the Structure window, right-click and choose Add Javadoc Comments.

A template for the documentation comment will be inserted in the file. Add information to the template to describe the element.

18.5.2 How to Set Javadoc Properties for a Project

Every project you create carries the JDeveloper project defaults or those you have supplied yourself for all the projects across workspaces. You can also replace these defaults on a project-by-project basis. Setting these properties is the same in either case: only the location, and application, of the information differs.

To set Javadoc properties for an individual project:

  1. In the Application Navigator, select the project.

  2. From the main menu, choose Application > Project Properties, or right-click and choose Project Properties.

    The Project Properties dialog opens.

  3. Make changes to the project properties as required.

  4. When finished, click OK to close the Project Properties dialog.

18.5.3 How to View Javadoc for a Code Element Using Quick Javadoc

When working in the Java Source Editor, you can quickly access Javadoc-generated documentation for the following code elements: a class, interface, or an individual member, using the Quick Javadoc feature.

The Quick Javadoc feature looks up the selected entity on the source path and displays the Javadoc comment entered in a popup window. If no Javadoc comment exists for that element, an empty Javadoc comment is displayed. The source code is available if one of the following is met:

To display Javadoc for a code element:

  1. Select the code element.

  2. From the main menu, choose Source > Quick Javadoc, or from within the editor, right-click and choose Quick Javadoc.

    A popup window displaying the documentation for the element appears. Click outside the window to close it.

The Quick Javadoc feature is available when the selected source code meets of the following criteria:

  • It is on this project's source path.

  • It is on the source path of a project that the current project depends on.

  • It is available for a library assigned to this project

  • It is a part of the JDK in use.

18.5.4 How to Preview Documentation Comments

You can preview documentation comments in your source files, in the same way that you view Javadoc for a single source element.

To display documentation comments for a given class, member, or method call:

  1. Select the name of the code element.

  2. Right-click and choose Quick Javadoc.

    A popup window showing the Javadoc for just that element now appears. From this window, you can link to other Javadoc as you would in a browser.

18.6 Building Java Projects

JDeveloper provides these facilities for building projects:

18.6.1 Building with Make and Rebuild Commands

The Make and Rebuild commands execute standard operations for compiling projects in JDeveloper.

  • Make project makes all the projects the project depends on (recursively), and then makes the project.

  • Make project only makes the project but not any of the projects it depends on.

  • Rebuild project rebuilds all the projects the project depends on (recursively), and then rebuilds the project.

  • Rebuild project only rebuilds the project but not any of the projects it depends on

18.6.1.1 Compiling with Make

Make operations compile source files that have changed since they were last compiled, or have dependencies that have changed. Rebuild operations, in contrast, compile source files unconditionally. You can invoke make on individual source files, on working sets, or on containers such as packages, projects, and workspaces.

If you wish to compile more selectively, you can add an Ant buildfile to a project, define additional targets, and run Ant to make those targets.

You cancel a compilation currently in progress by clicking the Cancel Build icon in the main toolbar. When you click this icon, an error message gets printed to the top row of the Compiler Log window.

Ways to make source file(s):

  • In a file's source editor window, right-click and choose Make.

  • Select one or more projects in the navigator, and click Make in the toolbar.

  • Select one or more projects in the navigator, and choose a Make item from the Build menu.

  • Select one or more projects in the navigator, right-click, and choose Make.

18.6.1.2 Compiling with Rebuild

Rebuild operations compile all the source files in a project or workspace. Unlike make operations, which recompile only those source files that have changed or have dependencies that have changed, rebuild operations are not conditional.

If you wish to compile more selectively, you can add an Ant buildfile to a project, define additional targets, and run Ant to make those targets.

You cancel a compilation currently in progress by clicking the Cancel Build icon in the main toolbar. When you click this icon, an error message gets printed to the top row of the Compiler Log window.

Ways to rebuild source files:

  • Select one or more source files in the Navigator, right-click, and click Rebuild (for one file), or Rebuild Selected (for multiple files).

  • Select one or more projects or workspaces in the navigator, and click Rebuild in the toolbar.

  • Select one or more projects or workspaces in the navigator, and choose a Rebuild item from the Build menu.

  • Select one or more projects or workspaces in the navigator, right-click, and choose Rebuild.

18.6.1.3 Understanding Dependency Checking

JDeveloper provides fast yet complete compiling by analyzing dependencies while building. Dependency checking results in fewer unnecessary compiles of interdependent source files, and thus accelerates the edit and compile cycle.

When you compile using JDeveloper, dependency checking is performed whenever you compile with Make. Make uses a dependency file that is automatically created within JDeveloper.

If you compile from the command line, you create or use a dependency file by specifying the following parameter:

javac -make <makedepfile>

18.6.1.4 How to Configure Your Project for Compiling

For each project, you can configure Java compilation options.

To configure project properties for compiling:

  1. Right-click a project in the navigator and choose Project Properties from the context menu.

    The Project Properties dialog appears.

  2. Select the Compiler page.

  3. Select and enter compiler options.

Note:

If you want to have all your project files automatically saved before compiling, specify this in the Environment page of the Preferences dialog.

18.6.1.5 How to Specify a Native Encoding for Compiling

You can specify an encoding scheme to control how the compiler interprets multibyte characters. If no setting is specified, the default native-encoding converter for the platform is used.

Text characters are represented using different encoding schemes. In the Windows environment, these are code pages, whereas Java refers to them as native encodings. When moving data from one encoding scheme to another, conversion needs to be done. Since each scheme can have a different set of extended characters, conversion may be required to prevent loss of data.

Most text editors, including the JDeveloper source editor, use the native encoding of the platform on which they run. For example, Japanese Windows uses the Shift-JIS format. If the source code has been encoded with Shift-JIS and you are compiling it in a US Windows environment, you must specify the Shift-JIS encoding for the compiler to read the source correctly.

JDeveloper supports the character encoding schemes included with your currently installed J2SE.

To set the encoding option, do one of the following:

  1. Within JDeveloper, select Application > Project Properties. In the Project Properties dialog, select the Compiler node.

  2. On the command line, use the javac command with the -encoding option followed by the encoding name.

  3. Choose an encoding name in one of the two following ways:

    • Select a name from the Character Encoding dropdown list.

    • Select "default" from the Character Encoding dropdown list to use the default encoding of your environment.

The Java SDK supported encodings are listed at http://download.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html

18.6.2 Compiling Applications and Projects

JDeveloper uses the Java Compiler (Javac) to compile Java source code (.java files) into Java bytecode (.class files). The resulting bytecode is the machine code for a Java Virtual Machine (JVM). Compiling a Java source file produces a separate class file for each class or interface declaration. When you run the resulting Java program on a particular platform, its JVM runs the bytecode contained in the class files.

Javac compiles the specified Java file and any imported files that do not have a corresponding class file. Unless dependency checking is specified (with the -make option), the compiler compiles all of the target Java files. For more information, see Section 18.6.1.3, "Understanding Dependency Checking."

When you work inside JDeveloper, the compiler used is Javac. You can adjust compiler options in the Project Properties > Compiler > Option.

The following command line options are supported:

-classpath path

The path used to find classes. It overrides the default CLASSPATH or the CLASSPATH environment variable. Directories are separated by semicolons. For example, to search for the class foo.java in the myclasses directory, you would enter the following:

javac -classpath c:\mydir;c:\jdeveloper\myclasses foo.java (Windows)
javac -classpath ~/mydir;/usr/jdeveloper/myclasses foo.java (UNIX)

If you are using the Java 2 platform (the default target is JDK 1.6), then the SYSTEM CLASSPATH is prepended to the CLASSPATH. For the above example, SYSTEMCLASSPATH would look similar to the following:

Windows

%JAVAHOME%\jre\lib\rt.jar; %JAVAHOME%\jre\lib\i18n.jar; %JAVAHOME%\jre\lib\sunrsasign.jar;
%JAVAHOME%\jre\lib\jsse.jar; %JAVAHOME%\jre\lib\jce.jar; %JAVAHOME%\jre\lib\charsets.jar;
%JAVAHOME%\jre\lib\classes; c:\mydir; c:\jdeveloper\myclasses

UNIX

$JAVA_HOME/lib/rt.jar;
$JAVA_HOME/lib/i18n.jar;
$JAVA_HOME/lib/sunrsasign.jar;
$JAVA_HOME/lib/jsse.jar;
$JAVA_HOME/lib/jce.jar;
$JAVA_HOME/lib/charsets.jar;
$JAVA_HOME/lib/classes;
~/mydir;
/usr/jdeveloper/myclasses 

If JAVAHOME is not defined, then the JDK defined by the SetJavaHome in jdev.conf will be used. If there is no JAVAHOME, then the JDK in the <jdev_install>/jdeveloper/jdk will be used (if present).

If the target JDK is 1.6 (by using -target 1.6), the SYSTEM CLASSPATH is appended to the CLASSPATH. For the above example it would then look similar to the following:

Windows

c:\mydir;
c:\jdeveloper\myclasses
%JAVAHOME%\lib\classes.zip
%JAVAHOME%\classes

UNIX

~/mydir;
~/usr/jdeveloper/myclasses
$JAVAHOME/lib/classes.zip;
$JAVAHOME/classes

To change the SYSTEMCLASSPATH use option -sysclasspath or option -bootclasspath.

-sourcepath pathlist

A semicolon-separated list of paths used to locate required Java files.

-sysclasspath pathlist

A semicolon-separated list of paths used to find the system class files.

-bootclasspath pathlist

Equivalent to -sysclasspath.

-d outdir

The root directory of the class (destination) file hierarchy. For example:

javac -d C:\JDeveloper\myclasses JavaBean.java (Windows)

javac -d ~/usr/jdeveloper/myclasses JavaBean.java (Unix)

causes the class files for the classes defined in the JavaBean.java source file to be saved in the directory C:\JDeveloper\myclasses\MyPackage, assuming that JavaBean.java contains the package statement MyPackage.

Java files are read from the SOURCEPATH and class files are written to the CLASSPATH directory. The destination directory can be part of the CLASSPATH. The default destination matches the package structure in the source files and starts from the root directory of the source.

-deprecation:self

Detects usage of deprecated types, fields, and methods within the class they are defined in.

-encoding name

You can specify a native-encoding name (or code page name) to control how the compiler interprets characters beyond the ASCII character set. The default is to use the default native-encoding converter for the platform. For more information, see Section 18.6.1.5, "How to Specify a Native Encoding for Compiling."

For example,

javac -encoding SJIS JavaBean.java

compiles JavaBean.java and any directly imported Java files that do not have class files. Characters in all source files are interpreted as the Shift-JIS character set for Japanese.

-endorseddirs pathlist

Allows you to override the default value for java.endorsed.dirs, the default endorsed standards JDK classes provided by Sun. In pathlist, separate path names with semicolons.

-exclude classname(s)

This option allows you to specify class names to exclude from your build. The compiler will ignore all calls to public static void methods of the specified class(es). This is useful mainly for diagnostics where your non-production application build may contain code that will need to be compiled in the official production build. More than one class may be excluded by separating them with semicolons or specifying -exclude more than once. For example: -exclude p1;p2;p3 -exclude p4 will exclude four classes, p1, p2, p3, and p4.

Note:

This option is also supported in the JDeveloper IDE, on the Compiler - Options page of the Project Properties dialog.

Example 18-3 contains example code that uses the -exclude option.

Example 18-3 -exclude option

// beginning of excludeTest.java
public class excludeTest
{
 public static void main(String argv[])

{
 diag.Trace("Application is about to start");
 System.out.println("Test successful"); 
 diag.Trace("Application is about to end");
  }
}
class diag
{
 static void Trace(String msg)
  {
 System.out.println(msg);
 }
}
// end of excludeTest.java

When compiling the application in Example 18-3 without the -exclude option, the output is:

Application is about to start
Test Successful
Application is About to End

When compiling with the following -exclude option:

javac -exclude diag excludeTest.java

the output becomes:

Test Successful

and successfully ignores all calls to diag.Trace.

-extdirs pathlist

A semicolon-separated list of paths that overrides the location where the compiler looks for extensions.

-g

Generates debugging information in the class file. It is required to access local variables and other information while debugging the class.

-g:none

Forces the compiler not to generate debugging information in the class file.

-g:source,lines,vars

Generates selective debugging information in the class file.

-help -?

Displays the options for the compiler.

-make depfilename

Uses the named dependency file for dependency checking. If the specified file is not found, it will be created.

-msglimit:#

Maximum number of errors and warnings written to output. Use -1 to represent no limit. The default is 1000.

-noquiet

Displays file names as they are compiled.

-nowarn:<id>

When specified with an argument, suppresses the warning associated with the number entered by the user.

-nowarn:486

Suppresses unused import statements.

-nowarn:487

Suppresses partially used import statements.

You can also use -nowarn in combination with -warn:

-nowarn -warn:487

to output warnings only for warning 487.

-nowrite

Compiles the program without outputting class files.

-p packagename(s)

Compiles all the source files found in the specified package(s)

-rebuild

Rebuilds specified files regardless of dependencies. Rebuild is assumed unless the -make option is used.

-recurse [level]

Instructs the compiler to recursively descend into directories when expanding file name specifications containing wildcards.

For example:

javac -recurse foo/*java

might be the equivalent to entering:

javac foo/bar/*java foo/lish/*java foo/lish/lee/*java 

The option [level] takes an optional integer argument specifying the maximum recursive level.

For example:

javac -recurse 1 foo/*java 

might be the equivalent to entering:

javac foo/bar/*java foo/lish/*java

Note that foo/lish/lee/*java would not be within the scope of the [level] variable.

-s sourcefile

Compiles the specified source file name(s).

-source {1.1|1.2|1.3|1.4|1.5|1.6}

By default, the source is compatible with J2SE 1.5, which enables J2SE assertions in the source code. You can enter -source 1.4 if you want the source compatibility to be J2SE 1.4.

-strictfp

Forces the compiler not to use extended precision for intermediate floating point calculations.

-target [1.1|1.2|1.3|1.4|1.5|1.6]

If the target is set to 1.1, the compiler compiles for JSDK 1.1. If the target is set to 1.2, the compiler compiles for Java 2 (JSDK 1.2). If the target is set to 1.3, the compiler compiles for Java 2 v1.3 (J2SE 1.3). If the target is set to 1.4, the compiler compiles for Java 2 v1.4 (J2SE 1.4).

The default target is JDK 6 (J2SE 1.6), consistent with Sun's javac defaults

-verbose

This option gives more information about compiling, such as which class files are loaded from where in the CLASSPATH. You get information about:

  • Which source files are being compiled

  • Which classes are being loaded

  • Which classes are being loaded

-verbosepath

This option displays SOURCE PATH and CLASSPATH values used by the compiler.

-warn:<id>

This option allows you to specify warnings. You can have any number of warnings in combination with any suppressed warnings. When used with no arguments, all warnings are displayed. Two useful warnings:

-warn:486

Displays Unused Import Statement

-warn:487

Displays Partially used Import Statement.

-warningtag tag[, tag]

A list of javadoc comment tags. If listed tag occurs in source comment, a warning is output. Use a comma to separate tags names.

18.6.2.1 Compiling from the Command Line

You have two ways to compile applications (workspaces) and projects:

  • Inside JDeveloper by using the various Build and Compile options on the application and project nodes

  • From the command line by using ojmake and ojdeploy.

You can find both in the jdeveloper/jdev/bin directory.

  • ojmake can be used for applications and projects that don't involve any deployment, for example, projects with no deployment profile defined.

  • ojdeploy can handle the build of any application and project (including any that involve deployment). You can think of it as a super-set of ojmake.

You can view help for the tools simply by executing ojmake or ojdeploy on the command line. The help will display in the console.

Note:

When you work from the command line, it is possible to use Javac to compile Java files, but it's not possible to build applications and projects by executing Javac manually. You must use ojmake or ojdeploy.

18.6.3 Cleaning Applications and Projects

You can clean your application or project using the Clean command. Running this command cleans the output and deploy directories in your project or application.

Running the Clean command on an application or project removes all class files, all copied resource files, and all deployed files. You can do this to ensure that there are no outdated files in the output and deploy directories. For instance, classes get renamed, moved, or deleted, and obsolete class files belonging to those classes need to be removed. Similarly, resources and deployments also get renamed, moved or deleted, and their obsolete copies in the output directory or deployment directory need to be removed. Cleaning enables you to remove previous build artifacts and start afresh.

You can run the Clean command on applications or projects.

When you clean an application:

  • The content in the output and deploy directories of each of the constituent projects in the application are deleted.

  • The content in the deploy directory of the application is deleted.

The content in the deploy directory of the application is deleted.

The following conditions must be satisfied for the Clean command to run successfully:

  • The output directory of the project to be cleaned, or of each of the projects in the application to be cleaned, must be specified.

  • The output location must be specified as a directory, and not a file.

18.6.3.1 How to Run the Clean Command

The Clean command enables you to remove artifacts left over from previous builds in order to begin a fresh build process.

To clean a project:

  1. In the Application Navigator, select the project to be cleaned.

  2. In the Build menu, select Clean project.

  3. In the Cleaning project dialog, click Yes.

To clean an application and all its projects:

  1. In the Application Navigator, select the application you want to clean.

  2. In the Build menu, select Clean All.

  3. In the Cleaning application dialog, click Yes.

18.6.4 How to Run Javadoc

You can generate API references and other documentation directly from the navigator, based upon the properties set for the project in the Javadoc page of the Preferences dialog. The documentation will be generated by the javadoc utility from the code and documentation comments in your files.

To run Javadoc on a package, file, or project:

  1. Select the appropriate node in the navigator.

  2. From the main menu choose Build, then Javadoc.

    The Javadoc is generated in the background. Information and results appear in the Log window. A link in the Log window allows you to add the index.html file to the project.

18.6.5 Building with Apache Ant

Apache Ant is a build tool similar in functionality to the Unix make utility. Ant uses XML formatted buildfiles to both describe and control the process used to build an application and its components. Ant supports cross-platform compilation and is easily extensible. Apache Ant is a product of the Apache Software Foundation. For more information, see the website http://ant.apache.org/index.html.

An Ant buildfile defines targets and dependencies between targets. A target is a sequence of programmatic tasks. When Ant is run to make a target, it first makes other targets on which it depends, and then executes the target's own tasks.

Ant is integrated into JDeveloper. Ant buildfiles can be added to or created for projects. Ant buildfiles can be edited with the XML Source Editor. Ant can be invoked from the user interface to make targets defined in buildfiles.

Ways to run Ant on buildfile targets:

  • On targets in the project buildfile. A project can contain several Ant buildfiles, but one can be designated as the project buildfile. You can configure the Run Ant on project toolbar icon and dropdown menu to give easy access to the project buildfile's targets.

  • From the Structure pane when editing an Ant buildfile. When an Ant buildfile is open in an XML source editor, its targets are listed in the structure pane. You can select these and run them.

  • From external tools you define. Use the Create External Tool wizard to define menu items and toolbar buttons that make Ant targets.

18.6.5.1 Running Ant on Project Buildfile Targets

You can invoke Ant from JDeveloper's main menu and toolbar to build targets defined in the current project's project buildfile.

A project can contain several Ant buildfiles, one of which can be designated as the project buildfile. You can configure the Run Ant on project toolbar button and dropdown menu to give easy access to the project buildfile's targets.

To select and configure a project's project buildfile, go to the Ant project properties page (choose Application > Project Properties).

Ways to run Ant on targets in the project buildfile:

  • From the toolbar, click Run Ant on project.

    Ant will make the project's designated default target.

  • From the main menu, choose Build > Run Ant on project.

    Ant will make the project's designated default target.

  • From the toolbar Run Ant on project dropdown menu, choose a target.

18.6.5.2 Using the Ant Tool in the IDE

The Ant Log window displays messages specific to the Ant build. Some features of the Ant Log window are:

  • It displays messages generated by an Ant invocation to build one or more targets.

  • In the Ant Log window, messages generated by Ant tasks are linked to the definitions of those tasks in the Ant buildfile, while compilation errors and warnings are linked to the source code that produced them.

  • The color coding indicates the output level of messages.

18.6.6 Building and Running with Apache Maven

Apache Maven is a software project management and comprehension tool. Maven can manage a project's build, reporting and documentation from a central piece of information, the project object model (POM). You can build the project using its POM and a set of plugins that are shared by all projects using Maven, providing a uniform build system.Maven can be extended by plugins to use a number of other development tools for reporting or the build process. For more information about Maven, see http://maven.apache.org/index.html.

18.6.6.1 Understanding the Project Object Model

The Project Object Model (POM) is an XML file that contains information about the project and configuration details used by Maven to build the project. The XML file contains most of the information required to build a project. Configuration information that can be specified in the POM includes the project dependencies, the plugins or goals that can be executed, and the build profiles.

For more information about the Maven Project Object Model, see: http://maven.apache.org/index.html

18.6.6.2 How to Create a Project Object Model

Use options in the New Gallery to:

  • Create a new Apache Maven POM

  • Create a POM for the Application

  • Generate a Maven POM from a Project

To create a POM:

  1. Choose File > New to open the New Gallery.

  2. In the Categories list, expand General and select Maven.

  3. Select an option for creating a POM and click OK.

18.6.6.3 How to Create a Maven POM for a Project

You can create a Maven POM based on an existing project that you select in the Application Navigator. Build elements will be added for multiple source directories. Settings will be added for the Java compiler you have specified for the project.

To create a Maven POM from a project:

  1. In the Application Navigator, select the project that you want to create the POM from.

  2. Choose File > New to open the New Gallery.

  3. In the Categories list, expand General and select Maven.

  4. Select Generate a Maven POM from a Project.

  5. Click OK.

18.6.6.4 How to Generate a Project Object Model from an Application

You generate a new Project Object Model (POM) for the selected application and optionally, a new POM for each project in the application. This generates a top level POM for the application, and a POM for each project.

To generate a POM from a application:

  1. Choose File, then New to open the New Gallery.

  2. In the Categories list, expand General and select Maven.

  3. Select Create a POM for the Application and click OK.

18.6.6.5 Creating a Maven Template

You can create a:

  • Maven Application template that is made of one or more Maven projects.

    This generates an application, a top level Project Object Model file (pom.xml) for the application, and a default pom.xml file for each project.

  • Maven Project template.

    This generates a Java project that includes a default Project Object Model file and Maven Configuration. The Project Object Model file is automatically created during project creation.

To create a JDeveloper Project with a default POM:

  1. Choose File, then New to open the New Gallery.

  2. Select All Items.

  3. Select either Maven Application or Maven Project.

  4. Click OK.

18.6.6.6 How to Run a Maven Project

Use the Application Navigator to locate and run a Maven project.

To run a Maven Project:

  1. In the navigator, locate the project containing the pom.xml file you want to run.

    The pom.xml file is typically located in the Resources folder under the project.

  2. Right-click on the pom.xml file.

  3. In context menu, select Run Goal(s), then select a goal.

    The list of goals that displays in the context menu is set using the Maven: Goals properties dialog.

18.6.6.7 How to Change the Maven Version

In the Maven project properties dialog, you can specify which version of Maven to use. Maven version 2.0 and above is supported.

To specify the Maven version:

  1. In the Application Navigator, locate the project whose properties you want to set.

  2. Right-click on the project name.

  3. Select Project Properties.

  4. Select Maven.

  5. Enter the Maven version you want to use in the Specify Maven Version field.

18.6.6.8 How to Set Project Properties

Use the Maven Project Properties dialogs to specify:

  • Which Maven version to use

  • Location of the settings.xml file

  • Location of the pom.xml file

  • Additional classpath entries

  • Dependencies

  • Choices that appear in the Run Goal(s) context menu

  • Java version

  • Environment variables

  • Maven repositories

  • Command line options

To set Maven project properties:

  1. In the Application Navigator, locate the project whose properties you want to set.

  2. Right-click on the project name.

  3. Select Project Properties.

  4. Select Maven.

  5. Select the name of a properties dialog.

18.6.6.9 How to Set Log Window Preferences

You can set the colors of various message text that displays in the messages log when you run a Maven project.

To set Maven preferences:

  1. Select Tools > Preferences.

  2. Select Maven.

18.7 Working with JavaBeans

JDeveloper comes with a set of ready-to-use JavaBeans on the Component Palette. You can also supplement these components by creating new JavaBeans yourself or by installing third-party ones.

JavaBeans Component technology lets you implement your own framework for data retrieval, persistence, and manipulation of Java objects. You can use JavaBeans technology to create reusable software components for building Java applets and Java client applications. In a Java EE application, applets and application clients can communicate with business-tier components directly or indirectly through web-tier components. For example, a client running in a browser would communicate with the business tier through JSP pages or servlets.

Although JavaBeans components are not considered Java EE web components according to the Java EE specification, JavaBeans components are often used to handle data flow between server components and application clients or applets on the client tier, or between server components and a database on the back end.

For more information on JavaBeans, for example, the basic notion of JavaBeans and what makes a bean, see http://download.oracle.com/javase/tutorial/javabeans/. The tutorial also contains lessons on writing a simple bean, bean properties, manipulating events and other topics.

18.7.1 Using JavaBeans in JDeveloper

JavaBeans are the Java building blocks used in the Java Visual Editor to build a program. Each JavaBean represents a program element, such as a user interface object, a data-aware control, or a system facility. You build your program by choosing and connecting these elements.

In order to speed up your UI design work in the future, create JavaBean components such as toolbars, status bars, checkbox groups, or dialog boxes that you can add to the Component Palette and reuse with no (or only minor) modifications

JDeveloper comes with a set of ready-to-use JavaBeans on the Component Palette. You can also supplement these components by creating new JavaBeans yourself or by installing third-party ones.

JavaBeans are objects in the true object-oriented programming (OOP) sense. Because they are true objects, JDeveloper components exhibit the following:

  • Encapsulation of some set of data and data-access functions.

  • Inheritance of data and behavior from a superclass.

  • Polymorphism, allowing them to operate interchangeably with other objects derived from a common superclass.

Each component encapsulates some element of a program, such as a window or dialog box, a field in a database, or a system timer. Visual components must ultimately extend either java.lang.Object or extend some other class that derives from it such as javax.swing.Panel. Non-visual JavaBeans components do not have this requirement.

To be recognized and used in JDeveloper, components must conform to the JavaBeans specification.

To be useful in a program, a JavaBean must provide the means by which it can be manipulated or interact with other components. JavaBeans meet this requirement by defining properties, methods, and events.

All components have properties, methods, and events built into them. Some of the properties, methods, and events that components provide are actually inherited from ancestor classes, which means they share these elements with other components. For example, all UI components inherit a property called background that represents the background color of the component. Each component can also introduce its own unique properties, methods, and events. For example, the Swing Checkbox component has a property called selected that indicates whether or not this component initially appears checked.

18.7.2 How to Create a JavaBean

The first step in developing a bean for reuse is to create the JavaBean class. Using the Create Bean dialog, you can either create a new empty bean or extend an existing class to conform to the requirements of the JavaBeans component model.

To create a JavaBean:

  1. In the Application Navigator, select the project you wish the bean to be added to.

  2. From the main menu, choose File > New, or right-click and choose New.

  3. In the New Gallery, in the Categories tree, expand General and select Java.

  4. In the Items list, double-click Bean.

  5. In the Create Bean dialog, accept the defaults, enter new values, or use the Browse buttons to navigate to an existing package and superclass.

  6. Click OK.

18.7.3 How to Create a BeanInfo Class

The BeanInfo class defines a set of methods that allow bean implementors to provide explicit information about their beans. By specifying BeanInfo for a bean component, you can hide methods, specify an icon for the toolbox, provide descriptive names for properties, define which properties are bound properties, and much more.

When you create a bean and install it on the Component Palette, in most cases you will want its properties and events to appear in JDeveloper's Inspector. If you followed the JavaBeans design and naming conventions while creating your bean, all the properties and events you defined, plus all those inherited from superclasses, appear automatically.

However, you may not use the JavaBeans design and naming conventions, or you may have existing classes that don't use them. In addition, you may not want to give the user of your bean access to every property at design time.

To handle these situations, you can create a BeanInfo class that will provide explicit information about a bean to JDeveloper, rather than having JDeveloper derive the information through automatic introspection. You create this class by extending the SimpleBeanInfo class.

To create a BeanInfo class using the BeanInfo dialog:

  1. In the Application Navigator, select the project you wish the bean to be added to.

  2. From the main menu, choose File > New, or right-click and choose New.

  3. In the New Gallery, in the Categories tree, expand General and select Java.

  4. In the Items list, double-click BeanInfo.

  5. In the Create BeanInfo dialog, choose the bean you want to create a BeanInfo for. The dialog will generate the BeanInfo class name from the bean itself.

  6. Accept the name of the package, or specify a different package to which the BeanInfo should be added.

  7. Click Browse to choose a base class other than SimpleBeanInfo for the BeanInfo that you want to implement.

  8. Click OK to add the new BeanInfo class to your project.

18.7.4 How to Implement an Event-Handling Method

In the Java Visual Editor, you see an event primarily as the event-handling method that must be implemented in the class that contains the component. For example, suppose you want to place a button named button1 into a container called Frame1. In addition, you want something to happen when an end user clicks button1.

To implement the event-handling method

  1. Select button1 in the Frame1 editor.

  2. Navigate to the Event page of the Property Inspector.

  3. Click to the right of actionPerformed (actionPerformed is the event generated when a button is pressed).

    This creates a default action-listener name, which you may edit.

  4. Double-click the name to direct JDeveloper to create the appropriate method and take you to the method body.

  5. JDeveloper switches to the Frame1 source view and inserts an event-handling method into Frame1 that is called when that event occurs.

    The method is called button1_actionPerformed() by default. The body of the method is initially empty.

  6. Add code into the method to respond to the button press.

The end user sees all of the potential events from button1 listed on the Events page of the Property Inspector. As the component writer, you are responsible for creating the component class in such a way that all the events it generates will appear in the Property Inspector. All the end user must do to use your bean is write the code that fills in the event-handling method.

18.7.5 What Happens When You Create an Event-Handling Method

Behind the scenes, JDeveloper also generates additional code in the Frame1.java file to handle the other aspects of event listening:

  1. It generates an anonymous inner class for the action adapter that implements the ActionListener interface.

  2. It instantiates the class in Frame1.

  3. It registers itself as a listener for the button1 event by calling button1.addActionListener().

All of this code is visible in the source, but your primary task is to fill in the event-handling method that the action adapter calls when the event occurs.

18.7.6 Understanding Anonymous Adapters

The particular type of inner-class event adapters that JDeveloper generates by default are known as anonymous adapters. This style of adapter avoids the creation of a separate (named) adapter class. The resulting code is compact.

Example 18-4 contains code that is generated for an action-performed event using an anonymous adapter:

Example 18-4 Code Generated for an Action-performed Event Using an Anonymous Adapter

button1.addActionListener(new java.awt.event.ActionAdapter()
     public void actionPerformed(ActionEvent e) {  
      button1_actionPerformed(e);
     } }}

void button1_actionPerformed(ActionEvent e) {
 // your code to respond to event goes here
}

18.7.7 Understanding Standard Event Adapters

You can control how JDeveloper generates the adapter class by selecting the desired option from the Code Style page of the Project Properties dialog. The standard event adapters have only public- and package-level access, unlike anonymous adapters that have access to all variables in the scope where the adapter is declared.

Example 18-5 contains code that is generated for an action-performed event using a standard class:

Example 18-5 Code Generated for an Action-performed Event Using a Standard Class

// Registers the adapter as a listener to button1.
button1.addActionListener(new Frame1_button1_actionAdapter(this));
...
// Adapter class definition.
class Frame1_button1_actionAdapter extends java.awt.event.ActionAdapter {
   Frame 1 adaptee;

   Frame1_button1_actionAdapter(Frame1 adaptee) {
        this.adaptee = adaptee; 
  }
public voidactionPerformed(ActionEvent e) {
   adaptee.button1_actionPerformed(e);
  }
}
void button1_actionPerformed(ActionEvent e) { 
 // code to respond to event goes here
}

18.7.8 How to Make Standard Adapters the Default for Your Projects

JDeveloper generated the code in Example 18-4 using an anonymous inner class. Example 18-5 contains code that is generated for an action-performed event using a standard class. Both ways of using adapters provide the code to handle action-performed events, but the anonymous adapter approach is more compact.

To make standard adapters the default for your projects:

  1. From the main menu, choose Tools > Preferences.

  2. Select the Java Visual Editor node.

  3. In the Event Settings group, select Standard Adapter as an event-handling option.

  4. Choose OK.

Now JDeveloper will generate standard adapters (as opposed to anonymous, inner classes) for its events.

18.7.9 How to Select an Event-Handling Adapter

When creating a bean for reuse, you will want to define its events. Once you have defined its events, you will want to select an event-handling adapter.

To make standard adapters the default for your projects:

  1. From the main menu, choose Tools > Preferences.

  2. In the Preferences dialog, select the Java Visual Editor node.

  3. On the Java Visual Editor page, under Event Settings, select Standard Adapter as an event-handling option.

  4. Click OK.

Now JDeveloper will generate standard adapters (as opposed to anonymous, inner classes) for events.

18.7.10 How to Create an Event Set

JDeveloper provides the functionality to create a set of custom events and create an EventListener interface and an EventObject class to support those events.

To create an event set:

  1. In the Application Navigator, select the project you wish the bean to be added to.

  2. From the main menu, choose File > New, or right-click and choose New.

  3. In the New Gallery, in the Categories tree, expand General and select Java.

  4. In the Items list, double-click EventSet.

  5. In the Create Event Set dialog, in the Name field, enter the name of the event set.

  6. Specify the events you want to create, edit, or remove in the Notifications field.

  7. Click OK to add the new event set classes to your project.

18.7.11 How to Create a Customizer

For complex beans, JDeveloper gives you the option of creating a customizer. A customizer allows you to modify the appearance and behavior of a bean within an application builder so it meets your specific needs. Sometimes properties are insufficient for representing a bean's configurable attributes. Customizers are used where sophisticated instructions would be needed to change a bean, and where property editors are too primitive to achieve bean customization.

  • A simple customizer can edit the entire component at once. Usually a simple customizer presents a dialog box or panel that lets the user set many properties in the same step.

  • A complex customizer provides an interactive interface to the component user, guiding the user through the steps to customize the component.

For a complex customizer, you might create a wizard that questions the user about how the component should be customized. Based on the user's responses, the customizer edits all affected properties of the component. Whenever a customizer generates an event informing JDeveloper that something happened, JDeveloper generates the appropriate code.

To create a customizer:

  1. In the Application Navigator, select the project you wish the bean to be added to.

  2. From the main menu, choose File > New, or right-click and choose New.

  3. In the New Gallery, in the Categories tree, expand General and select Java.

  4. In the Items list, double-click Customizer.

  5. In the Create Customizer dialog, in the Name field, enter the name of the customizer.

  6. If you want to add the customizer to a package other than the default package of your project, enter the package name in the Package field or click Browse Packages.

  7. If you want the customizer to extend a class other than the default, enter the class name in the Extends field or click Browse Classes.

  8. Click OK to add the new customizer class to your project.

18.7.12 How to Make a Component Capable of Firing Events

When you develop a bean, you must think of all the events that the bean should be able to generate.

To make a component capable of firing events:

  1. Determine what kind of event needs to be fired, and either:

    • Select an appropriate existing event set from the AWT or JFC, or

    • Create a new event set.

  2. Create event registration methods for the component.

  3. Create an event notification/propagation mechanism for the event: fire<yourEventName>Event()

  4. Call the event that is fired and call the event notification mechanism from the key points in your bean where such an event should be sent.

18.8 Refactoring Java Projects

Refactoring is an editing technique that modifies code structure without altering program behavior. A refactoring operation is a sequence of simple edits that transform a program's code but, taken together, do not change its behavior. After each refactoring operation the program will compile and run correctly. JDeveloper provides a collection of automated refactoring operations.

Use refactoring when you modify a program's source code to make it easier to maintain, extend, or reuse. Perform the modification as a series of refactoring steps. After each step you can rebuild and revalidate the program to ensure that no errors have been introduced.

Some examples of simple refactoring operations are:

JDeveloper also provides more sophisticated refactoring operations such as:

If the results of the refactoring operation are not as desired, you can undo the refactoring as you would any editing operation, by pressing Ctrl+Z.

18.8.1 Refactoring on Java Class Diagrams

If you rename or move a class using the in-place edit functionality on a diagram, the source code for the class will be refactored automatically. Renaming or moving a Java package on a diagram will automatically refactor the contents of that package.

Deleting a field, method, or inner class on a diagram will automatically apply the Delete Safely refactoring pattern. For more information, see Section 18.8.4, "How to Delete a Code Element".

To apply a refactoring pattern to a Java class, interface, enum, or member on a diagram, select the class or member on the diagram and choose the refactoring pattern from the Refactoring menu. Where a refactoring pattern is applied in this way, the appropriate dialog is displayed, including the facility to preview the results of the refactoring. For more information, see Section 18.8.6, "Refactoring Classes and Interfaces."

The following refactoring patterns are available for the Java classes, interfaces, and enums on a Java class diagram:

  • Rename

  • Move (applies to both single and multiple selections on the diagram)

  • Duplicate

  • Extract Interface

  • Extract Superclass

The following refactoring patterns are available for the Java fields and methods on a Java class diagram:

  • Rename

  • Move

  • Make Static

  • Pull Members Up

  • Push Members Down

  • Change Method (Java methods only)

18.8.2 How to Invoke a Refactoring Operation

JDeveloper provides a wide range of automated refactoring operations that enable you to enhance code quality in such a way that it does not alter the external behavior of the code, yet improves its internal structure.

To invoke a refactoring operation:

  1. Select a program element in a source editor window, navigator pane, or structure pane.

  2. Right-click on the program element.

  3. Choose an operation from the context menu.

  4. You can also choose Refactor from the toolbar and select a refactoring operation from the drop-down list.

Refactoring context menus reflect the operations that are available in the current context. This is determined by the source element that was at the cursor when you right-clicked. These operations differ from element to element. Therefore, the refactoring context menus contain different items depending on where in JDeveloper you are right-clicking to display the menu.

For example, you can display different context menus containing different refactoring operations by right-clicking on:

  • The structure menu

  • The beginning of the line of a method

  • The method's return type in the IDE

  • The method's name in the IDE

  • A parameter in the method's parameter list in the IDE

If the results of the refactoring operation are not what you want, you can undo the refactoring as you would any editing operation, by pressing Ctrl+Z.

18.8.3 How to Rename a Code Element

While developing your Java application you can easily rename the definition and all references to a package, class, interface, method, field, parameter, or variable. If you wish, you can first generate a preview — a list of the usages that will be replaced. Use the preview to inspect and modify or exclude selected usages, before causing the rest to be renamed.

The scope of a renaming operation is the full scope of the element in the project. Project, class, interface, and member usages are replaced anywhere they appear in the project. Parameters and variables are renamed only in the lexical scope of their definitions: other elements with the same name are not modified.

By default, the operation will be restricted to.java files, excluding comments (but not documentation comment tags that name code elements) and annotations. Usages that are not ambiguous will be replaced. Usages of class and interface names will be replaced if they are fully qualified or if they are named in import statements.

For package, type, and member elements, you can choose to extend the operation to comments or to other files. When extended to comments, replacements will be made in line comments, commented-out code, the bodies of documentation comments, and in annotations. When the operation is extended to other files, text replacements will also be made in project files of types designated as text files in the File Types page of the Preferences dialog. Replacements in comments and other files will be made more aggressively than replacements in Java code.

To rename a code element:

  1. Select the element that is to be renamed in one of the two following ways:

    • In a Java Source Editor, select the name.

    • In a Navigator or Structure pane, select the name.

  2. Invoke the command in one of the two following ways:

    • From the Main menu or the context menu, choose Refactor > Rename.

    • Press Ctrl+Alt-R.

      The Rename dialog opens.

  3. In the Rename To box, enter the new name. The name must be valid and not already in use.

  4. Set the depth of the text substitution.

    • Select Search in Comments to extend the operation to comments, the bodies of documentation comments, and to annotations.

    • (Package, type, and members elements only.) Select Search in Non-Java files to extend the operation to other types of text files in the project.

  5. Select Preview if you wish to inspect the usages that will be replaced before committing to the renaming operation.

  6. Click OK.

    If you selected Preview, to avoid all the usages being modified, finish the renaming operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."

18.8.4 How to Delete a Code Element

While developing your Java application you can safely delete the definition of a class, interface, method, or field. The deletion will not be performed without your confirmation if the element is still in use.

If the element is in use a log showing the usages will be displayed. Use the list to inspect and resolve the usages. If you then confirm the deletion, any remaining usages will remain in the code as undefined references.

To delete a code element:

  1. Select the element that is to be deleted in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a Navigator or Structure pane, select the name.

  2. Invoke the command in one of the following ways:

    • From the Main menu or the context menu, choose Refactor > Delete Safely.

    • Press Alt+Delete.

      The Delete Safely dialog displays while the project files are searched for usages.

  3. If the dialog closes, the element has been deleted. If it remains open after performing its search, the element has unresolved usages.

    • Click View Usages to inspect and resolve the usages. When finished, invoke the command again to delete the element.

    • Click Ignore to delete the element's definition without viewing the usages.

18.8.5 How to Preview a Refactoring Operation

When performing a refactoring operation that may modify many usages, it is useful to preview the usages to identify those that should be modified by hand or be excluded. You have the option, before committing these operations, of having usages listed in the Preview Log window, from which you can inspect and resolve them, and if you wish, commit the operation.

The log displays a collapsible tree of packages and Java files. Under each file, lines of code containing usages are listed.

To view a usage in an Edit window:

Double-click the entry in the log.

To exclude a usage from the refactoring operation:

Right click it and choose Exclude.

To commit the refactoring operation:

  1. If you have made any edits that affect usages, click the Refresh icon in the log toolbar to rerun the usages search.

  2. Click the Do Refactoring icon in the log toolbar.

18.8.6 Refactoring Classes and Interfaces

While developing your Java application you can easily define new classes and interfaces and repurpose existing ones.

18.8.6.1 How to Move a Package, Class, or Interface

When developing your Java application you can easily move a package, class, or interface to a different package. If you wish, you can first generate a preview — a list of the usages that will be replaced. Use the preview to inspect and modify or exclude selected usages, before completing the move.

When moving types, only primary classes and interfaces — those having the same name as their file — can be selected to be moved. In effect the file is renamed, and the definitions of secondary classes and interfaces remain with the primary. Accessibility will be preserved: if other classes in the original package refer to the class being moved, it will be given public access. If the class being moved refers to other classes in the original package, those classes will be made public.

The scope of an operation to move a class or interface is the entire project.

By default, the operation will be restricted to .java files, excluding comments (but not documentation comment tags that name code elements) and annotations. Usages that are not ambiguous will be replaced. Usages will be replaced if they are fully qualified or if they are named in import statements.

You can choose to extend the operation to comments or to other files. When extended to comments, text replacements will be made in line comments, commented-out code, the bodies of documentation comments, and in annotations. When the operation is extended to other files, replacements will also be made in project files of types designated as text files in the File Types page of the Preferences dialog. Replacements in comments and other files will be made more aggressively than replacements in Java code.

To move a class or interface:

  1. Select the package, class, or interface that is to be moved, in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a navigator or in the Structure window, select the name.

  2. Invoke the command in one of the following ways:

    • From the Main menu or the context menu, choose Refactor > Move.

    • Press Ctrl+Alt-M.

      The Move Vehicle dialog opens.

  3. In the Move To box, enter the new package name, or click [...] to navigate to an existing package.

  4. Set the depth of the text substitution.

    • Select Search in Comments to extend the operation to comments, the bodies of documentation comments, and to annotations.

    • Select Search in Text Files to extend the operation to other types of text files in the project.

  5. Select Preview if you want to inspect the usages that will be replaced before committing to the move operation.

  6. Click OK.

    If you selected Preview, to avoid all the usages being modified, finish the renaming operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."

Classes can also be moved in the Application Navigator by dragging multiple classes from one package to another.

18.8.6.2 How to Duplicate a Class or Interface

While developing your Java application you can easily duplicate a class or interface.

Only primary classes and interfaces — those having the same name as their file — can be selected to be duplicated. The duplicated class or interface is added to the same package as the original.

Member names in the new class are given the same name as those in the original, except for those derived from the original class or interface name. When the original name is embedded in a member name, the new name is substituted.

To duplicate a class or interface:

  1. In a Java Source Editor, select the name of the class or interface that is to be duplicated.

    Note:

    Only primary classes and interfaces - those having the same name as their file - can be selected to be moved.
  2. From the Main menu, choose Refactor > Duplicate.

    The Duplicate type dialog opens.

  3. In the Class Name box, enter the new name. You can also specify a new package.

  4. Click OK.

    The new class will be added to the project.

18.8.6.3 How to Extract an Interface from a Class

While developing your Java application you can easily derive a new interface from selected methods and static fields defined in an existing class.

Optionally, you can also generalize declarations — such as the type specifications of parameters, variables, and members — by replacing each type name in the declaration with the new interface name. Not all such declarations can be replaced. For example, the replacement cannot be done for the declaration of a variable that is used in a method invocation, if that method was not extracted into the new interface. The replacements will be done anywhere in the project.

The declaration of the class will be modified to show that it is an implementation of the new interface.

To extract an interface:

  1. Select the class from which the interface will be derived in one of the following ways:

    • In a Java Source Editor, select the class name.

    • In a navigator or in the Structure Window, select the class name.

  2. From the Main menu, choose Refactor > Extract Interface.

    The Extract Interface dialog opens.

  3. In the Package field, enter the name of the package of the new interface.

  4. In the Interface field, enter the name of the new interface.

  5. In the Members to Extract table, select the members that will be included in the new interface.

  6. Select Replace Usages if you want to convert existing declarations that name the class into declarations naming the interface.

  7. Select Preview if you wish to inspect the usages before you commit to the operation. This option is enabled only if you have selected Replace Usages.

  8. Click OK.

    Otherwise, the interface will be created, and no usages will be replaced.

18.8.6.4 How to Extract a Superclass

You can create a superclass based on chosen members of the current class. The superclass will consist of field and method declarations that match the chosen members.

To extract a superclass:

  1. In a navigator, in the Structure window, or in a Java Source Editor window, select the class name.

  2. From the main menu, choose Refactor > Extract Superclass.

    The Extract Superclass dialog opens

  3. In the Package Name box, enter the name of the package to which the new superclass will belong.

  4. In the Class Name box, enter a name for the new superclass.

  5. In the Members to Extract table, select the members that will be included in the new interface.

    If you want a method to be created as an abstract method in the superclass, check the Abstract box against that method. If you want dependencies of a method to be included in the superclass, check the Dependencies box.

  6. Select Replace Usages if you wish to convert existing declarations that name the class into declarations naming the superclass.

  7. Select Preview if you wish to inspect the usages before you commit to the operation.

    This option is enabled only if you have selected Replace Usages.

  8. Click OK.

    If you selected Preview, finish the extraction operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."

    Otherwise, the interface will be created, and no usages will be replaced.

18.8.6.5 How to Use Supertypes Where Possible

While developing your Java application you can easily generalize declarations — such as the type specifications of parameters, variables, and members — by replacing references to the selected class with references to one of its supertypes. Not all such declarations can be replaced. For example, the replacement cannot be done for the declaration of a variable that is used in a method invocation, if that method is not also defined in the supertype. The replacements will be done anywhere in the project.

To generalize declarations:

  1. Select the class or interface whose declarations will be generalized in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a navigator or in the Structure window, select the name.

  2. From the Main menu, choose Refactor > Use Supertype Where Possible.

    The Use Supertype dialog opens.

  3. In the Supertypes table, select the supertype that the declarations will be generalized to.

  4. Select Preview if you want to inspect the usages before you commit to the operation.

  5. Click OK.

    If you selected Preview, finish the extraction operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."

    Otherwise, the substitutions will be made immediately.

18.8.6.6 How to Convert an Anonymous Class to an Inner Class

You can convert an unnamed inner class (an anonymous class) into a named inner class.

To convert an anonymous class into an inner class:

  1. In a Java source editor window, select the declaration of the anonymous class.

  2. From the main menu, choose Refactor > Convert Anonymous to Inner Class.

    The Convert Anonymous to Inner Class dialog opens

  3. In the Class Name box, enter the name to be given to the inner class.

  4. If you want the inner class to be given the static modifier, check the Static box.

  5. To convert the anonymous class into an inner class, click OK.

18.8.6.7 How to Move an Inner Class

You can move an inner class to a newly created class at the top level.

To move an inner class:

  1. Select the inner class name in the structure pane or in a Java source editor window.

  2. On the main menu select Refactor > Move. The Move Inner Class dialog opens.

  3. If you do not want the new top level class to be created with the names already shown in the dialog, overwrite them or select new ones.

  4. To create a new class at the top level with the details shown in the dialog, click OK.

18.8.7 Refactoring Members

While developing your Java application you can easily move member definitions from one class to another.

18.8.7.1 How to Move a Class Member

You can move a class member (for example, a method) to another class.

To move a non-static method:

  1. Select the method name in the Structure window or in a Java Source Editor window.

  2. From the main menu select Refactor > Move.

    If there is at least one suitable target to which the member can move, the Move Member dialog opens. Otherwise, a message box is displayed.

  3. In the Targets panel, choose the class to which the member will be moved.

  4. If you want new names to be used for the method and the parameter in the new location, enter new names into the Method Name and Parameter Name boxes.

  5. Select how usages of the member will be handled after the move.

    • Select Use Delegate to handle usages through a newly created delegating method.

    • Select Replace to replace all usages with new ones that call the moved class member directly.

To move a static method:

  1. Select the method name in the Structure window or in a Java Source Editor window.

  2. From the main menu select Refactor > Move.

    The Move Members dialog opens.

  3. In the Target panel, enter or choose the class to which the member will be moved.

  4. For each member that you want to move, ensure that the checkbox to its left in the Members to Extract list is checked.

  5. If you want the dependencies of a member to also be moved, check the corresponding checkbox in the Dependencies column.

18.8.7.2 How to Change the Signature of a Method

You can change the signature of a method. The signature of a method is the combination of the method's name along with the number and types of the parameters (and their order.)

To change the signature of a method:

  1. Select the method name in the Structure window or in a Java Source Editor.

  2. On the main menu select Refactor > Change Method.

    The Change Method dialog opens.

  3. Make changes to the method name, return type, accessibility and parameters as required.

    If you change the name of the method to one that already exists in the class, you will later see a second dialog. Through this you can opt to replace all usages of the method that you are changing to usages of the existing method.

  4. If you want to create tasks based on the changes you have made and add them to the Tasks window, check the Add tasks to the task window box.

Note:

This feature does not apply to constructors.

18.8.7.3 How to Change a Method to a Static Method

You can assign the static modifier to a method.

To change a method to a static method:

  1. Select the method name in the Structure window or in a Java Source Editor.

  2. On the main menu select Refactor > Make Static.

    If the class is part of a class hierarchy, the Make Static dialog opens. Otherwise, the static modifier is added immediately.

  3. If the Make Static dialog opens:

    • In the Name box, enter or select a name to be used as a reference in the modified method.

      The options listed are derived from local object names.

    • If you want to create a method that cannot be overridden, check the Declare final box.

18.8.7.4 How to Pull Members Up into a Superclass

While developing your Java application you can easily move the definitions of members from a class (the source class) to one of its superclasses (the target class). This operation can be applied to a class only if it has one or more potential target classes in the project. Members cannot be pulled up into library classes. Also, this refactor command is only available for a class that is declared with a superclass clause or a list of implemented interfaces.

By default, when a method is pulled up, its definition is moved from the source class to the target class. You can instead choose to abstract the method, in which case the method definition will remain in the source class, and a declaration for it will be added to the target class. Abstracting a method will convert the target class to an abstract class, if it is not already.

A member that you wish to pull up may have dependencies. A member is a dependency if it is used in the definition of a member that is to be pulled up. Pulling a member up without also pulling its dependencies up will introduce undefined references in the target class. When you select a member to be pulled up, its dependencies will be indicated. You can choose whether or not to pull up the dependencies as well.

When a member declared to be private is pulled up, its access changes to protected.

To pull members up:

  1. Select the class from which the members will be pulled in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a navigator or the Structure window, select the name.

  2. From the main menu, choose Refactor > Pull Members Up.

    The Pull Members Up dialog will open.

  3. From the Target drop-down menu, choose the superclass that will be the target class.

  4. In the Members to Extract table, select the members you want to pull up.

    The members that are the dependencies of the selected members, if any, will be indicated.

  5. In the Abstract column, select the checkbox if you wish the method is to abstracted to the target class.

    Note:

    Members that are to be abstracted do not have dependencies.
  6. In the Dependencies column select the checkbox if you wish to also pull up all of the member's dependencies.

    This selection is transitive. It will cause dependencies of dependencies to also be pulled up.

  7. Click OK.

18.8.7.5 How to Push Members Down into Subclasses

While developing your Java application you can easily move the definitions of members from a class (the source class) to its immediate subclasses (the target classes).

By default, when a method is pushed down, its definition is moved from the source class to the target classes. You can instead choose to leave a method declaration in the source class, converting it to an abstract class, if it is not already.

A member that you wish to push down may have dependencies. A member is a dependency if its definition uses a member that is to be pushed down. Pushing a member down without also pushing its dependencies down will introduce undefined references in the source class. When you select a member to be pushed down, its dependencies will be indicated. You can choose whether or not to push down the dependencies as well.

To push members down:

  1. Select the class from which the members will be pulled in one of the following ways:

    • In a Java Source Editor, select the name.

    • In a navigator or the Structure window, select the name.

  2. From the main menu, choose Refactor > Push Members Down.

    The Push Members Down dialog opens.

  3. In the Members to Extract table, select the members you wish to push down.

    The members that are the dependencies of the selected members, if any, will be indicated.

  4. In the Abstract column, select the checkbox if you wish an abstract definition of the member to be left in the source class.

    This selection is transitive. It will cause dependencies of dependencies to also be pushed down.

  5. Click OK.

18.8.8 Refactoring Expressions

While developing your Java application you can easily convert expressions into named elements.

18.8.8.1 How to Inline a Method Call

You can incorporate the body of a method into the body of its callers and remove the original method. This is known as inlining a method call.

To inline a method call:

  1. In a Java Source Editor, select an instance of the method call that you want to be inlined.

  2. From the main menu select Refactor > Inline.

    • If there is only one call to the method in this class, the change is made immediately.

    • If there is more than one call to the method in this class, the Inline dialog opens.

  3. If the Inline dialog has opened:

    • Choose between inlining only the selected instance of the call or inlining all instances of the call.

    • Click OK.

18.8.8.2 How to Introduce a Field

While developing your Java application you can easily convert an expression into a reference to a field. A new field declaration will be added to the class, and the selected expression will become its initialization. The original expression will be replaced by a reference to the new field.

An expression cannot be converted into a field if its type is void.

To introduce a field:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Field.

    The Introduce Field dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option will not be shown if only a single type is valid.

  4. A suggested name will be shown in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Select an initialization:

    • Select Current Method to put the assignment statement for the field immediately preceding the statement that contains the expression.

    • Select Field Declaration to assign the value to the field in its declaration statement. This option will not be enabled if the expression has a variable or parameter with local scope.

    • Select Constructor to assign the value to the field in the constructor methods of the class. This option will not be enabled if the expression has a variable or parameter with local scope.

  6. Click OK.

18.8.8.3 How to Introduce a Variable

While developing your Java application you can easily convert an expression into a reference to a variable. A new variable declaration will be added to the method, and the selected expression will become its initialization. The original expression will be replaced by a reference to the new member.

An expression cannot be converted into a member if its type is void.

To introduce a member:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Variable.

    The Introduce Variable dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option will not be shown if only a single type is valid.

  4. A suggested name will be shown in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Select Declare final if you wish to add the final modifier to the variable's declaration.

  6. Click OK.

18.8.8.4 How to Introduce a Parameter

While developing your Java application you can easily convert a constant expression in a method body into a new parameter for the method. The expression will be replaced by the new parameter name, the new parameter will be added to the method's parameter list, and in all invocations of the method the expression will be inserted as an additional argument.

Expressions can be introduced as parameters only if they are literals or operations on literals.

This operation is disallowed for methods that implement an interface. Altering the signature of such a method would invalidate the implementation.

To introduce a parameter:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Parameter.

    The Introduce Parameter dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option will not be shown if only a single type is valid.

  4. A suggested name displays in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Select Declare final if you want to add the final modifier to the variable's declaration.

  6. Click OK.

18.8.8.5 How to Introduce a Constant

While developing your Java application you can easily convert a constant expression into a constant reference. The new constant declaration initialized by the expression will be added to the class, and the original expression will be replaced by the name of the constant.

Expressions can be introduced as constants only if they are literals or operations on literals.

To introduce a constant:

  1. In the source editor, select the expression.

  2. From the main menu, choose Refactor > Introduce Constant.

    The Introduce Constant dialog opens.

  3. From the Type drop-down menu choose a type for the field.

    The menu lists all types that are consistent with the expression. This option will not be shown if only a single type is valid.

  4. A suggested name displays in the Name text box.

    You can modify or replace it, or choose another suggestion from the drop-down menu.

  5. Click OK.

18.8.8.6 How to Extract a Method

While developing your Java application you can easily extract part of the body of one method to create another. The extracted code is replaced in the original method with a call to the new method. Local variables and parameters used in the extracted code become parameters of the new method. An assignment made by a statement in the extracted code, if any, will be converted in the original member to an assignment that takes the value of the call to the new method.

To be extractable, a piece of code must satisfy several restrictions:

  • It must consist of a single complete expression, or a sequence of complete statements.

  • It cannot make an assignment to more than one variable whose declaration is external to the selection.

  • It cannot have more than one exit point. An exit point is a statement that throws an exception that is not caught in the selection, a break or continue statement for a loop outside of the selection, or a return statement.

The new method is added to the same class as the original. The new method is declared to be private.

Note:

Only the selected code block gets replaced by the extracted method. Other occurrences of the same code block do not get replaced.

To extract a method:

  1. In the source editor, select the expression or the sequence of expressions that you wish to extract.

  2. From the main menu, choose Refactor > Extract Method.

    The Extract Method dialog opens.

  3. Enter a name for the new method.

  4. In the Parameters list, specify the substitutions that will be made for the local variables and parameters that appear in the selected code:

    • In the Name column replacement names, which are similar or identical to the original names, are proposed. You can select and modify the names.

    • In the Included column, select the proposed parameters that will become the parameters of the new method. Those that you deselect will become uninitialized local variables in the new method.

    • Use the Up and Down buttons to order the parameters

  5. Select static if you want to declare the new method to be static.

    This option is disabled if the method is forced to be static because it is called from a static method, or if it is forced to be non-static because it uses a non-static member.

  6. Click OK.

    The new method is added to the class, and the code you selected will be replaced by a call to the new method.

  7. If you deselected any of the proposed parameters in the Parameters list, edit the new method to initialize its local variables.

18.8.8.7 How to Replace a Constructor with a Factory Method

You can convert a constructor into a factory method.

To convert a constructor into a factory method:

  1. Select the constructor name in the Structure window or in a Java Source Editor.

  2. On the main menu select Refactor > Replace Constructor With Factory Method.

    The Replace Constructor With Factory Method dialog opens.

  3. In the Method Name box, enter a name for the new method.

    A suggested name based on the current class name already appears in the box.

  4. To convert the constructor into a factory method click OK.

18.8.8.8 How to Encapsulate a Field

You can change the fields of a class from being publicly accessible to being accessible only from within the class.

To encapsulate a field:

  1. Select the field name (or its parent class) in the Structure window or in the Java Source Editor.

  2. On the main menu select Refactor > Encapsulate Fields.

    The Encapsulate Fields dialog opens.

  3. In the Fields table, check the box next to each field that you want to be encapsulated.

    In this dialog, you can also specify options for method/field accessibilities and the scope for replacements.

  4. Select how you would like accessors to be replaced as part of the encapsulation.

  5. If you want to create tasks based on the changes you have made and add them to the Tasks window, check the Add tasks to the task window box.

  6. If you want to inspect the changes before you commit to the operation, select Preview.

  7. Click OK.

    If you selected Preview, finish the extraction operation from the Preview log window. For more information, see Section 18.8.3, "How to Rename a Code Element."

18.8.8.9 How to Invert a Boolean Expression

While developing your Java application, you can select a boolean field, parameter or local variable and initialize it with the opposite value. JDeveloper automatically corrects all references to maintain the same code functionality. JDeveloper looks at all fields, parameters and local variables and inverts all usages. This refactoring changes the sense of a Boolean method or variable to the opposite one. A Boolean expression evaluating to true will be false. Likewise, a Boolean expression evaluating to false will be true.

For example, if you have a variable that is enabled and you want to change to change the meaning to disabled, the Invert Boolean menu choice changes usages to disabled.

To invert a boolean method:

  1. In the source editor, select the boolean expression.

  2. Right-click on the expression and choose Refactor > Invert Boolean.

    Table 18-1 contains an example of an inverted boolean expression.

Table 18-1 Invert Boolean Example

Before After

private double a;...public boolean method() { if (enabled){ a =5; return true; } false;

}

private double a;...public boolean method() { if (disabled{ a =5; return false; } return true;}


18.9 Optimizing Application Performance

JDeveloper provides a suite of tools for analyzing the quality and performance of your Java code. Use these tools to improve both the quality of your code and your own programming skills.You can use JDeveloper's Auditing feature to analyze Java code for conformance to programming standards.

Auditing is the static analysis of code for adherence to rules and metrics that define programming standards. Auditing finds defects that make code difficult to improve and maintain. JDeveloper's auditing tools help you find and fix such defects. Code can be audited even when it is not compilable or executable.

You can create and customize profiles, choose the rules to be used, and set parameters for individual rules. Browse the audit rules and metrics to learn more about them. For more information, see Section 18.9.25, "How to Browse Audit Rules, Code Assists, and Metrics."

Developers's audit and metrics features are extensible. Audit and metrics are two facets of a source code analysis and transformation framework that can be customized and extended. The public API for both audit and metrics is the oracle.jdeveloper.audit package.

To audit Java code:

An audit report displays rule violations and measurements organized as a tree. A row of the tree corresponds to either a construct or a violation, and includes any measured values for the construct or theoretical violation. A construct is a method, class, file, project, or workspace.

The following properties are found in the rules:

Default fix

The fix that will be used for violations of this rule are when Apply Default Fix is applied to a construct.

Pattern

A regular expression used as a filter to find unconventional identifiers.

Severity

Use to sort rule violations in the audit report.

Visibility

A threshold based on the accessibility keyword. Violations will be reported only if they occur in classes or methods having at least the chosen visibility.

18.9.1 Understanding Audit Rules

Audit rules are static, qualitative, analyses of code.

In an auditing profile individual rules can be enabled and configured by setting their properties. When a code construct does not satisfy a rule, a rule violation is reported. Some rules define automatic fixes that you can choose to apply.

Table 18-2 Audit Rules

Rule Description

Default Fix

The fix that will be used for violations of this rule are when Apply Default Fix is applied to a construct.

Pattern

A regular expression used as a filter to find unconventional identifiers.

Severity

Use to sort rule violations in the audit report.

Prefix

A regular expression used to find identifiers with unconventional prefix.

Visibility

A threshold based on the accessibility keyword. Violations will be reported only if they occur in classes or methods having at least the chosen visibility.


18.9.2 Understanding Audit Metrics

Audit metrics are static, quantitative analyses of code.

In an auditing profile individual metrics can be enabled and configured. Metrics are configured by setting a threshold: when a code construct exceeds the threshold, an over-threshold measurement is reported in the audit report.

JDeveloper measures the following metrics:

Depth of Inheritance Tree (DIT)

The depth of the inheritance tree of a class. By convention, java.lang.Object has DIT of 1, a class which directly extends java.lang.Object has DIT 2, and so on.

Number of Statements (NOS)

The size, in Java statements, of a method, class, or other construct.

Cyclomatic complexity (V(G))

The branching complexity of a method. Constructs which enclose methods, such as classes and projects, are assigned the maximum complexity measured for an enclosed method. Values above 10 are generally considered problematic.

18.9.3 Using the Auditing Tools

You can use auditing tools to view audit reports and to investigate and correct rule violations and over-threshold measurements. A new tab will be created in the Log window when auditing starts, and the audit report will be displayed in it.

Auditing is the static analysis of code for adherence to rules and metrics that define programming standards. Auditing finds defects that make code difficult to improve and maintain. The JDeveloper auditing tools help you find and fix such defects. Code can be audited even when it is not compilable or executable.

18.9.3.1 Using the Audit Window Report Panel

An audit report is a set of rule violations and metrics measurements presented as a tree organized into constructs. A construct is a method, class, package, file, project, or workspace. If the audit profile includes rules, the table will have a Severity column that shows the designated severity of the constructs. If the audit profile includes metrics, the table will have an additional column for each metric showing the measurements for the constructs.

To sort the report by the contents of a column, click the column header. To reverse the sort order, click again.

18.9.3.2 Using the Audit Window Toolbar

From the Log window toolbar you can perform the operations shown in Table 18-3.

Table 18-3 Audit Window Toolbar Icons

Icon Name Description

Refresh Icon

Refresh

Click to rerun the audit on the same selection with the same profile.

Cancel Icon

Cancel

Click to terminate a running audit. Note that this may give partial results.

Export Icon

Export

Click to open the Export Results Dialog, from which you can save the report to a file. You may save the results in XML, HTML, or plain text.

Expand All Icon

Expand All

Click to expand all the container nodes in the report, exposing all the rows.

Collapse All Icon

Collapse All

Click to collapse all the container nodes in the report, hiding all but the top-level constructs.

Group Constructs By Icon

Group Constructs By

Click to open the Group By dialog, from which you can specify the types of container constructs that will be shown. Grouping by constructs enables you to organize the results better, track defects and violations quickly, and analyze the results easily.

Fix Icon

Fix

Choose a fix for a rule violation from the dropdown menu. For an individual rule violation, choose among the fixes defined for that violation's type. For a group construct, the only choice is Apply Default Fixes, which applies the default fix defined for its type, if any.

Show Over Threshold Only Icon

Show Over Threshold Only

Toggle the display of measurements that are within acceptable limits. The threshold is a settable property of metrics.


18.9.3.3 Using Filters

You specify filters to prune the set of Java classes whose violations are shown. You can filter by package names, class names, or both. A filter consists of one or more patterns separated by commas.

A pattern can contain the following special characters:

  • * matches any number of characters

  • ? matches any single character

  • ! at the beginning of a pattern denotes an exclusion pattern

The set of classes that passes a filter is determined by considering the patterns in order. A non-exclusion pattern adds all classes that match the pattern to the set, an exclusion pattern removes all classes that match the pattern from the set. Table 18-4 contains the filters you can specify

Table 18-4 Filters

Name Description

Package

Enter filter patterns that will apply to all but the last element of fully qualified class names. If this field is empty it has no effect.

File

Enter filter patterns that will apply only to the last element of fully qualified class names. If this field is empty it has no effect.

Apply

Click to apply the given Package and File filters to the report's rows.

Clear

Click to erase the Package and File filters, and to restore the report's rows.


18.9.3.4 Using the Audit Window Context Menu

Select one or more constructs (container nodes) or rule violations (leaf nodes) and right-click to open the context menu. From the context menu you can perform the operations shown in Table 18-5 on the selected constructs or rule violations.

Table 18-5 Audit Window Context Menu Items

Name Description

Apply Default Fixes

Choose to apply the default fix, if any, to each selected rule violation or to all the violations in the selected constructs. You can define the default fixes using the Tools > Preferences > Audit: Profiles page.

Apply <Fix>

Choose to apply this fix to the selected rule violation in the construct.

About <Rule>

Choose to display an explanation of the rule that applies to this rule violation.

Hide <Rule> Violations

Choose to remove all violations of the selected rule from the report.

Show Hidden Violations

Choose to restore all previously hidden violations.

Show Over Threshold Only

Click to toggle the display of measurements that are within acceptable limits.

Cancel

Choose to terminate a running audit.

Refresh

Choose to rerun the audit.

Group By

Choose to open the Group By dialog, from which you can specify the types of container constructs that will be shown.

Expand All

Click to expand all the container nodes in the report, exposing all the rows.

Collapse All

Click to collapse all the container nodes in the report, hiding all but the top-level constructs.

Go to Source

Choose to open the source file at the point of the rule violation. If you wish, you can edit the file and correct the violation.

Export

Choose to open the Export Results Dialog, from which you can save the report to a file.


18.9.4 How to Audit Java Code in JDeveloper

JDeveloper's auditing tools help you find and fix defects that make code difficult to improve and maintain. You can audit code even when it is not compilable or executable. The focus of an audit is defined by a profile, which is a set of audit rules and metrics.

You can browse the audit rules and metrics to learn more about them. For more information, see Section 18.9.25, "How to Browse Audit Rules, Code Assists, and Metrics."

To audit Java Code:

  1. Create an Audit Profile that specifies the rules, code assists, and metrics used to analyze Java programs. In an Audit Profile, individual rules and metrics can be enabled and configured by setting their properties. When a code construct does not satisfy a rule, a rule violation is reported.

  2. Run the Audit Report.

  3. Inspect the completed Audit Report for rule violation. For more information, see Section 18.9.15, "How to Inspect an Audit Report Violation or Measurement."

    An Audit Report displays rule violations and measurements organized as a tree. A row of the tree corresponds to either a construct or a violation, and includes any measured values for the construct or theoretical violation. A construct is a method, class, file, project, or workspace.

  4. Fix an audit rule violation manually by editing the source, or for some rules, by selecting an automated fix. For more information, see Section 18.9.16, "How to Fix an Audit Rule Violation.".

  5. If you want to run the audit again, you can modify an audit profile by enabling or disabling rules, code assists, and metrics, or by changing their configuration. For more information, see Section 18.9.22, "How to Modify an Audit Profile."

You can save the finished audit report as an XML file or as a formatted HTML or text file. For more information, see Section 18.9.14, "How to Save an Audit Report." Formats are defined by XSL stylesheet files in the /jdev//audit/stylesheets directory (this directory is not created until audit is run). To create a custom format, adapt a copy of one of the predefined stylesheet files, and add it to the directory.

18.9.5 Auditing Java Code from the Command Line

You can audit a workspace, a project, or a source file from the command line by invoking ojaudit.exe, which is included in your JDeveloper installation, in the <jdev_install>/jdeveloper/jdev/bin directory.

Synopsis

ojaudit option... file...

Table 18-6 contains the parameters you can use during the audit.

Table 18-6 Command Line Parameters

Parameter Description

file

The workspace (.jws), project (.jpr), or source (.java) file to be audited.

-classpath path

Set class path for files to audit, if a project is not being audited.

-encoding code

The character encoding for the report. If absent, the character encoding specified for the project is used (see the Compiler page of the project's Project Properties dialog).

-disable rule

Disable rule in profile. To supply multiple values, repeat this option.

-enable rule

Enable rule in profile. To supply multiple values, repeat this option.

-fail severity

Set the issue severity that the Auditor will regard as failure.

-f[ix]

Applies default fixes to the code. This option modifies source files.

-h[elp]

Prints help for the command help and exits.

-o[utput] file

The pathname of the output file. If omitted, output is written to standard output.

-p[rofile] name

(required) The profile to use. It is either one of the profiles defined in JDeveloper (as set in the Audit > Audit Profiles page of the Tools > Preferences dialog), or the path name of an exported Audit profile file.

Case and whitespace are ignored when searching for a matching profile.

-profilehelp

Print defined profile names and exit.

-project file

The project context to use for parameters that are source files. If all parameters are projects or workspaces, this option is not required.

-q[uiet]

Suppresses the copyright message.

-sourcepath path

Set source path for files to audit, if a project is not being audited

-s[tyle] file

The XSLT stylesheet to apply to the report. The name can either be a style sheet defined in JDeveloper, or a pathname to a style sheet file. If absent, the output will be an XML file.

Case and whitespace are ignored when searching for a matching predefined stylesheet.

-stylehelp

Print defined style sheet names and exit.

-title text

The title to use for the report. If absent when -untitled is not specified, a default title will be used.

-untitled

Causes the title to be omitted from the report.

-v[erbose]

Causes all execution messages to be displayed.

-version

Prints the command's version and exits.

-w[orkspace]

The workspace context to use for parameters that are not workspaces. If no workspace is designated, a default workspace is synthesized.

workspace file

Sets workspace context for files to audit.


18.9.6 How to Run Audit to Generate an Audit Report

Developer allows you to audit your Java programs and generate an audit report.

To audit Java code in JDeveloper:

  1. In the Application Navigator, select one or more applications, projects, or Java source files. The Audit command also works for selections from other views, such as editors and the Structure window.

  2. From the main menu choose Build then Audit target.

    The Audit <File, Project, or Application> Dialog dialog appears.

  3. Choose a profile to use in one of the two following ways:

    • From the Profile dropdown menu choose a profile to use.

    • Click Edit to create or modify a profile.

  4. Click Run.

    An audit report appears in the Log window, and the audit begins. If you wish to stop the audit, click the stop icon in the log's toolbar.

18.9.7 How to Audit Serializable Fields That Do Not Have The serialVersionUID

An object is marked serializable by implementing the java.io.Serializable interface, which signifies that the object can be flattened into bytes and subsequently inflated in the future.

There is an identifier called serialVersionUID that enables versioning.

You can run an audit that flags all classes that implement java.io.Serializable but do not also have the serialVersionUID.

To set audit rules

  • From the main menu, choose Tools then Preferences then Audit thenProfiles.

18.9.8 How to Audit Unserializable Fields

An object is marked serializable by implementing the java.io.Serializable interface, which signifies that the object can be flattened into bytes and subsequently inflated in the future.

To turn off serialization on a field of an object, tag the field of the class of the object with the Java's transient keyword. If a class is marked as serializable, but contains unserializable fields that are not marked as transient, then the class is not serializable. You can run an audit to detect these unserializable fields.

To set audit rules:

  • From the main menu, choose Tools then Preferences then Audit then Profiles.

18.9.9 Viewing an Audit report

Audit reports are displayed as tabbed panes of the Log window. Use the audit report to investigate and correct rule violations and over-threshold measurements.

18.9.10 Refreshing an Audit Report

Use refresh to rerun an audit using the same profile. You may wish to perform a refresh after you have made changes and fixes to your code.

To refresh an audit report:

  • Click in the Log Window toolbar, or right-click and choose Refresh.

The Export Audit Results dialog is cleared, and a new audit will begin. If you wish to stop the audit, click in the Log's toolbar.

18.9.11 Organizing Audit Report Columns

You can rearrange the audit report columns to follow your preferred organization.

To organize audit report columns:

  • Drag the column headers left or right to your preferred position.

18.9.12 How to Organize Audit Report Rows

Audit report rows are rule violations or measurements, or groups of violations and measurements. The report is organized as a tree. A row of the tree corresponds to either a construct or a violation, and includes any measured values for the construct or a theoretical violation. A construct is a method, class, file, package directory, project, or workspace.

You can choose the constructs that are shown in the report.

To organize audit report rows:

  1. Click the Group By icon in the Log window toolbar.

    The Group By dialog opens.

  2. Select the constructs you wish to see.

  3. Click OK.

To sort a metrics report:

  • Click a column header to sort rows by that column. To reverse the sort order, click again.

18.9.13 How to Filter Audit Report Rows

You can use a class name pattern filter to hide violations and measurements in classes that do not match the filter.

A filter is a sequence of patterns separated by commas, semicolons, or spaces. A pattern can contain the following special characters:

  • * matches any number of characters

  • ? matches any single character

  • ! at the beginning of a pattern denotes an exclusion pattern

The set of visible classes is determined by considering the patterns in order. A non-exclusion pattern adds all classes that match the pattern to the set; an exclusion pattern removes all classes that match the pattern from the set. Patterns are matched against classnames.

To filter audit report rows:

  1. In the Package box of the audit log window, enter a sequence of patterns that will apply to all but the last element of fully-qualified class names. You can leave this box empty if you specify a File filter.

  2. In the File box, enter a sequence of patterns that will apply only to the last element of fully-qualified class names. You can leave this box empty if you specify a Package filter.

  3. Click Apply.

    The report will be redisplayed to show only the selected rows.

Click Clear to delete text from the Package and File boxes.

18.9.14 How to Save an Audit Report

You can save an audit report as an XML file or as a formatted HTML or text file.

Formats are defined by XSL stylesheet files in the <jdev_install>/jdev/< system>/audit/stylesheets directory (this directory is not created until audit is run). To create a custom format, adapt a copy of one of the predefined stylesheet files, and add it to the directory.

To save an audit report:

  • Click in the Log Window toolbar, or right-click and choose Export.

    The Export Audit Results dialog opens. Choose a title, format, and destination for the report, and click OK.

18.9.15 How to Inspect an Audit Report Violation or Measurement

JDeveloper generates a report of all audit rule violations.

To inspect an audit rule violation:

  1. In the audit report, select the construct you wish to view.

  2. Right-click and choose Go to Source, or double-click the construct.

    An editor for the source file opens with the cursor positioned at the location of the rule violation or the code element measured

  3. Right-click on a violation or anomaly, and select About to learn more about the rule that has been violated

18.9.16 How to Fix an Audit Rule Violation

You can fix an audit rule violation manually by editing the source, or for some rules, by selecting an automated fix.

To manually fix an audit rule violation:

  1. In the audit report, select the rule violation (a leaf node in the Constructs tree).

  2. Right-click and choose Go to Source.

    An editor for the source file opens with the cursor positioned at the location of the rule violation.

  3. Edit the code to correct the cause of the violation.

To apply an automated fix to an audit rule violation:

  1. In the audit report, select the rule violation (a leaf node in the Constructs tree).

  2. Right-click, and choose an Apply <Rule> Fix menu item, if any.

    or

    Click in the Log window toolbar, and choose one of the Apply <Rule> Fix menu items.

18.9.17 How to Fix a Construct's Audit Rule Violations

You can apply automated fixes to all the rule violations in a construct. Default fixes will be applied to each rule violation in the construct that has a Default Fix property with a value other than None.

To fix a construct's audit rule violations:

  1. In the audit report, select the construct (a container node in the Constructs tree.

  2. You can apply default fixes in one of the two following ways:

    • Right-click, and choose Apply Default Fixes.

    • Click in the Log window toolbar, and choose Apply Default Values.

18.9.18 How to Hide Audit Rule Violations

You can suppress the display of all the rule violations of a given type in the audit report. It is not possible to suppress individual rule violations.

To hide audit rule violations:

  1. In the audit report, select a rule violation (a leaf node in the Constructs tree).

  2. Right-click, and choose Hide <Rule> Violations.

    All of the violations of <Rule> are removed from the audit report. The removed rules are not tallied in their parent construct's summaries. Empty constructs are removed if Show Over Threshold Only is enabled. If not, just the violations are removed.

To restore hidden audit rule violations:

  1. In the audit report, right-click to open the context menu.

  2. Choose Show Hidden Violations.

    All of the previously hidden rule violations are restored to the audit report.

18.9.19 How to Hide Audit Report Measurements

Metrics reports display measurements for the constructs in the analyzed code. You can focus the report on over-threshold measurements by hiding the others. The threshold is a settable property of metrics.

To show only over-threshold measurements:

In the Log window toolbar, click the over threshold icon. Click again to show all measurements.

Removed measurements are not tallied in their parent construct's summaries. Empty constructs are removed if Show Over Threshold Only is enabled. If not, just the violations are removed.

18.9.20 Managing Audit Profiles

An audit profile defines the focus of an audit by specifying the rules, code assists, and metrics that will be used to analyze Java code. While several profiles are predefined, you can create others. You can modify an audit profile by enabling or disabling rules, code assists, and metrics, or by changing their configuration.

Certain audit profiles are used by default with some JDeveloper processes and features.

  • The Code Assist profile is used by the Source Editor, Status window, Application Overview, and File List.

  • The Audit While Compiling profile is used at the end of a compile when Audit While Compiling is selected in the Audit page of the Preferences dialog.

  • The Audit Rules profile is the initial default for the Audit command. However, this is not permanent because the Audit dialog remembers whatever profile was last selected.

18.9.21 How to Create an Audit Profile

JDeveloper allows you to specify the rules, code assists, and metrics used to analyze Java programs.

To create an audit profile:

  1. From the main menu, choose Tools then Preferences.

    The Preferences dialog opens.

  2. Choose the Audit - Profiles page.

  3. From the Profile dropdown menu, choose a profile to copy.

  4. Select the rules, assists, and metrics to enable in the new profile. For more information, see Section 18.9.26, "How to Activate and Deactivate Components of an Audit Profile."

  5. Configure the selected rules, assists, and metrics, if desired. For more information, see Section 18.9.27, "How to Set Property Values for an Audit Test."

  6. Click Save As.

  7. Enter a name for the new profile, and click Save.

    Note:

    Names are not case or space sensitive, though case and space are preserved. If the new name differs only in case or space from an existing name, a warning message appears to inform you of this.

    The new profile name is shown in the in the Audit Profiles preferences page's Profile box.

  8. Click OK.

18.9.22 How to Modify an Audit Profile

JDeveloper allows you to modify audit profiles you created to analyze Java programs.

To modify an existing audit profile:

  1. From the main menu, choose Tools > Preferences.

    The Preferences dialog opens.

  2. Choose the Audit - Profiles page.

  3. From the Profile dropdown menu, choose a profile to modify.

  4. Select the rules, assists, and metrics to enable in the new profile. For more information, see Section 18.9.26, "How to Activate and Deactivate Components of an Audit Profile."

  5. Configure the selected rules, assists, and metrics, if desired. For more information, see Section 18.9.27, "How to Set Property Values for an Audit Test."

  6. Click OK.

18.9.23 How to Delete an Audit Profile

To delete an existing audit profile:

  1. From the main menu, choose Tools >Preferences.

    The Preferences dialog opens.

  2. Choose the Audit - Profiles page.

  3. From the Profile dropdown menu, choose a profile to be deleted. (You cannot delete the predefined profiles.)

  4. Click Delete.

    The profile's name will be removed from the Profile box.

  5. Click OK.

18.9.24 How to Import or Export an Audit Profile

You can import or export audit profiles. This would enable you to share profiles, for example, or to maintain a checked in profile used by ojaudit and a nightly build. Audit profiles are imported or exported as XML files.

To import or export an audit profile:

  1. In the Tools menu, select Preferences to open the Preferences dialog.

  2. In the Preferences dialog, open the Audit - Profiles page

  3. Click Import or Export, and select the profile you want to import or export.

18.9.25 How to Browse Audit Rules, Code Assists, and Metrics

Browse the audit tests to learn more about them.

To browse the audit rules:

  1. From the main menu, choose Tools >Preferences.

    The Preferences dialog opens.

  2. Choose the Audit - Profiles page.

  3. Select one of the Rules, Code Assists, and Metrics tabs.

  4. In the list tree in the left panel, select a category.

    A description of the category will be shown in the Explanation box.

  5. Expand the category and select a rule, code assist, or metric, depending on the tab selected.

    A description of the selected item will be shown in the Explanation box, and its properties and settings will be shown in the right pane

  6. Click OK to close the dialog.

18.9.26 How to Activate and Deactivate Components of an Audit Profile

Activate and deactivate rules, code assists, and metrics for an audit profile from the Audit Profiles preferences page while creating or modifying the profile.

To activate or deactivate a rule, code assist, or metric:

  1. Select the project in the Application Navigator

  2. Choose Tools then Preferences - Audit - Profiles page.

  3. In the dialog, select one of the Rules, Code Assists, and Metrics tabs.

  4. In the list tree in the left panel, expand the category.

  5. Click the checkbox for a test to activate or deactivate it.

  6. Optionally, configure the rule, code assist, or metric. For more information, see Section 18.9.27, "How to Set Property Values for an Audit Test."

  7. Click OK when you are done.

To activate or deactivate a category:

In the left-hand list, click the checkbox for a rule category to activate or deactivate all the category's items. Clicking on any item in the category while pressing the Ctrl key achieves the same result.

18.9.27 How to Set Property Values for an Audit Test

To set an audit rule's property values:

  1. Select the project in the Application Navigator.

  2. Choose Tools then Preferences - Audit - Profiles page.

  3. In the dialog, select one of the Rules, Code Assists, and Metrics tabs.

  4. In the list tree in the left pane, expand a category and select an item.

  5. The test's property names and current values are shown in the right panel.

  6. Change the property values by choosing or entering alternative values.

  7. Click OK when you are done.

18.10 Profiling a Project

The profiler gathers statistics on your program that enable you to more easily diagnose performance issues, such as bottlenecks by identifying methods consuming more time, which method is called the most, how memory is used, and what kind of objects are being created.

The Profiler monitors and logs a running program's use of processor and memory resources. It gathers statistics that enables you to more easily diagnose the performance issues and correct the inefficiencies in your code.

JDeveloper offers two kinds of profilers: The CPU Profiler and the Memory Profiler, for local as well as remote profiling.

18.10.1 Understanding Memory Profiler Views

Memory profiling displays which parts of the application are using the most memory. It also enables you to investigate which objects are responsible for holding the most memory. The Memory Profiler displays data in three views: Classes and Allocators for new objects/garbage collection reporting, and the References view for heap snapshots.

The Classes view shows new objects/garbage collection data organized by Java class. It is used to discover which classes allocated the most memory.

The Allocators view shows the threadgroups, threads and methods that created the most memory.

The References view contains a hierarchical display of all classes, objects and references to objects in the application heap at the time of the snapshot.

Profilers are invoked from the Run menu. You can use the Profiler pages of the Edit Run Configuration dialog to specify the mode of profiling you would like to analyze your code.

In the dialog, you can also specify how you want to profile your programs, locally or remotely. To profile your program locally, set Profiler Connection Parameters, and to profile your program remotely, set Remote Profiling Parameters in the Profiler page of the Edit Run Configuration dialog.

18.10.2 Profiling an Application

You can profile your application locally or remotely. In local profiling, you profile your application within JDeveloper by choosing one of the CPU Profile or Memory Profile commands from Run menu, or outside JDeveloper by choosing Attach Profiler from the Run menu. In remote profiling, you run a profiling session remotely. You profile your application external to JDeveloper with, or without, profiler parameters. The application's JVM can be on the same host or on a network.

18.10.3 Configuring Profilers

You can configure options for the CPU and Memory profilers by right-clicking on a project and clicking Project Properties. Click Run/Debug/Profile > Edit > Tool Settings > Profiler to set the options.

18.10.4 Understanding CPU Profiling

You use the CPU Profiler to gather statistics on the performance of your application. The CPU Profiler can be used to test functions of your application, such as startup, initialization, repainting, and compiling.

The CPU Profiler collects sample data on a running application at regular intervals based on the Sample Interval setting, which you can change using the CPU Profiler options page. For more information, see Section 18.10.13, "How to Set Options for the CPU Profiler."

The Profiler provides two CPU profiling options: Sample CPU Time and Count Method Calls. You can use Sample CPU Time to determine the areas of your code which are accounting for the most (or least) execution time. Count Method Calls display which methods are called and the number of times they are called.

Note:

The Profiler does not allow you to sample time and count method calls at the same time. Counting method calls will cost you a high level of CPU time, and also distorts the profiler results.

Counting method calls is the most expensive form of profiling, both in terms of CPU overhead and memory usage, because the process uses extra CPU for every method entry and exit and it collects data for every method that is called during the use case.

The CPU Profiler window displays data that the Profiler returns. It provides several options to view, sort, and organize Profiler results, as well as to begin, label, compare, and end Profiler use cases.

18.10.5 Understanding Memory Profiling

The profiler has two tools for memory profiling: New objects/garbage collection reporting and reference snapshots (also known as heap dumps). Use new objects/garbage collection reporting to find out what parts of an application are using the most memory. Use reference snapshots to find out what objects are responsible for holding the most memory. The options allow you to use both at the same time, but usually you would not need a snapshot unless you have spotted a memory leak, and you would not need another new objects/G.C. report if you are investigating a particular leak.

The Memory Profiler window displays data that the profiler returns. It provides several options to view, filter, sort, and organize Profiler results, as well as to begin, label, compare, and end Profiler use cases

18.10.6 Understanding Profiler Performance

The Profiler itself consumes CPU and memory resources during use. The overhead varies depending on the profiling mode in operation. In general, CPU sampling (with a 20 ms. sample interval) and reference snapshots are the fastest and use the least memory.

Both CPU method call count and memory new objects/garbage collection profiling are much more expensive in terms of CPU and memory in both the Profiler and profilee. This is because they intercept essentially every method call and record per method, per call stack, per thread data.

In the case of reference snapshots, it takes only a few seconds for the Profiler agent to write a snapshot file. All other processing is done outside the application, so memory snapshots have little effect on application performance.

Table 18-7 contains some actual performance times for an application's benchmark.

Table 18-7 Application Benchmark Times

Profile Type Relative Time Time (seconds) Notes

No profiling

1.0

720

 

CPU samples

1.025

738

20ms sample rate

CPU samples

1.29

930

10ms sample rate

Memory new objects/garbage collection

1.56

1125

 

Reference Snapshot

1.02

735

 

Table 18-8 contains the numbers produced by a shorter run:

Table 18-8 Shorter Run Times

Profile Type Relative Time Time (seconds) Notes

No profiling

1.0

30.7

 

CPU samples

1.4

41.8

20ms sample rate

CPU samples

1.7

51.2

10ms sample rate

Method call count

4.6

141.2

With method filter

Method call count

6.6

201.3

No filter


As the Profiler output is essentially the same for both the 10 and 20 ms. sample intervals, the 20 ms. interval is preferable.

The two tables illustrate that while profiling overhead can vary dramatically for different use cases, CPU samples and reference snapshots are always less expensive than the other alternatives.

In JDeveloper, you can profile a usecase in the default allocated 512MB memory, but some use case require a memory of 1GB or more for new objects/G.C. memory profiling.

18.10.7 Understanding Profiler Use Cases

The aim of profiling is to discover those parts of an application that use more resources than desired, and improve them so that optimization of resources can be achieved. The process is to find individual commands, transactions, or sequences of actions that are perceived to be slow, use too much memory or leak memory. You then investigate the cause, make changes intended to improve performance, and then measure again to see if the changes had the desired effect.

In the profiler, we call such a command, transaction, or sequence of actions a use case. The profiler is designed to allow you to isolate meaningful use cases and measure them precisely. By default, the profiler measures nothing until you begin a use case and stops measuring when you end the use case. The data displayed is always relative to a given use case.

The toolbar in the profiler tab indicates the current use case status and provides controls to start and stop use cases and navigate between them.

The Begin Use Case icon in the top left of the toolbar is used to start a new use case. The End Use Case icon beside it is used to stop a running use case. When you start a use case, the End Use Case toolbar icon is enabled and the Begin Use Case toolbar icon is disabled.

If you save an active use case, the use case stops immediately; the End Use Case toolbar icon is disabled, and Begin Use Case toolbar icon is enabled.

Both the begin and end use case controls are disabled when:

  • A use case has ended but is still being processed by the profiler.

  • The profilee application has stopped running.

  • The profiler is no longer connected.

  • You open a saved session.

18.10.8 How to Profile a Project in JDeveloper

The Profiler monitors and logs a running program's use of processor and memory resources. It gathers statistics that enable you to diagnose performance issues and correct the inefficiencies in your code.

The steps for profiling a project are:

  1. Set options for the CPU and Memory Profilers. For more information, see Section 18.10.13, "How to Set Options for the CPU Profiler" and Section 18.10.15.3, "How to Set Options for the Memory Profiler."

    For example, you can specify if you want the Profiler to sample CPU time usage by your application, or to count method calls. Or you can specify if you want the Profiler to report data on new objects and garbage collection, or to provide a heap snapshot.

  2. Start the CPU or Memory Profiler inJDeveloper. For more information, see Section 18.10.14, "How to Start the CPU Profiler."

    You can also run a profiling session remotely. When you start a remote profiling session, the Profiler connects and profiles remote applications as if they were local. For more information, see Section 18.10.16, "Profiling Remotely."

  3. Isolate meaningful use cases in your program and measure them precisely. For more information, see Section 18.10.7, "Understanding Profiler Use Cases."

    The Begin Use Case control in the top left of the toolbar is used to start a new use case. The End Use Case control beside it () is used to stop a running use case. When you start a use case, the End Use Case toolbar icon is enabled and the Begin Use Case toolbar icon is disabled.

  4. Inspect the data that the profiler returns. The Profiler windows provide options to view, filter, sort, and organize Profiler results, as well as to begin, label, compare, and end Profiler use cases.

  5. You can also save the results of your Profiling session for later analysis.

After you have completed your Profiling session, you can then use its statistics to more easily diagnose the performance issues and correct the inefficiencies in your code.

18.10.9 CPU Profiling

The CPU Profiler tabulates and displays statistical data on the performance on your application, either in terms of time usage, or methods called.

The CPU Profiler enables you to profile your code in one of two ways:

  • Sample CPU Time to identify which parts of an application are taking the most time.

  • Count Methods Calls to confirm that methods are being called and how many times they are called.

18.10.10 Understanding CPU Profiler Views

CPU profiling tabulates the processing time spent by each method in your application by displaying Java Platform calls, and counting those method calls. The CPU Profiler displays data in two views: Hotspots and Call Stacks.

The Hotspots view lists all Java platform methods and all methods they call, sorted by time usage in the CPU Profiler's time sampling mode of operation. It also displays the cumulative amount of CPU time spent in each method. During the method call count operation, the Hotspots view shows all the methods and the number of times they were called.

The Call Stacks view, during the CPU Profiler's time sampling mode of operation, lets you view the Java platform methods called in their call hierarchy. In the count method call mode, the Call Stacks view lists the Java platform methods called, sorted by thread group.

18.10.11 Understanding CPU Time Sampling Results

The CPU profiler, when used in time sampling mode, analyzes your program and reports results on CPU time usage. The data is displayed in two views: Hotspots and Call Stacks.

The Hotspots view lists all methods sorted by the value of the time spent in them. The hierarchy beneath each method shows the callers of the method, and in turn, their callers, and so on.

The topmost methods in Hotspots are often just noise; the path that the event dispatcher takes to accomplish a task. You can use the Stack Filter to narrow the view down to only relevant methods. Alternatively, you can use the Edit Filter dialog to enter a find or filter expression that will specify the methods to be displayed.

The Call Stacks view lets you see the methods called in their call hierarchy. That is, each level is called by the level immediately above it. Table 18-9 contains the data columns that display in the Calls Stacks View.

Table 18-9 Profiler Data Columns

Column Description

Name

Displays the fully qualified method names.

CPU%

Displays the percentage of the currently selected data column. For example, if the CPU column is selected, indicated by a downward-pointing triangle, this column is named CPU%. If CPU Shallow column is selected, the column name would be CPU Shallow%.

CPU (ms)

Displays the cumulative amount of CPU time spent in seconds, in each method and all the methods it calls.

CPU Shallow (ms)

Displays the amount of CPU time spent in each method individually.

Blocked (ms)

Displays the cumulative blocked time spent in each method and all the method it calls. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog.

Blocked Shallow (ms)

Displays the blocked time spent in each method. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog.

Wait (ms)

Displays the cumulative wait time of each method and all the method it calls. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog.

Wait Shallow (ms)

Displays the wait time of each method. The column is available if the Collect Blocked and Wait Time checkbox is selected in the Edit Run Configuration dialog.

Elapsed (ms)

Displays the cumulative elapsed time of each method and all the method it calls. The column is available if the Collect Elapsed Time checkbox is selected in the Edit Run Configuration dialog.

Elapsed Shallow (ms)

Displays the elapsed time of each method. The column is available if the Collect Elapsed Time checkbox is selected in the Edit Run Configuration dialog.

I/O (ms)

Displays the cumulative Input/Output time of each method and all the method it calls. The column is available if the Collect IO Time checkbox is selected in the Edit Run Configuration dialog.

I/O Shallow (ms)

Displays the Input/Output time of each method. The column is available if the Collect IO Time checkbox is selected in the Edit Run Configuration dialog.


Note:

If you see more than one top-level method per thread in the Stacks view, the stack depth is too low for your application. To increase the stack depth, you need to update the CPU Profiler options page in the Edit Run Configuration dialog.

18.10.12 Understanding Method Call Counts Results

The CPU Profiler, when used to count method calls, confirms that methods are being called and tells you how many times. Method call counting is useful when you want to know why a particular method is taking too much CPU time. You can use the Profiler's count method call data to analyze the callers to that method, and edit your code appropriately to reduce the number

18.10.13 How to Set Options for the CPU Profiler

You can specify if you want the Profiler to sample CPU time usage by your application, or to count method calls.

To set CPU Profiler options:

  1. In the navigator, double-click the project you want to profile to open the Project Properties dialog.

  2. Click Run/Debug/Profiler.

  3. Click Edit.

  4. In the Edit Run Configuration dialog, set the options as desired on the Tool Settings - Profiler - CPU page.

    You can specify if you want the profiler to sample CPU time or count method calls.

  5. When finished, click OK.

18.10.14 How to Start the CPU Profiler

Starting a CPU profiling session will automatically run your program. Once the CPU profiler window is open, you can begin a use case to profile your application.

To start the CPU Profiler:

  1. In the navigator, select a runnable node, for example, Application1.java.

  2. From the main menu, choose Run > CPU Profile project.

    If no default run target is specified in the Launch Settings page of the Edit Run Configuration dialog (Application menu > Project Properties > Run/Debug/Profile), the Choose Default Run Target dialog opens. Use this dialog to specify the default run target

  3. Click the Begin Use Case icon to begin a profiling use case.

Note:

If you want to profile your application immediately when the profiler is launched, select the Begin Use Case on Application Startup checkbox in the Profiler page of Edit Run Configuration dialog.

18.10.15 Memory Profiling

The Memory Profiler enables you to find out how your program is using the Java heap. You can find inefficient heap usage and any suspect memory behavior.

The profiler has two tools for memory profiling: new objects/garbage collection (hereafter referred to as new/G.C. reporting) and reference snapshots (also known as heap dumps). Note the following points while using these tools:

  • Use new/G.C. reporting to find out what parts of an application are using the most memory.

  • Use reference snapshots to find out what objects are responsible for holding the most memory.

Memory profiling and method call counts, slows down the system and the application considerably. Note the following points of information before you start profiling an application:

  • Keep your use cases specific and short.

  • Wait for the application to start, before you start the use case.

  • When profiling large applications, JDeveloper requires more than the default memory size. If your applications slows down, navigate to <jdev_install>/jdev/bin directory and try launching JDeveloper from command line with the following command:

    jdev -J-Xmx1024m

    This command allocates 1 GB of virtual memory to JDeveloper, overriding the default memory of 512 MB.

  • A web application deployed in Oracle WebLogic Server is considered as a large application. Hence, launch JDeveloper with the -J-Xmx1024m parameter to increase the memory size before you start profiling.

  • Some large applications or use cases may fail when profiled in Windows, try profiling such applications or use cases in Linux. Windows operating systems limit the contiguous virtual memory for JVM, but there is no such limitation in Linux.

18.10.15.1 Understanding Memory Profiler Views

The Memory Profiler displays data in three views: Classes view, Allocators view for new/G.C. reporting, and the References view for heap snapshots.

  • The Classes view shows new objects/garbage collection data organized by Java class. It is used to discover which classes allocated the most memory. You can switch to this view by clicking the Classes tab at the bottom of the Memory Profiler.

  • The Allocators view shows the threadgroups, threads, stacks, and methods that created the most memory. You can switch to this view by clicking the Classes tab at the bottom of the Memory Profiler.

  • The References view contains a hierarchical display of all classes, objects and references to objects in the application heap at the time of the snapshot.

18.10.15.2 Understanding Reference Snapshots

A reference snapshot is a hierarchical display of classes, objects and references to objects in the application heap at the time of the snapshot. There are two fundamental kinds of references: references from JVM garbage collection roots to objects, and references from one object to another.

JVM garbage collection roots include references from an active thread, references from JNI local and global variables, and internal JVM references. These are the references that keep objects in memory; if there is no path from a gc root to an object, it is eligible for garbage collection. The snapshot contains only objects that are reachable from one or more JVM gc roots.

Note that static references and references from class loaders are not garbage collection roots. A class loader can be garbage-collected when there are no more references to the class loader, any classes loaded by the class loader or any objects of these classes. When a class loader is garbage collected, all classes it has loaded are also garbage collected, as well as all objects that are only referred to by static references from these classes.

There are four types of references from objects to objects: normal (strong) references, soft references, weak references and pseudo references. When you are looking for memory leaks, you normally only care about strong references. You can toggle between viewing only strong references, or all references.

New and old references in different snapshots are indicated using different font styles. When you compare two memory snapshots, the methods in the current snapshot show up in boldface font. If there are methods that are also in the other snapshot, they are shown in bold-italic font in the current snapshot.

There are several ways to compare reference snapshots. In the Memory Profiler References view, for example, you can choose Compare With to select a different use case (snapshot) from the current one. Or, if you have two profiler tabs open (for example, if you have opened a saved profile session) select Compare With and Other, then choose a use case from another session.

18.10.15.3 How to Set Options for the Memory Profiler

You can specify if you want the Profiler to sample CPU time usage by your application, or to count method calls.

To set memory profiler options:

  1. In the navigator, double-click the project you want to profile to report data on new objects and garbage collection, or to provide a heap snapshot.

  2. Click Run/Debug/Profiler.

  3. Click Edit.

  4. In the Edit Run Configuration dialog, set the options as desired on the Tool Settings - Profiler - CPU page.

    You can specify if you want the profiler to collect new objects/garbage collection data, take a heap snapshot, or do both.

  5. When finished, click OK.

18.10.15.4 How to Start a Memory Profiling Session

Starting a Memory profiling session also automatically runs your program. Once the Memory profiler window is open, you can begin a use case to profile your application.

To start the Memory Profiler:

  1. In the navigator, select a runnable node.

  2. From the main menu, choose Run > Memory Profile project.

  3. Click the Begin Use Case icon to start the profiling session.

18.10.16 Profiling Remotely

You can run a profiling session remotely. When you start a remote profiling session, the Profiler connects and profiles remote applications as if they were local. Since you still run the Profiler locally, you can profile applications on other computers provided that they have a reachable IP address or DNS name.

The main difference between remote and local profiling is the way in which you begin the profiling session. For local profiling, JDeveloper automatically launches the program that you want to profile (the profilee) and then attaches the Profiler to that program. For remote profiling, you must manually launch that profilee program and attach the Profiler later. Once the profilee is launched and the JDeveloper Profiler is attached to it, remote profiling is no different from local profiling. Remember that you can use remote profiling whether or not the profilee process is running on the same machine as JDeveloper.

Note:

If you are profiling your application remotely, you can start your external application with or without profiler parameters. An application started with profiler parameters can have JVM can be on the same host (local) or on a network. An application started without profiler parameters must have JVM on the same host, and you may attach the profiler later.

Remote profiling and local profiling each have advantages over the other. When you remote profile, the Profiler and profilee can be run on two different computers so that they are not competing for the same resources. However, transferring large amounts of data over a network could make profiler performance significantly slower.

18.10.17 Understanding Profiler Agent Support for JVMs

To profile remotely in JDeveloper, you invoke the profiler agent. The JDeveloper profiler agent supports 32- and 64-bit JVMs in Windows and Linux. You specify a JVM for a project using the Edit Run Configuration - Launch Settings page.

The names of the profiler agent files are based on the supported architecture and JVM size:

  • profiler_x32.dll

  • profiler_x32.so

  • profiler_x64.dll

  • profiler_x32.so

If you launch the profilee from JDeveloper, the profiler automatically detects the size of the JDeveloper JVM.

  • On Linux, it should use API to detect which of 32-bit or 64-bit architecture remote JVM is and use appropriate agent. (This can be generalized to support additional architectures.)

  • On Windows, it should use API to detect which of 32-bit or 64-bit architecture remote JVM is and, if it is not the same as JDev JVM architecture, not show it in the list of available JVMs to attach

If you attach locally and the JDeveloper JVM is 32-bit, the profiler attempts to load the 32-bit agent and if that fails, tries to use the 64-bit agent. If the JDeveloper JVM is 64-bit, the profiler only tries the 64-bit agent.

18.10.18 How to Invoke the Profiler Agent

To profile a program remotely in JDeveloper, you must start the Java process from the command line. From the command line, you also invoke the Profiler Agent. Once the process has started, you can connect the JDeveloper Profiler to the Profiler Agent.

You can invoke the Profiler Agent using the -agentlib or -agentpath option.

To invoke the Profiler Agent using the -agentlib option:

At the command line, enter the following execution string:

java
-agentlib:<Profiler-Agent-Library>=<sub-option1>[=<value1>],<sub-option2>[=<value2>]... -classpath 
 -classpath <Project_Directory>\classes <Java_Main_Class>

Note:

While specifying the -agentlib, you may specify the absolute path of the agent excluding the .dll extension, or add the agent's path to your PATH variable and then specify the agent without absolute path and extension.

Example 1

java
-agentlib:C:\JDeveloper\jdeveloper\jdev\lib\ profiler_x32=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\ profiler-agent.jar,port=4000,enable=t,startup=connect 
-classpath c:\MyApp\MyProject\classes MyMainClass 

Example 2

set PATH=C:\JDeveloper\jdeveloper\jdev\lib;%PATH%

java
-agentlib:profiler_x64=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,port=4000, enable=t,startup=connect 
 -classpath c:\MyApp\MyProject\classes MyMainClass 

To invoke the Profiler Agent using the -agentpath option:

At the command line, enter the following execution string:

java
 -agentpath:<Path_to_Agent_Library>=<option1>[=<value1>],<option2>[=<value2>]...
 -classpath <Project_Directory>\classes <Java_Main_Class> 

where

<Path_to_Agent_Library> is the full path to the profiler_x32.dll or profiler_x64.dll. For example, <jdev_install>\jdeveloper\jdev\lib\profiler_x32.dll.

Note:

While specifying the -agentpath, you must specify the absolute path to the agent including the.dll extension.

Example

-agentpath:C:\JDeveloper\jdeveloper\jdev\lib\ profiler_x32.dll=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\ profiler-agent.jar,port=4000,enable=t,startup=connect,depth=1000,interval=20 
-classpath c:\MyApp\MyProject\classes MyMainClass

Table 18-10 contains the suboptions that are available with the -agentlib and -agentpath options.

Table 18-10 Suboptions

Suboption Description

port=<port>

Specifies the port over which the data will be transferred. Defaults to 4000.

jarpath=<path>

Path to profiler JAR file. This JAR is located at <jdev_install>\jdeveloper\jdev\lib\profiler-agent.jar. If the JAR path is not specified, the JAR must be on bootstrap classpath.

enable=[t][c][m][r]

Enables agent capabilities.

  • t = CPU time sampling

  • m = memory new/gc

  • c = count method calls

  • r = heap reference snapshot

Only one of t, c or m may be specified. r may be specified in combination with m or by itself.

startup=time|mem|count|refs|connect

If a use case is to begin on startup, you may specify one of the following:

  • time - CPU time sampling

  • count - count method calls

  • mem - memory alloc/free

  • refs - heap reference snapshot (may be specified in combination with mem or by itself)

  • connect - waits for connection before allowing application to run

It is not possible to have a use case running unless the profiler is connected.

startup=mem,refs also enables profiler agent's memory and heap reference snapshot capabilities (enable = mr).

depth=<size>

Sets maximum stack depth used for collection. Defaults to 1000.

interval=<sample-interval>

Sample interval in milliseconds. Defaults to 20. This is only applicable to CPU time sampling.

wait=y|n

Report wait and blocked times. Default is n. This is only applicable to CPU time sampling.

refpath=<path>

Sets the path used to write reference snapshot files. Required if enable=r is specified.

The same path is used for all snapshots, so it is important that the file be copied before the next use case ends. The profiler and file client do this automatically.

stackfilter=<expression>

Specifies classes to include or exclude in stack traces. For example:

stackfilter=(!java.lang.*)

This expression will ensure that no reported stack trace contains any class whose name begins with java.lang.*. For example, stack traces with java.lang.Integer and java.lang.reflect.Method not appear. Any time used in such methods is collected and added with the next caller.

methodfilter=<expression>

Collects only stacks containing the specified methods specified in the expression. For example:

methodfilter=(com.mycorp.MyClass.MyMethod*)

This expression will ensure that no stack will appear unless it contains at least one call to com.mycorp.MyClass.myMethod. The * in the filter ensures that methods for any type signature are collected; in Java, there could be more than one method that matches.

memfilter=<expression>

Object classes to include or exclude from memory reports. For example:

memfilter=(!java.lang)

This expression will ensure that no class that contains java.lang in its string will be displayed.


Command line examples

  • java -agentlib:profiler_x32=port=4000, jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,enable=t,depth=1000,startup=time,interval=20 -classpath C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1

  • java -agentlib:profiler_x64=port=4000, jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,enable=m,startup=connect -classpath C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1

  • java -agentlib:profiler_x32=port=4000, jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,startup=connect,mem -classpath C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1

  • java -agentpath:C:\JDeveloper\jdeveloper\jdev\lib\profiler_x64.dll=jarpath=C:\JDeveloper\jdeveloper\jdev\lib\profiler-agent.jar,port=4000,enable=t,startup=connect,depth=1000,interval=20 -classpath C:\JDeveloper\jdeveloper\mywork\Application1\Project1\classes project1.Application1 *

18.10.19 How to Connect the Profiler Remotely to a Java Program

To profile a program remotely in JDeveloper, you must first start the Java program session and invoke the Profiler Agent. For more information, see Section 18.10.18, "How to Invoke the Profiler Agent."

Once the session has started, you can connect the JDeveloper Profiler to it. Connecting the Profiler involves first preparing JDeveloper for remote profiling.

To set up a remote profiling session:

  1. In the Application Navigator, select the project to be remotely profiled.

  2. Select a run configuration and click Edit. For more information, see Section 19.3, "How to Configure a Project for Running."

  3. In the Remote page under Profiler node, select the process type as local or remote.

  4. Click OK when you are done.

  5. Start the Java program session, if you have not already. For more information, see Section 18.10.18, "How to Invoke the Profiler Agent."

To connect remotely:

  1. In the Application Navigator, select the project to be remotely profiled.

  2. From the Run menu, attach the profiler to CPU Profile or Memory Profile, as desired.

  3. In the Attach Profiler to Running JVM dialog, confirm that Attach to Remote Process option is selected and host/port information is correct.

  4. Click OK.

  5. In the Profiler tab, click Begin Use Case to start profiling a use case.

  6. When you are done, detach the profiler. From the Run menu, select Detach.

Note:

The Connect on Application Startup and Begin Use Case on Application Startup checkboxes in the Profiler page of the Edit Run Configuration dialog have no impact if you attach the profiler to a local process. The checkboxes are applicable when you attach profiler to a remote process only.

18.10.20 How to Dynamically Attach and Detach the Profiler To a Running Process

JDeveloper allows you to dynamically attach and detach a profiler to a running process. This is similar to profiler attached remote profiling, but doesn't require you to specify profiler parameters on the command line when you launch the application. For example, if you are running an application with no plan to profile it when you started it, but later you wish to profile it because it is exhibiting some performance problems. In such a scenario, dynamically attaching a profiler to a running process saves you from restarting your JVM to attach a profiler to it.

Dynamically attaching a profiler has its limitations too. You can do CPU time sampling or take memory reference snapshots (heap dumps), but you cannot do method call counts or new/gc memory profiling as they require byte code instrumentation, which can only be requested on the command line before the JVM is launched.

To dynamically attach/detach the profiler to a running process:

  1. Start the program outside of JDeveloper, for example, in a different command window.

  2. Open JDeveloper and open the Attach Profiler to Running JVM dialog (Run > Attach Profiler > CPU Profile or Memory Profile).

  3. In the Attach Profiler to Running JVM dialog, select the Attach to Local Process option.

  4. From the list of JVMs, select the program's JVM running on the local system.

  5. Click OK. The profiler connects to the running JVM.

To detach profiler from a running process, select Detach from the Run menu. If you disconnect the profiler by closing the Profiler tab, you cannot reattach to it. To reattach later, you must use Detach command.

To reattach the profiler to a process:

You can detach and attach the profiler to a process as many times as you want, but you must remember the following points before reattaching:

  • Ensure that profiler is detached before reattaching it again.

  • When you reattach the profiler, you start a new profiler session, and the data of previous session is lost. To save data of previous session, select Save As from the File menu.

When you reattach profiler to a process, you can change your configuration settings and reattach with the new configuration settings. For example, if you are profiling CPU, you can change CPU configuration to enable or disable collect I/O time, CPU time, wait time, and so on. If you are memory profiling, you can reattach profiler to take heap dumps. You can also switch back and forth between CPU profiling and memory profiling.

However, you cannot reattach if you change your CPU profiling configuration to count method calls, or memory profiling configuration to New/gc. These require capabilities the profiler cannot acquire after the application starts running. To do either of these, you must launch the application with appropriate profiling parameters and attach profiler using the Attach to Remote Process command.

18.10.21 How to Set Profile Points

The Profile Points allow you to set a method filter on a method or class. This means that only stacks that contain those methods, or classes, are reported by the profiler. It is used to filter data so you only see a method, what calls it, and what it calls.

To set a profile point:

  1. pen the file in the source editor, and right-click in the left margin next to a line of executable code.

  2. From the context menu, choose Toggle Profile Point. The profile point icon is displayed on the left margin of the parent class or method name.

Disabling a Profile Point

You can disable a profile point in any of the following ways:

  • In the source editor, right-click the profile point symbol in the left margin and choose Disable Profile Point.

  • In the Profile Point window (View > Profile Points) right-click the profile point you want to disable and choose Disable.

  • To disable all current profile points, right-click in the Profile Points window, and choose Disable All from the context menu.

Deleting a Profile Point

When you no longer need to examine the code at a profile point location, you can delete the profile point. You can delete a profile point in any of the following ways:

  • In the source editor, right-click the profile point symbol in the left margin and choose.

  • In the Profile Point window (View, then Profile Points) right-click the profile point you want to remove and choose Delete.

  • To remove all current profile points, right-click in the Profile Points window, and choose Delete All from the context menu.

18.10.22 Saving and Opening Profiler Sessions

The profiler allows you to save output for later viewing and analyzing.

To save a running profiler session to disk, in the File menu, select Save As. In the Save As dialog, enter an appropriate name to describe your session, for example, uianalysis.opr, or accept the default.

Note:

If you are saving an active use case, it will be automatically terminated. The End Use Case toolbar icon is disabled, and Begin Use Case toolbar icon is enabled.

To open a saved profiler session, in the File menu, select Open, and navigate to the session you want to view.

A saved session is visually distinguishable from an active session by its unique profiler icon. In a saved session, the use case begin and end icons are disabled, but the use case navigation controls are active when multiple use cases are available.

18.10.23 How to Open HPROF Format Heap Dumps

JDeveloper allows you to open heap dumps in HPROF binary format and display them in the profiler. HPROF binary format heap dumps can be created by the HPROF profiler, by the JDK tools jmap and jconsole, or through the Java parameter -XX:+HeapDumpOnOutOfMemoryError.

For example, to create the HPROF file using the jmap command, you could enter on the command line:

jmap -dump:format=b,file=heap.hprof <jdev process id>

For more information about HPROF, see http://java.sun.com/javase/reference/index.jsp

To open HPROF Binary File:

  1. From the File menu, select Open.

  2. Browse and select the HPROF binary format file, and then click Open.

The heap dump opens in the profiler References editor tab.

Note:

Opening large heap dumps is a slow process and may take several minutes to open. The Writing output... progress item, which appears when file open process is approximately halfway done, indicates that the heap dump file is valid and will open for viewing.

18.11 Modeling Java Classes

A Java class diagram allows you to visually create classes, interfaces, enums, and inheritance and composition relationships, and to view existing Java classes and interfaces. If you want to visualize a particular facet of your application, add only the classes that contribute to that aspect to the diagram.

To model Java classes you should start with a Java class diagram, although you can subsequently add other elements to the diagram. For more information, see Section 18.11.10, "How to Create a Diagram of Java Classes." You can create and modify the classes that comprise your application directly through the diagram. Changes made on the Java class diagram are immediately available in the Java source editor, and vice versa.

18.11.1 Modeling Dependencies

Dependencies are represented on the diagram as a dashed line with an open arrowhead in the direction of the dependency and are used for documentation purposes only and do not change the underlying Java code.

18.11.2 Creating Java Classes, Interfaces, and Enums

Java classes, interfaces, or enums are created on a diagram by clicking on the Java Class icon, Java Interface icon or Java Enum icon on the Java Component Palette for the diagram, and then clicking on the diagram where you want to create the class. The Java source file for the modeled class or interface is created in the location specified by your project settings.

Java Class, Java Interface, and Java Enum icons are represented on a diagram as rectangles containing the name and details of the Java class. Java classes and interfaces are divided into compartments, with each compartment containing only one type of information.

An ellipsis (...) is displayed in each compartment that is not large enough to display its entire contents. To view a modeled class so that all the fields and methods are displayed, right-click the class and choose Optimize Shape Size, then Height and Width.

Each type of class on a diagram is identified by a stereotype in the name compartment. This is not displayed by default.

Members (fields and methods) display symbols to represent their visibility. The visibility symbols are: + Public, - Private, # Protected. If no visibility symbol is used, the field or method has package visibility.

18.11.2.1 Modeling Java Interfaces

An interface is normally used to group together method signatures for groups of methods that together define a coherent service. Classes that want to provide the service defined by an interface do this by implementing the interface. Interface names must be unique within a namespace. Because interfaces can be used to specify a set of services that other classes provide, they can be used to enforce some level of consistency on those other classes.

Note:

Modeled Java interfaces can inherit from other interfaces using extends relationships.

For more information, see Section 18.3.6, "How to Create a New Java Interface."

18.11.2.2 Modeling Inner Java Classes and Inner Java Interfaces

A diagram can include primary or inner classes from different packages, the current application, or from libraries. Inner Java classes and inner interfaces are defined as members of their 'owning' class. Hence, they are also referred as member classes.

Inner classes and inner interfaces are displayed in the inner classes compartment of the modeled Java class or interface on the diagram. Inner classes are prefixed with the term Class, and inner interfaces are prefixed with the term Interface, between the visibility symbol and the class or interface name.

To create an inner class or inner interface on a modeled Java class or interface, either add the inner class to the implementing Java code, or create a new Java class or interface as an internal node on an existing modeled class.

Inner Java classes and inner Java interfaces cannot have the same name as any containing Java class, Java interface or package or contain any static fields or static methods.

18.11.2.3 Modeling Enums

Enumerated types, or enums, containing fields and methods, can be created on a diagram. Enumerated types cannot implement interfaces, extend other classes, or be extended by another class.

18.11.3 Modeling Composition on a Java Class Diagram

A variety of references (previously referred to as associations) can be created quickly between classes and interfaces on a diagram using the various reference icons on the Java Class component palette for the diagram. References created between modeled Java classes are represented as fields in the source code of the classes that implement the references. Compositional relationships are represented on the diagram as a solid line with an open arrowhead in the direction of the reference. Table 18-11 displays the references that can be modeled on a diagram.

Table 18-11 References Between Classes or Interfaces

Reference Description

Reference (Object)

A singular, direct reference from one class or interface to another. This is represented in the code of the reference's originating class as a field of type <destination_class>.

Reference (Array)

A reference to an array of another class or interface. This is represented in the code as an array of type <destination_class>.

Reference (Collection)

This is represented in the code as a Collection declaration, and adds an @associates <{type}> Javadoc tag to the source to identify this reference as well as the required import java.util.Collection; statement.

Reference (List)

This is represented in the code as a List declaration, and adds an @associates <{type}> Javadoc tag to the source to identify this reference as well as the required import java.util.List; statement.

Reference (Map)

This is represented in the code as a Map declaration, and adds an @associates Javadoc tag to the source to identify this reference as well as the required import java.util.Map; statement.

Reference (Set)

This is represented in the code as a Set declaration, and adds an @associates Javadoc tag to the source to identify this reference as well as the required import java.util.Set; statement.


Note:

If you want to quickly change the properties of a reference on a diagram, double-click it to display the Code Editor and change the details of the reference.

Labels are not displayed on references by default. To display the label for a reference, right-click the reference and choose Visual Properties, then select Show Label. The default label name is the field name that represents the reference. If you select this label name on the diagram and change it, an @label <label_name> Javadoc tag will be added before the field representing the reference in the code.

You can change the aggregation symbol used on a reference on a diagram by right-clicking the reference, choosing Reference Aggregation Type, then choosing None, Weak (which adds an @aggregation shared Javadoc tag to the code representing the reference), or Strong (which adds an @aggregation composite Javadoc tag to the code representing the reference). Aggregation symbols are for documentary purposes only.

18.11.4 Modeling Inheritance on a Java Class Diagram

Inheritance structures, which are represented in the Java source as extends statements, can be created on a diagram of Java classes using the Extends icon on the Java Class Component Palette for the diagram. Extends relationships are represented on the diagram as a solid line with an empty arrowhead pointing towards the extended class or interface.

Where an interface is implemented by a class, this can be created using the Implements icon on the Java Component Palette for the diagram. Creating an implements relationship adds implements statement to the source code for the implementing class. Implements relationships are represented on the diagram as a dashed line with an empty arrowhead pointing towards the implemented Java interface.

18.11.4.1 Extending Modeled Java Classes

Extends relationships model inheritance between elements in a class model. Extends relationships can be created between Java classes and between Java interfaces, creating an extends statement in the class definition. Enums cannot extend other classes, or be extended by other classes.

Note:

As multiple class inheritance is not supported by Java, only one extends relationship can be modeled from a Java class on a diagram. Multiple extends relationships can be modeled from a Java interface.

18.11.4.2 Implementing Modeled Java Interfaces

Implements relationships specify where a modeled Java class is used to implement a modeled Java interface. This is represented as an implements keyword in the source for the Java class. Implements relationships are represented on class diagrams as dashed lines with an empty arrowhead pointing towards the interface to be implemented. Enums cannot implement interfaces.

If the implemented interface is an extension (using an extends relationship) of other modeled interfaces, this is reflected in the Java source code for the interface.

A class that implements an interface can provide an implementation for some, or all, of the abstract methods of the interface. If an interface's methods are only partially implemented by a class, that class is then defined as abstract.

18.11.5 Modeling Java Fields and Methods

You can create members (fields and methods) of a Java class or interface on a diagram. The fields and methods are added to modeled Java classes and interfaces on a diagram by double-clicking the modeled Java class or interface then adding the field or method using the Java Source Editor.

  • Fields are used to encapsulate the characteristics of a modeled Java class or Java interface. All modeled fields have a name, a datatype and a specified visibility.

    When a field or method is displayed on a class on a diagram, it is prefixed with + (if declared as public), - (if declared as private) or # (if declared as protected). Static fields are underlined on the diagram.

  • Methods are defined on a class to define the behavior of the class. Methods may have return types, which may be either a scalar type or a type defined by another class.

18.11.6 Modeling Packages on a Java Class Diagram

A package is a general purpose mechanism for organizing elements into groups. It may contain many different types of elements including packages, files, classes and model elements (for example; classes, interfaces, entity objects). Packages may be nested within other packages.

A package owns the elements within it and provides the context and namespace for those elements. Elements owned by the same package must have unique names within the package. Each element is directly owned by a single package, but can be referenced (imported) from other packages; in other words, referred to by other elements in other packages.

If a package is renamed on a diagram, or moved to another package, the contents of the moved or renamed package will be refactored automatically to reflect this package change.

Package names must be unique within a namespace, even if the names have different capitalization.

Java packages can be either created on a diagram, or dragged onto a diagram from the navigator. To open a diagram for a Java package, right-click the package on the diagram and choose Drill Down.

18.11.7 How to Display Related Classes on a Diagram

Java classes and interfaces related to those currently displayed on the diagram can be brought onto the diagram. This includes classes or interfaces that are extended, implemented, or referenced by the selected class or interface.

Note:

Where classes are added to a diagram from the project's source path, and are not already part of the project, those classes are automatically added to the current project.

To display related classes on a diagram, use one of the two following ways:

  • Select the class or interface, on the diagram, for which you want to display related elements, then choose Model > Show > Related Elements.

  • Right-click the class or interface, on the diagram, for which you want to display related elements, then choose Show > Related Elements.

18.11.8 How to Hide References between Java Classes

Relationships between Java classes or interfaces can be visualized on a diagram using references. You can hide a reference on a diagram.

To hide a reference between Java classes:

  • Right-click the reference you want to hide and choose Hide Reference.

To display a hidden reference between Java classes:

  1. Double-click the modeled Java class in which the field representing the reference is defined.

  2. Click the Source tab at the bottom of the editor window.

  3. Remove the attribute Javadoc tag from above the member representing the reference.

    The hidden reference will be displayed on the diagram.

Note:

Hiding a reference between Java classes on a diagram adds a comment to the Java source for the class, so if this class is also on any other diagrams, that reference will also be hidden on those diagrams.

18.11.9 What Happens When You Model a Java Class

The definitions of the classes on a diagram, their members, inheritance, and composition relationships are all derived directly from the Java source code for those classes. These are all created as Java code, as well as being displayed on the diagram. If you change, add to, or delete from, the source code of any class displayed on the diagram, those changes will be reflected on those classes and interfaces on the diagram. Conversely, any changes to the modeled classes are also made to the underlying source code. Some information relating to composition relationships, or references, captured on a Java class diagram is stored as Javadoc tags in the source code.

A Java class diagram can contain shapes from other diagram types (Oracle ADF Business Components, UML elements, Enterprise JavaBeans, and database objects). A form of UML notation is used to display the classes on your diagram. Modeled UML classes can be transformed to modeled Java classes. Likewise, modeled Java classes can be transformed to modeled UML classes. You can annotate a diagram of Java classes using notes, dependency relationships and URL links.

18.11.10 How to Create a Diagram of Java Classes

Java classes, interfaces, and enums can be visually created on a Java class diagram, together with their members, inheritance and composition relationships.

You can create UML classes, UML use cases, offline database objects, business components, Enterprise JavaBeans, and web services on a Java class diagram.

Java classes on a diagram must have valid Java class names and must be unique within the class's package. If you define a modeled Java class as abstract you should create a concrete Java class with a generalization to the abstract Java class. The names of modeled abstract Java classes are displayed in italics.

To create a diagram of Java classes:

  1. Create a new diagram using the Java Class Diagram icon in the New Gallery.

  2. Create the nodes you require on the diagram using the Java Class Component Palette.

    Also, Java classes and interfaces available to the current project can be dragged from the navigator and dropped on the diagram to either modify the code for those classes, or to visualize the structure of existing code.

    Tip:

    You can also annotate your diagram by creating and attaching notes to diagram elements, and adding URL links to other locations such as files or web locations.

18.12 Unit Testing with JUnit

JUnit is an open source regression testing framework for Java. Use JUnit to write and run tests that verify Java code. For detailed information about JUnit, visit the JUnit website, http://www.junit.org/

Use JUnit wizards in JDeveloper to create test fixtures, cases, and suites. In addition to wizards for creating test components for generic projects, specialized wizards for business components projects are provided.

JUnit is an optional feature that can be installed and integrated with JDeveloper.

After you install JUnit as an extension, additional online documentation is installed. These help topics appear under Help Table of Contents under the folder Creating a JUnit Test for a Java Project.

18.12.1 How to Install JUnit

JUnit is an optional feature that is not distributed with JDeveloper. You must download and install it if you wish to use it.

Note:

JUnit is provided under an IBM public license agreement. You must accept to the license agreement before downloading JUnit.

To install JUnit in JDeveloper:

  1. Use the IDE Update Wizard to download JUnit from the Oracle Technology Network (OTN).

  2. Exit and restart JDeveloper.

  3. JUnit will be installed. Use the Extension Manager if you wish to uninstall it.

18.12.2 Creating a JUnit Test for a Java Project

A JUnit test application consists of the following components:

  • One or more test cases, which invoke the methods that are to be tested, and make assertions about the expected results. While test case classes generated by default have 'Test' in their names, the user can specify any valid Java name.

  • Test fixtures, which provide the state in which the tests are run. Any class can serve as a test fixture, but JDeveloper provides wizards to help you create specialized test fixture classes. While test fixture classes generated by default have 'Fixture' in their names, the user can specify any valid Java name.

  • A test suite, which invokes the test cases. Default test suite classes have 'AllTests' in their names.

  • A runner, which invokes the test suite and collates and displays the results of the tests.

18.12.3 How to Create a JUnit Custom Test Fixture

A test fixture is a set of objects, having known values, that provide data for the test cases. Any class can serve as a test fixture, but JDeveloper provides wizards to help you create custom test fixture classes and various specialized test fixture classes.

To create a JUnit custom test fixture class:

  1. In the Navigator, select the project.

  2. Choose File > New to open the New Gallery.

  3. In the Categories tree, expand General and select Unit Tests.

  4. In the Items list, double-click Test Fixture.

  5. Complete the wizard to create the test fixture class. The class created by the wizard will be opened for editing.

  6. In the Categories tree, expand General and select Unit Tests (JUnit).

  7. In the Items list, double-click Custom Test Fixture.

  8. Complete the wizard to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.

  9. In the Categories tree and expand the Unit Tests.

  10. Click Test Suite > OK.

  11. In the Items list, double-click Test Fixture.

  12. Complete the wizard to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.

    The class created by the wizard will be opened for editing.

  13. Modify the file as needed. In particular, to the setUp() method add code that initializes test fixture objects, and to the tearDown() method add code that releases any resources they acquire.

18.12.4 How to Create a JUnit JDBC Test Fixture

A test fixture is a set of objects, having known values, that provide data for the test cases. A JDBC test fixture provides code that establishes a database connection for the test cases to use.

To create a JUnit JDBC test fixture class:

  1. In the navigator, select the project.

  2. Choose File, then New to open the New Gallery.

  3. In the Categories tree, expand General and select Unit Tests (JUnit).

  4. In the Items list, double-click JDBC Test Fixture.

  5. Complete the dialog to create the test fixture class. For more information at any time, press F1 or click Help from within the dialog.

    The class that was created will be opened for editing.

  6. Modify the file as needed. In particular, to the setUp() method add code that initializes test fixture objects, and to the tearDown() method add code that releases any resources they acquire.

18.12.5 Creating a JUnit Test Case

A test case class has one or more methods that perform tests by calling JUnit assertions. Example 18-6 shows a typical test case in JUnit 3.x. It passes test fixture data to the method being tested, and then compare the result with a known value to confirm that it is what is expected.

Example 18-6 JUnit 3.x Test Case

public void testCountChars()
{
      int expected = 4;
      int actual = fixture1.countChars('a');
      assertEquals(expected, actual);
}

Example 18-7 JUnit 4 Test Case

@Test
public void testCountChars()
{
      int expected = 4;
      int actual = fixture1.countChars('a');
      Assert.assertEquals(expected, actual);
}

In the test case shown in Example 18-7, countChars() is being tested, and the result of the test is checked by assertEquals(), which is one of a variety of assertion methods defined in the JUnit Assert class. The state of the test fixture, fixture1, is established in the setUp() method, which will have been called before the test case is called, as shown in Example 18-8.

Example 18-8 setUp() method

protected void setup() throws Exception
{
fixture1 = new StringFixture("Goin' to Kansas City, Kansas City, here I come.");
}

To create a JUnit test case class:

  1. In the navigator, select the project or the particular class that you want to test.

  2. Choose File, then New to open the New Gallery.

  3. In the Categories tree, expand General and select Unit Tests (JUnit).

  4. In the Items list, double-click Test Case.

  5. Complete the wizard to create the test fixture class. The class created by the wizard will be opened for editing.

18.12.6 Creating a JUnit Test Suite

A test suite is a class that invokes test cases.

The JUnit Test Suite wizard has options to insert a main() method and a call to a TestRunner class. Within JDeveloper, this will open the JUnit TestRunner log window to display the test results. Edit the method if you wish to use a different test runner.

In the JUnit 3.x test suite shown in Example 18-9, the suite() method creates a TestSuite instance and adds the test cases to it. Edit this method if you wish to add or remove test cases.

Example 18-9 JUnit 3.x Test Suite

public class AllTests {
    public static Test suite() {
    TestSuite suite;
    suite = new TestSuite("project1.AllTests");
    return suite;    }        

In the JUnit 4 test suite shown in Example 18-10, the test case classes are written with @Suite and @RunWith annotations.

Example 18-10 JUnit 4 Test Suite

@RunWith(Suite.class)
@Suite.SuiteClasses( {})
public class AllTests1 {
    public static void main(String[] args) {
    String[] args2 = { AllTests1.class.getName() };
    org.junit.runner.JUnitCore.main(args2);
    }
}

To create a JUnit test suite class:

  1. In the navigator, select the project.

  2. Choose File, then New to open the New Gallery.

  3. In the Categories tree, expand General and select Unit Tests (JUnit).

  4. In the Items list, double-click Test Suite.

  5. Complete the wizard to create the test fixture class. The class created by the wizard will be opened for editing.

  6. Modify the file as needed. In particular:

    • In the suite() method add the test cases.

    • In the main() method replace the runner invocation, if desired.

18.12.7 How to Add a Test to a JUnit Test Case

You can add a unit test for a method to an existing JUnit test case class.

To add a test to a JUnit test case class:

  1. In the code editor, select a method for which you want to create a new unit test.

  2. From the main menu, choose Source > New Method Test. The New Method Test dialog is opened.

  3. Select Add to Existing TestCase Class.

  4. From the Class Name dropdown box, or by using Browse, select the test case class that you want to add the new test to.

  5. To add the new test to the test case, click OK.

18.12.8 How to Update a Test Suite with all Test Cases in the Project

You update a test suite with all test cases in a project.

To update a test suite:

  1. In a class that has a suite() method, from the main menu, choose Source > Refresh Test Suite. The Refresh Test Suite dialog is opened.

  2. Ensure that all items in the list of test cases are checked.

  3. To update the test suite, click OK.

18.12.9 How to Run JUnit Test Suites

When your test suite has been successfully compiled you can run it.

To run a JUnit test suite:

  1. In the navigator, select the test suite class.

  2. Right click it, and choose Run.

    The test will execute, and the test runner will display the results.