168
BEA WebLogic is a J2EE application server and also an HTTP web server by BEA Systems of San Jose, California, for Unix, Linux, Microsoft Windows, and other platforms. WebLogic supports Oracle, DB2, Microsoft SQL Server, and other JDBC-compliant databases. WebLogic Server supports WS-Security and is compliant with J2EE 1.3. BEA WebLogic Server is part of the BEA WebLogic Platform™. The other parts of WebLogic Platform are:Portal, which includes Commerce Server and Personalization Server (which is built on a BEA-produced Rete rules engine), WebLogic Integration, WebLogic Workshop, an IDE for Java, and JRockit, a JVM for Intel CPUs. WebLogic Server includes .NET interoperability and supports the following native integration capabilities: Native enterprise-grade JMS messaging J2EE Connector Architecture WebLogic/Tuxedo Connector COM+ Connectivity CORBA connectivity IBM WebSphere MQ connectivity BEA WebLogic Server Process Edition also includes Business Process Management and Data Mapping functionality. WebLogic supports security policies managed by Security Administrators. The BEA WebLogic Server Security Model includes: Separate application business logic from security code Complete scope of security coverage for all J2EE and non-J2EE components

webLogic

Embed Size (px)

Citation preview

Page 1: webLogic

BEA WebLogic is a J2EE application server and also an HTTP web server by BEA Systems of San Jose, California, for Unix, Linux, Microsoft Windows, and other platforms. WebLogic supports Oracle, DB2, Microsoft SQL Server, and other JDBC-compliant databases.

WebLogic Server supports WS-Security and is compliant with J2EE 1.3.

BEA WebLogic Server is part of the BEA WebLogic Platform™. The other parts of WebLogic Platform are:Portal, which includes Commerce Server and Personalization Server (which is built on a BEA-produced Rete rules engine),

WebLogic Integration,

WebLogic Workshop, an IDE for Java, and

JRockit, a JVM for Intel CPUs.

WebLogic Server includes .NET interoperability and supports the following native integration capabilities:

Native enterprise-grade JMS messaging

J2EE Connector Architecture

WebLogic/Tuxedo Connector

COM+ Connectivity

CORBA connectivity

IBM WebSphere MQ connectivity

BEA WebLogic Server Process Edition also includes Business Process Management and Data Mapping functionality.

WebLogic supports security policies managed by Security Administrators. The BEA WebLogic Server Security Model includes:

Separate application business logic from security code

Complete scope of security coverage for all J2EE and non-J2EE components

WebLogic History

WebLogic, Inc., was founded by Paul Ambrose, Bob Pasker, Laurie Pitman, and Carl Resnikoff, in September, 1995. Up until then, Paul and Carl had been developing (pre-JDBC) Oracle, Sybase, and Microsoft SQL Server database drivers for Java under the name dbKona, as well as a "three tier" server to permit applets to connect to these databases. An old dbKona/An T3 Usenet posting. This was the WebLogic 1.48 server, and was called T3Server (a bastardization of 3-Tier Server).

Page 2: webLogic

Concurrently, Laurie and Bob had been working on network management tools in Java. Bob had written a SNMP stack in Java and a W32 native method for ICMP ping, while Laurie worked on applets to display the management data.

One of the hidden features of the 1.48 server version was the ability to extend it by modifying a dispatcher and adding a handler for different types of messages. Bob talked Paul into sending him the source code for the server, and Bob extended it so that Applets could make SNMP and PING requests on the network, and display the results.At this point, the founders worked together to pursue what was eventually to be called the Application Server.

The WebLogic Workshop Development Environment

WebLogic Workshop is an integrated development environment for building enterprise-class J2EE applications on the WebLogic Platform. WebLogic Workshop provides an intuitive programming model that enables you to focus on building the business logic of your application rather than on complex implementation details. Whether you are an application developer with a business problem to solve or a J2EE expert building business infrastructure, WebLogic Workshop makes it easy to design, test, and deploy enterprise-class applications.

WebLogic Workshop consists of two parts: an Integrated Development Environment (IDE) and a standards-based runtime environment. The purpose of the IDE is to remove the complexity in building applications for the entire WebLogic platform. Applications you build in the IDE are constructed from high-level components rather than low-level API calls. Best practices and productivity are built into both the IDE and runtime.

WebLogic Workshop is available in two editions:

WebLogic Workshop Application Developer Edition includes the basic features required by application developers to build web services, web applications, custom controls and Enterprise JavaBeans (EJBs). All editions of WebLogic Workshop also include ubiquitous support for XMLBeans, BEA's technology for seamless, natural manipulation of XML in Java. WebLogic Workshop Platform Edition includes additional extensions to the IDE and runtime framework that let you build portal applications and business processes in conjunction with the WebLogic Portal and WebLogic Integration products, respectively. WebLogic Workshop's intuitive user interface lets you design your application visually. Controls make it simple to encapsulate business logic and connect to enterprise resources, like databases and Enterprise JavaBeans, without writing a lot of code. Conversations handle the job of keeping track of application state. And WebLogic Workshop's support for asynchronous processes makes it easy to build highly reliable applications for the enterprise.

Developing Applications with WebLogic Workshop

The topics in this section address the basic concepts you need to understand to build entrprise-class applications with WebLogic Workshop.

What Can I Build with WebLogic Workshop?

Page 3: webLogic

The WebLogic Workshop IDE builds enterprise-class applications that run in the WebLogic Workshop runtime. The applications you build in WebLogic Workshop typically expose systems and data within or between enterprises, typically via web applications and/or web services. As an example, considering an express shipping company. Such a company might want to expose shipment scheduling, tracking and billing data to its business partners via web services so that partners' applications can access the data directly. The company also might want to expose tracking information via one or more web applications so that shipment originators and recipients can check the status of shipments from a web browser. WebLogic Workshop makes it easy to construct common functionality for both applications and then expose that functionality with appropriate interfaces.

In WebLogic Workshop Application Developer Edition, the core components are:

Java controls

Web services

Web applications

Enterprise Java Beans (EJBs)

In WebLogic Workshop Platform Edition you can also build:

Portal Applications

WebLogic Integration components: business processes, data transformations, integration-specific controls

What is an "Enterprise-class" Application?

"Enterprise-class" applications exhibit specific attributes. The J2EE foundation on which the WebLogic Platform and WebLogic Workshop is built provides reliability, availability and scalability as well as caching, security and transaction support. "Enterprise-class" also refers to additional specific attributes with regard to web services and web applications:

Enterprise-class web services are loosely-coupled and coarse-grained and optionally asynchronous. To learn more about how WebLogic Workshop enables these attributes, see Why Build Web Services with WebLogic Workshop?.

An enterprise-class web application exhibits a separation between its application logic and its presentation logic. WebLogic Workshop enables this separation with Java page flows, which are based on the well-established Model-View-Controller pattern. To learn more about Java page flows, see Developing Web Applications.

How WebLogic Workshop Simplifies Development

As you read about the various components of a WebLogic Workshop application in the sections that follow, there are two common threads you will notice: the use of Java classes with powerful custom

Page 4: webLogic

Javadoc annotations and the presence of custom design and development tools for each component type.

Javadoc Annotations

Each of the major components of a WebLogic Workshop application is expressed as a single Java class that is annotated with special Javadoc annotations (also called Javadoc annotations). The Javadoc annotations indicate to the WebLogic Workshop runtime that the component developer wants to utilize or configure particular features of the runtime.For example, the @common:operation Javadoc annotation on a method in the Java class defining a web service indicates that that method should be exposed as an operation in the web service's WSDL file. As another example, the @jpf:forward Javadoc annotation on a method in the Java class defining a Java page flow indicates the page to which the user should be directed when that action is invoked. Via these annotations, WebLogic Workshop hides the vast majority of the complexity of implementing sophisticated applications. The Javadoc annotations are typically managed for you; they are represented as "properties" in the IDE.

The fact that each component type is expressed in a single Java file is also significant. In WebLogic Workshop, you never have to manage generated stub files or deployment descriptors. The WebLogic Workshop runtime analyzes the annotations and performs all of the required infrastructure plumbing automatically. As a developer, you can focus completely on the business logic of your application.While each of the core components of a WebLogic Application is expressed as a 100% pure Java class, WebLogic Workshop uses different filename extensions to denote the component types. For example, a web service is stored in a file with the .jws extension indicating Java Web Service.To learn more about the filename extensions you will encounter while working with WebLogic Workshop, see WebLogic Workshop File Types.

Component-Specific Development Tools

WebLogic Workshop provides customized editors for all of the component types. Most component types have a dedicated Design View, which provides an intuitive graphical view of the component under development and the other components with which it interacts. WebLogic Workshop also provides customized Source Editors with all of the features developers expect in an IDE including source code completion, syntax coloring and error and warning indications in real-time. In the cases where multiple languages appear in the same source file (for example, when fragments of XML are used in a web service source file to specify XML <-> Java mapping), the Source Editor automatically adjusts its behavior to the language of the file segment in which the cursor is currently located.

Finally, WebLogic Workshop provides full two-way editing: any changes you make in the source view of a component are immediately reflected in the graphical view and vice versa.

Java Controls

All of the entities in the diagram that include the word "control" are Java controls. A Java control encapsulates business logic or facilitates access to an enterprise resource. Once a Java control has been

Page 5: webLogic

created, that control can be used easily and consistently from a web service, a page flow, a portal, a business process or another Java control.A Java control is a Java class that is annotated with special Javadoc annotations that enable features in the control when it is executed in the WebLogic Workshop runtime. A Java control may define methods and events. From the application developer's point of view, the consistent architecture of Java controls serves to greatly reduce the complexity of using the enterprise resources or business logic they encapsulate. Since all Java controls are Java classes, productivity aids such as source code-completion are available throughout the WebLogic Workshop IDE to streamline the development process.

When designing a Java control, you can see the relationship between the control, its client, and any other controls in the IDE's Design View. All of the important development activities can be accomplished by drag-and-drop or context-menu actions.

WebLogic Workshop includes several built-in controls that facilitate access to commonly used enterprise resources including databases, Enterprise Java Beans (EJBs), external web services and Java Message Service (JMS) queues and topics. You can create custom Java controls to encapsulate any business logic that is required by your application. Business or application logic might be contained in a variety of components, including EJBs or other applications. If you have the choice, however, encapsulating business or application logic in a Java control leverages the full power of the WebLogic Workshop architecture, including asynchronous execution and conversations ("conversation" is the WebLogic Workshop model for a long-running transaction).

Web Services

A Web Service is a piece of application logic that is exposed via standards such as Simple Object Access Protocol (SOAP; a specific dialect of XML)) and Web Services Description Language (WSDL). To use a web services, an application sends an XML message that requests an operation be performed. The application typically receives an XML response indicating or containing the results of the operation. WebLogic Workshop makes it very easy to create and deploy web services that adhere to web service standards, to access and process the XML messages received by web services and to format XML responses. Specifically, WebLogic Workshop provides two powerful technologies for manipulating XML in web services: XML Maps using XQuery for simple inline Java

<-> XML mapping specifications and XMLBeans for comprehensive Java <-> XML binding.

In WebLogic Workshop, a web service is a Java class that is annotated with special Javadoc annotations that provide simplified access to advanced web service features such as asynchrony, conversations, security and reliable messaging. Like all WebLogic Workshop components, Java web services can use Java controls to access business logic or enterprise resources. Everything you need to completely define a web service's operations, protocols, message formats and runtime behavior is contained in the web service's JWS file. There are no deployment descriptors to decipher and no external file generation to manage. WSDL generation for web services is completely automatic.

Page 6: webLogic

When designing a web service, the IDE's Design View shows you the relationship between the web service, its client, and any controls used by the web service. All of the important development activities can be accomplished by drag-and-drop or context-menu actions.While this topic is concerned mostly with components you build with WebLogic Workshop, it is important to note that WebLogic Workshop can easily inter-operate with web services built with other tools. One of the built-in Java controls WebLogic Workshop provides is the Web Service control. WebLogic Workshop can automatically generate a Web Service control from any valid WSDL file. Subsequently, the generated Web Service control can be used from any WebLogic Workshop component to access the remote web service as though it were a simple Java class.

Web Applications

To enable construction of dynamic, sophisticated web applications, WebLogic Workshop provides Java page flows. A page flow links together multiple web pages in a web application and provides a central control mechanism that coordinates the user's path through the pages and the associated flow of data. A page flow is a Java class that is annotated with special Javadoc annotations that controls the behavior of the web application Page flows use methods, and in most cases, forms and form beans (Java classes containing the data associated with a form) to manage navigation and state. A directory that contains a page flow class typically also includes one or more Java Server Pages (JSPs). The JSP files can reference custom WebLogic Workshop JSP annotations to raise actions, bind user interface components to data and access other application facilities. The actions referenced in a JSP correspond to action methods that are defined in the page flow class. These action methods implement code that can result in site navigation, data management, or invocation of business logic via Java controls. Significantly, the business logic in the page flow class is separate from the presentation code defined in the JSP files.

When designing a page flow, the IDE's Flow View shows the relationship between the pages in the web application and the actions that link the pages. All of the important development activities can be accomplished by drag-and-drop or context-menu actions. WebLogic Workshop also provides wizards to create specific types of page flows, generating the Java and JSP files that serve as a starting point for sophisticated applications. Page flows are based on the Struts architecture, which is itself based in the popular Model-View-Controller user interface design pattern. Page flows add powerful, scalable support for state management and page flows and the JSPs they manage also have complete access to Java controls to access business logic or enterprise resources.

Enterprise Java Beans

Enterprise Java Beans (EJBs) are server-side Java software components of enterprise applications. The J2EE Specification defines the types and capabilities of EJBs as well as the environment (or container) in which EJBs are deployed and executed. From a software developer’s point of view, there are two aspects to EJBs: first, the development and deployment of EJBs; and second, the use of existing EJBs from client software. WebLogic Workshop enables you to create new session, entity and message driven EJBs using a custom Design View. To learn how to create EJBs in WebLogic Workshop, see Developing Enterprise Java Beans.

Page 7: webLogic

WebLogic Workshop also provides a built-in control, called the EJB control, that makes it easy to use an existing, deployed EJB from your application.

Portal Applications

WebLogic Workshop Platform Edition adds the WebLogic Workshop Portal Extensions™ which allow you to build portals and portal resources using the WebLogic Workshop IDE. The portals you build are deployed using WebLogic Portal. A portal represents a Web site that provides a single point of access to applications and information and may be one of many hosted within a single WebLogic Portal server. Portals are becoming more and more important to companies who need to provide employees, partners, and customers with an integrated view of applications, information, and business processes. WebLogic Portal meets these needs, allowing companies to build portals that combine functionality and resources into a single interface while enforcing business policies, processes, and security requirements, and providing personalized views of information to end users.

From an end user perspective, a portal is a Web site with pages that are organized by tabs or some other form of navigation. Each page contains a nesting of sub-pages, or portlets—individual windows that display anything from static HTML content, dynamic JSP content or complex Web services. A page can contain multiple portlets, giving users access to different information and tools in a single place. Users can also customize their view of a portal by adding their own pages, adding the portlets they want to it, and changing the look and feel of the interface. The business problem that portals solve is illustrated in the following example. A company has the need for several types of Web presence: an Intranet for its employees, a secure site for interactions with partners, and a public Web site. WebLogic Portal’s flexible portal network architecture supports multiple implementation choices which allow re-use of resources across portals.

WebLogic Integration Components

WebLogic Workshop Platform Edition adds the capability to build WebLogic Integration components using the WebLogic Workshop IDE. WebLogic Integration enables you to design business processes that span applications, users, enterprise networks, and trading partners. WebLogic Integration's business process management (BPM) functionality enables the integration of diverse applications and human participants, as well as the coordinated exchange of information between trading partners outside of the enterprise. A business process is a graphical representation of a business process. Business processes allow you to orchestrate the execution of business logic and the exchange of business documents among back-end systems, users and trading partners (systems and users) in a loosely coupled fashion. WebLogic Workshop Platform Edition enables you to create business processes graphically, allowing you to focus on the application logic rather than on implementation details as you develop.

A business process can utilize data transformations using either a query or an eXtensible Stylesheet Language Transformation (XSLT). WebLogic Workshop Platform Edition includes a data mapper to create data transformations graphically. From the graphical representation of a data transformation, WebLogic Workshop generates a query. The generated query is invoked at runtime by the business process to

Page 8: webLogic

transform data. A query is expressed in the XQuery language—a language defined by the World Wide Web Consortium (W3C) that provides a vendor independent language for the query and retrieval of XML data.

WebLogic Integration also provides a standards-based integration solution for connecting applications both within and between enterprises. WebLogic Integration provides the following tools for integrating applications: application views, the Adapter Development Kit (ADK), EIS adapters and Application View Controls. By using these tools, you can integrate all your enterprise information systems (EIS). Typical IT organizations use several highly specialized applications. Without a common integration platform, integration of such applications requires extensive, highly specialized development efforts.

Applications and Projects

In WebLogic Workshop you create and build an application.

A WebLogic Workshop application is a J2EE Enterprise Application and ultimately produces a J2EE Enterprise Application Archive (EAR) file. An application may contain:

one or more projects

libraries and modules

security roles

This topic introduces applications and their contents.

Applications

An application in WebLogic Workshop is the collection of all resources and components that are deployed as a unit to an instance of WebLogic Server. It is also the top-level unit of work that you manipulate with WebLogic Workshop IDE. In the IDE, you may have at most one application open at a time. When you create a new application, you specify a name for the application. By default, new applications are created in the BEA_HOME/weblogic81/samples/workshop folder of your installation, but you should create your applications elsewhere so they cannot cause conflicts when upgrading to future versions of WebLogic Platform. An application in WebLogic Workshop contains one or more projects. Except in specific cases, such as accessing remote EJBs or web services, a WebLogic Workshop application is self-contained. Components in the projects of an application may reference each other, but they may not generally reference components in other WebLogic Workshop applications.

An application — more formally called an enterprise application — is different from a web application. Web application refers to a collection of resources, typically HTML or JSP pages, that allow users to access functionality via the Web. An application may contain zero or more web applications.

When to Create a New Application

Page 9: webLogic

An application should represent a related collection of business solutions. For example, if you were building an e-commerce site you might design an application that includes web applications for catalog shopping and customer account management and the components that support them (Java controls, EJBs, etc.). You might also need to deploy a human resources application for use by your employees. The human resources application is not related to the e-commerce application. Therefore, in WebLogic Workshop you would probably create two applications to separate these disparate business functions.

Applications Installed with WebLogic Workshop

WebLogic Workshop is installed with an application named SamplesApp, which contains example projects that you can explore to learn about WebLogic Workshop. The SamplesApp application is located in the file system at BEA_HOME/weblogic81/samples/workshop/SamplesApp. The following image shows the Application pane for the SamplesApp application:

WebLogic Workshop is also installed with an application named TutorialsApp that contains components used in the product tutorials. The TutorialsApp is located in the file system at BEA_HOME/weblogic81/samples/platform/TutorialsApp.

Projects

A project groups related files that comprise a component of an application.

In WebLogic Workshop Application Developer Edition, there are six default project types:

Web project

Web Service project

Control project

Control Deliverable project

EJB project

Java project

Page 10: webLogic

Schema project

WebLogic Workshop Platform Edition adds the following project types:

Portal project

Datasync project

Process project

WebLogic Workshop project types are defined by project templates. You may create custom project templates to meet the needs of your organization.

Web Project and Web Service Project

Web projects are typically used to expose enterprise application logic via a user interface. The user interface is constructed from Java Server Pages (JSPs), which are web pages that can interact with server resources to produce dynamic content. WebLogic Workshop defines Java Page Flows that define and contain the logic required to connect multiple JSPs. Web services are typically used to expose enterprise application logic to applications (as opposed to users). Individual web service interfaces are published via Web Services Description Language (WSDL) files. Each Web project or Web Service project ultimately produces a J2EE web application, each of which is included in the complete WebLogic Workshop application's EAR file when the application is built for deployment.

Contents of Web projects and Web Service projects are accessed via URLs. The WebLogic Workshop application is implicit in the URL for resources within that application. For example, the index.jsp sample JSP, which is located in the file system at SamplesApp/WebApp/index.jsp, is accessed from a web browser with the following URL:

http://localhost:7001/WebApp/index.jsp

Note that the name of a project becomes part of the public URL of each resource located within that project. You should choose your project names with that in mind. You can configure a Web or Web Service project to load by default if you do not want to require users to provide a project name as part of the URL. For example, users can access

http://localhost:7001/WebApp/index.jsp by simply requesting http://localhost:7001/.

To configure a project to load by default:

From the Application tab, right-click on the Web or Web Service project that you would like Web Logic Server to load by default and select Properties.

In the Project Properties dialog, select the Use project name check box..

In the text box labeled Context Path, enter / and Click OK.

Page 11: webLogic

The SamplesApp sample application contains a sample Web project named WebApp and a sample Web Service project named WebServices.

Note: Web projects and a Web Service projects are both J2EE web applications. Web services may be created in a web application and page flows and JSPs may be created in a web service project. The only difference between the project types is the set of supporting files the project initially contains. If you add web services to a web project or page flows or JSPs to a web service project, the necessary supporting files are automatically added to the project.

Control Project

Java controls are entities that contain business logic or provide convenient access to enterprise resources. A control project may be used to construct and package controls that are intended for use by components in other projects. For example, a custom control that provides access to a proprietary Human Resources application might be used from JSPs in a web project and also from web services in a web service project.

Each Control project ultimately produces a Java Archive (JAR) file.

The SamplesApp samples application contains a sample Control Project named ControlProject.

Control Deliverable Project

You use a control deliverable project when you want to build Java controls that will be distributed to multiple users. A control deliverable projects creates directories you can use to store help and sample files relating to the control. When you build a control deliverable project, WebLogic Workshop packages the controls of that project into a Java Archive (JAR) file along with the help and sample files that you provide in the generated help and sample directories. When users install the control, WebLogic Workshop automatically integrates the help and sample files contained in the JAR with the users existing WebLogic Workshop help installation.

EJB Project

Enterprise Java Beans (EJBs) are Java software components of enterprise applications. The J2EE Specification defines the types and capabilities of EJBs as well as the environment (or container) in which EJBs are deployed and executed. From a software developer’s point of view, there are two aspects to EJBs: first, the development and deployment of EJBs; and second, the use of existing EJBs from client software. An EJB Project provides support for creating and deploying new EJBs. Each EJB project ultimately produces a Java Archive (JAR) file and when an EJB project is built the EJBs in the project are automatically deployed to the development server.The EJB Control that is a built-in control in WebLogic Workshop allows clients such as web services, JSP pages or other controls to access existing EJBs, including EJBs created in an EJB Project.

Page 12: webLogic

Java Project

A Java project is a place to develop or collect general-purpose Java code that is not directly part of special entities such as web services, controls or EJBs. The product of a Java project is a JAR file that typically holds Java classes you want to access from other parts of your application. For example, a Java Project might hold Java code for a library of string formatting functions that are used in web services and JSPs in other projects in the application. By default, each Java project ultimately produces a Java Archive (JAR) file.

Schema Project

A Schema project provides convenient, automatic access to BEA Systems' XMLBeans functionality. XMLBeans is a facility that constructs Java classes from XML Schema and allows very easy, direct and powerful manipulation of XML documents in Java. If you place an XML Schema (XSD) file into a schema project, the XMLBeans schema compiler is automatically run on the schema and the resulting JAR file is automatically placed in the Libraries folder of the application. The Java classes in the JAR file are accessible to all projects in the application. For example, a web service in a web service project in the application can reference a schema as the input type of one or more of its methods and can automatically access incoming XML documents via the XMLBeans Java APIs.

The SamplesApp samples application contains a sample Schema Project named Schemas. It contains XML Schemas used by various samples in the SamplesApp application. Note: For XML Schemas to be available in a business process, the schemas must be imported into a Schemas project in your integration application. To learn more about using XML Schemas in integration applications, see Guide to Data Transformation.

Portal Project

Portal projects are available in WebLogic Workshop Platform Edition. Portals are used to provide a single point of access to enterprise applications and information that can be based on user, group and role attributes.A Portal project is similar to a Web project in that it is used to expose enterprise application logic via a user interface. Portal projects usually contain Java Server Pages (JSPs), and they provide additional capabilities, in addition to those available in Web projects, that allow developers to define portal Web sites.

Note: A Portal project is a J2EE web application and supports the creation of Web services, page flows and JSPs. The difference between a Portal project and a Web or Web Service project is the set of supporting files the project initially contains. Portal projects contain additional files that support creation of portals.

Datasync Project

Datasync projects are available in WebLogic Workshop Platform Edition. A Datasync project is used to develop and manage general purpose portal services that are used in the development of personalized applications and portals. These portal services include user profiles, user segments, events, request

Page 13: webLogic

properties, session properties, content selectors, placeholders, and campaigns. A Datasync project called data is generated when a Portal application is created.

Process Project

Process projects are available in WebLogic Workshop Platform Edition. A business process orchestrates the execution of business logic and the exchange of business documents among back-end systems, users and trading partners (systems and users) in a loosely coupled fashion. A Process project typically contains business process (JPD) files, control files and transformation files.

When to Create a New Project

As you develop an application, you may need to create new projects within the application for the following reasons:

To separate unrelated functionality

Each project should contain components that are closely related to each other. If, for example, you wanted to created one or more web services that expose order status to your customers and also one or more web services that expose inventory status to your suppliers it would make sense to organize these two sets of unrelated web services into two projects.

To control build units

Each project produces a particular type of file when the project is built. For example, a Java project produces a JAR file. If you want to reuse the Java classes contained in the Java project from multiple components, it would make sense to segregate the Java classes into a separate project and reference the resulting JAR file from other projects in your application.

Libraries and Modules

In addition to projects, each WebLogic Workshop application also contains two folders named Libraries and Modules. These folders can contain compiled Java code that you want to be available to the components of the application. The products of the various project types are automatically placed in the Libraries or Modules folder as appropriate. For example, the JAR file containing the XMLBeans Java classes derived form the XML Schemas in a Schema Project is automatically placed in the Libraries folder. However, you may also copy additional JAR files directly into the Libraries or Modules folders to make them available to the rest of your application.

The Libraries and Modules folders both place their contents on the application's Java class path. The main difference between the Libraries and Modules folders is that the contents of the Modules folder are automatically deployed to the appropriate instance of WebLogic Server. For example, when you build an EJB Project, the EJBs in the project are compiled and placed in a JAR file, which is then copied to the Modules folder and thereby automatically deployed to the server. The Libraries folder is equivalent to the APP-INF/lib directory of a J2EE Enterprise Application.

Page 14: webLogic

Security Roles

A WebLogic Workshop application also may define security roles, which are a facet of the J2EE security framework based on security roles, principals and groups.

A human resources application might define the following categories of users: an administrator may perform any operation, including configuring the application itself; a manager may perform HR operations on employees (add, delete, adjust compensation, etc.); and an employee may access a subset of his or her own HR records. Each of these user categories is called a security role, an abstract grouping of users that is defined by the designers of the application. When the application is deployed, an administrator will map the roles to actual security identities in the production environment.

A security role is an application-specific grouping of users, classified by common traits such as job title. When an application is deployed, roles are mapped to security identities, such as principals (identities assigned to users as a result of authentication) or groups, in the production environment. Based on this, a user has access rights to specific components and/or functions of an application based on the security role(s) to which the user's identify is mapped. The link is the actual name of the security role that is being referenced.

Following this model of role-based security, application components may be configured to allow or restrict access based on security roles. The application components do not (and should not) concern themselves with specific user or group identities. By abstracting security to roles, the actual configuration of an application's security settings can occur at runtime and requires no changes to the application code. In fact, J2EE allows configuration of security to a fine level of detail purely via declarative means by using files called deployment descriptors, so the application code doesn't even have to be aware of the actual security roles that are defined.

WebLogic Workshop allows you to define the security roles that will be used in your application. When your application is deployed, the security roles you have defined are deployed with it. If you have defined users and groups for test purposes in your development environment, those definitions are not deployed with your application. This eases testing of security configurations in the development environment but avoids the risk of leaving security roles in your application when it is deployed.

Cleaning Applications and Projects

Sometimes when you build an application or project, WebLogic Workshop does not update all of the appropriate build files. As a result, stale artifacts can exist between builds. This could happen for any number of reasons like moving or deleting files while WebLogic Workshop is closed. If you believe that any of your projects are exhibiting strange behavior, you can use the Clean utility to ensure that WebLogic Workshop removes all outdated build files and references. After cleaning, you can re-build the application or individual project and be sure that each build file is fresh.

To clean an application:

Page 15: webLogic

From the Application tab in WebLogic Workshop, right-click the application folder and select Clean Application.

To clean a project:

From the Application tab in WebLogic Workshop, right-click on the project folder representing the project you would like to clean and select Clean.

WebLogic Workshop File Types

This topic lists the file types you will encounter in your use of WebLogic Workshop. WebLogic Workshop Application Developer Edition File Types

You may use a variety of files to create your application in WebLogic Workshop, some of which you may not be familiar with. The key file types you may encounter in WebLogic Workshop Application Developer Edition are:

EJB file, or Enterprise Java Bean. An EJB file contains the Java implementation class for an EJB, with Javadoc annotations that configure the EJB.

JCS file, or Java Control Source. A JCS file contains the Java implementation class for a Java control type. There is only one JCS file per Java control. If the Java control is extensible, there may be many JCX files that extend the Java control.

JCX file, or Java Control eXtension. A JCX file is a local extension or customization of a Java control. For example, the Database control is defined once in a JCS file, but a local JCX file in an individual project defines the data source and operations for that particular instance of the control.

JPF file, or Java Page Flow. A JPF file contains the Java implementation class for a page flow, together with Javadoc annotations that configure and control the behavior of a web application. A page flow is a controller and a collection of JSPs. The controller coordinates a user's course through the JSPs depending on changes in state as the user progresses. Page flows also enable you to bind application data to user interface components in the JSPs and to access application logic and data via Java controls.

JSP file, or Java Server Pages. The JSP file type is defined by the J2EE Specification. WebLogic Workshop defines custom JSP tag libraries that allow JSP files to reference Java controls and page flow actions. A related file type is the JSPF file, which stands for Java Server Page Fragment. JSPF files are used to hold snippets of JSP code that can be included in other JSP files. There are many sample JSP files in the WebApp project of the SamplesApp sample application installed with WebLogic Workshop.

JSX file, or JavaScript with Extensions. A JSX file can contain ECMAScript (formerly called JavaScript) for manipulating XML. The functions in the JSX file are called from with XML Maps in a web service. WebLogic Workshop provides an extended ECMAScript language with support for XML as a native type, making XML processing in script very straightforward.

Page 16: webLogic

JWS file, or Java Web Service. A JWS file contains the Java implementation class for a web service, with Javadoc annotations that enable specific web service features. There are many sample JWS files in the WebServices project of the SamplesApp sample application installed with WebLogic Workshop.

WSDL, or Web Services Definition Language. WSDL files describe the interface of a web service to consumers of the web service. WebLogic Workshop can easily generate WSDL files for your web services, and can consume WSDL files for external web services so that you may access them from your WebLogic Workshop applications.

XMLMAP files. XML map files describe how XML should be mapped to Java, and vice versa, for a web service.

XQ files, also known as XQuery maps, contain queries written in the XQuery language. These queries contain transformations that convert data between XML, non-XML, Java classes, and Java primitive data sources. You can generate these queries using the provided mapper and use these queries to create business process and web service transformations.

XML files, or Extensible Markup Language files contain XML data that you can use as input to transformations.

XSD files, or XML Schema Definition files contain a schema that describes XML data. Importing an XSD file into a WebLogic Workshop application allows you to use imported XML data types in transformations.

CTRL files, or control files (deprecated). In WebLogic Workshop 7.0, control extensions were defined in CTRL files. CTRL files have been deprecated but are still supported in WebLogic Workshop 8.1. The functionality formerly provided by CTRL files is now provided by JCX files.

WebLogic Workshop Platform Edition File Types

In WebLogic Workshop Platform Edition, you may encounter the following additional file types:

WebLogic Integration File Types

CHANNEL file. The Message Broker provides typed channels to which messages can be published and to which services can subscribe to receive messages. A message broker channel has similar properties to a Java Message Service (JMS), but is optimized for WebLogic Integration processes, controls, and event generators. Channel files define the Message Broker channels in an application. To be visible to other application components, channel files must be placed in a Schemas project in your application.

To learn more about Message Broker channels, see Publishing and Subscribing to Channels.

DTF file, or Data Transformation Format. A DTF file references reusable data transformation methods which convert data from one format to another. For example, XML data can be transformed from XML data valid against one XML Schema to XML data valid against a different XML Schema. Sample DTF files are available in the following applications: Tutorial:

Page 17: webLogic

Process Application and New Process Application. (For example, if you create an application based on the Tutorial: Process Application, the TutorialJoin.dtf is available in the application.) These applications are available from File->New->Application in the WebLogic Workshop menu bar.

To learn more about data transformations, see Guide to Data Transformation.

For a tutorial on building data transformations, see Tutorial: Building Your First Data Transformation.

JPD file, or Process Definition for Java. A JPD file contains the Java implementation class for a WebLogic Integration business process, with special annotations that configure the business process. Sample business processes are available in the following applications: Tutorial: Hello World Process Application, Tutorial: Process Application, New Process Application. These applications are available from File->New->Application in the WebLogic Workshop menu bar.

To learn more about business processes, see Guide to Building Business Processes.

For a tutorial on building building business processes, see Tutorial: Building Your First Business Process.

MFL file, or Message Format Language describes and constrains the content of non-XML data. An MFL file defines a schema for non-XML data. You can use the the Format Builder to create MFL files at design-time. Importing an MFL file into a WebLogic Workshop application allows you to use the imported non-XML data types ( defined by the MFL ) file in transformations.

To learn more about working with MFL data, see Assigning MFL Data to XML Variables and XML Data to MFL Variables.

XSL file. This is basically an XSLT file with an XSL extension. XSL stands for Extensible Stylesheet Language. This language is defined by the W3C that supports the use of stylesheets for the conversion of XML data. When a Transformation method of type XSLT is invoked, the XSLT processor invokes the transformations defined in the associated XSLT file.

WebLogic Portal File Types

CAM file. Campaigns provide a container for executing scenarios to offer personalized content to users.

EVT file. Event property sets are used to define the events available for personalization services.

PLA file. Placeholders are used to display targeted media to users. In addition, event and behavior data can be tracked via event services.

PORTAL file. A portal is an aggregation of applications and information in a common, coherent user interface.

PORTLET file. A portlet provides a user interface to applications and information.

REG file. Request property sets are used to define the attributes available in the HTTP request

Page 18: webLogic

SEG file. User segments represent a business rule to classify users based upon their profile, request, session attributes as well as date and time conditions.

SES file. Session property sets are used to define the attributes available in the HTTP session.

SET file. Content selectors are a business rule used to retrieve content based upon user profile, request, session attributes as well as date and time conditions.

USR file. User Profile property sets are used to define the attributes available in a user’s profile.

Debugging Your Application

You can use the WebLogic Workshop integrated debugger to debug your application. The debugger allows you to set breakpoints, step through your code line-by-line, view local variables, set watches on variables, and view the call stack and exception information.

There are a variety of properties that can be set for the debugger. Some are set on a project basis, while others apply only to Java and Control Projects.

You can use the debugger on runnable files, non-runnable files, non-Workshop enabled servers, and projects developed against a remote server. You can also attach to JUnit and use the JUnit functionality in conjunction with the Weblogic WorkShop Debugger.

Using the Debugger

In order to debug an application, you must have a way to exercise the application as a real client would. WebLogic Workshop includes a Test Browser in which you may test Workshop web applications and web services. When you run a web application or web service, the Test Browser automatically loads Test View, a tool for exercising the application.

To start the debugger, click the Start button on the toolbar or press Ctrl-F5. To pause debugging, click the Pause button on the toolbar. To stop debugging, click the Stop button on the toolbar.

When the debugger is started, the WebLogic Workshop Debugger command window is opened for the debugger proxy. This window must remain open in order to use the debugger. If you close this window, your breakpoints will not be hit when you test your application.

While your application is running in the debugger, it is unavailable to clients other than the Test Browser.

To debug your project, you will use breakpoints, the commands that allow you to navigate the code, and the debug windows, which show information about variable values, how the program is running, and what code is executed.

Breakpoints

Page 19: webLogic

Breakpoints allow you to halt execution at a specified point in the program so you can observe information about its operation. When you halt execution at a breakpoint, you can step through the program line-by-line, step over a breakpoint, and use the debug windows to change values or execute arbitrary code.

The types of breakpoints you can set include:

Line Breakpoints - halts execution at the line of code before the breakpoint

Exception Breakpoints - halts execution when an exception occurs

Method Breakpoints - halts execution as soon as a specified method is called

Taglib Breakpoints - halts at the taglib method being implemented

JSP Breakpoints - used with JSP files only

To create Exception and Method breakpoints, select Debug-->Create Breakpoint and enter the appropriate settings in the Create Breakpoint dialog.

To create a Line breakpoint, put the cursor on the line of code where you want to halt execution and click the Toggle Breakpoint button on the toolbar.

To clear all breakpoints at once including exception breakpoints in the project, click the Clear All Breakpoints button on the toolbar, or press Ctrl-F9.

Using the Debugging Commands

Once execution is halted on a breakpoint, you can use one of the following commands to continue executing your code with the debugger. All of these commands are available on the toolbar and on the Debug menu.

Step Into: The Step Into command continues execution line-by-line, beginning with the next line of code. Use this command if you want to debug your code one line at a time.

Step Over: The Step Over command executes a method call without debugging that method, and halts execution on the next line. Use this command if you know that the code in a method works and you don't need to step into it.

Step Out: The Step Out command finishes executing a method and returns execution to the procedure that called it, halting on the line immediately following the method call. Use this command if you have stepped into a method and you don't want to continue stepping all the way through it.

Continue: The Continue command resumes execution until another breakpoint is encountered or the procedure has completed.

Page 20: webLogic

Export Threads: The Export Threads command, found in the Debug menu, creates and opens a text file that contains the call stacks of all of the threads that are running. This is a convenient way to save or share the current threads in the event of a deadlock or other threading problem. The command is only active when the debugger has thread information.

Note that if you step into a line that contains more than one statement, all of the statements on that line will be executed when you step to the next line.

Debug Windows

The debug windows provide information about values and conditions in your code while you're running it in the debugger. There are several to choose from:

Locals Window - shows variables that are in scope

Watch Window - displays the value of a specified variable while debugging

Stream Window - shows output stream for JSPs

Immediate Window - allows you to execute code while debugging

Call Stack Window - shows the methods called to get to the point at which execution halted

Threads Window - shows information about currently executing threads

Breakpoints Window - lists currently set breakpoints

To view one of the debug windows, choose Debug Windows from the View menu, and select the desired window. For more detailed information about the debug windows,

Debugging Properties

Several debugging options can be set on a project scope. The debugging options for each project in an application are independent, and are not set on an application basis.

Debugging properties for a project can be set on the Project Properties dialog box. To change them, pull up the project properties by either right-clicking the project folder in the Application tab and selecting Properties from the context menu, or by going to Tools-->Project Properties-->[Project_Name], then select Debugger in the pane on the left.

Alternatively, project debugging properties can be set by editing the WORK configuration file associated with the project.

Some project debugging properties apply only to specific types of projects.

Smart Debugging

Page 21: webLogic

Smart debugging lets you focus on debugging your code and not platform code. When you step through code, you stay in your own code. When smart debugging is enabled, you can specify classes that the debugger will automatically step through. Typically, the filtered classes are part of the WebLogic Platform. For example, if you step into a method that's part of WebLogic Server and that method eventually calls your own code, the debugger will step directly into your code. For web application projects, this should almost always be left on.

Smart debugging is enabled by default, and a default list of classes is generated automatically. You can disable filtering on parts of the class list by checking or unchecking the group of classes in the debugging properties dialog. For example, if you uncheck XML classes, the debugger will step into platform classes that support XML.

With version 8.1 SP2 or higher, you can add, remove, and edit the class list. The asterisk (*) wildcard can be used to specify packages and subpackages.

Build Before Debugging

This option specifies whether the project should be rebuilt before it is run in the debugger. For web applications, only the current file is rebuilt before running. For Java projects, the entire project is built before running.

By default, the Build before debugging option is enabled.

Pause All Threads After Stepping

This option specifies which threads are shown in the Threads window after stepping in the debugger. All threads are always suspended after hitting a breakpoint, but by default only the thread in which you are stepping is visible. By default, this option is disabled to provide better performance, so other threads will not be visible in the threads window. If you choose not to suspend all threads after stepping, you can still view them on demand using the Pause command.

Java and Control Project Options

Process Settings

The Create new process and Attach to process radio buttons specify whether the debugger runs the application is run locally or attaches to a remote process. These settings apply only to Java and Control projects.

Create new process settings

When this option is selected, the debugger starts a new Java Virtual Machine for the application when you click Start. The following options can be set for this process:

Main class: The name of the class containing the main method that is the entry point for the application.

Parameters: Arguments that are passed to the main method.

Page 22: webLogic

VM parameters: Arguments that are passed to the virtual machine when it starts. These arguments may include -D and -X virtual machine options.

Home directory: The directory in which to start the Java application.

Application classpath: Classpath used by the virtual machine.

Automatically append Library JARs: When this option is enabled, all of the JARs specified in the Libraries folder are appended to the classpath.

Automatically append server classpath: Then this option is enabled, all of the JARs that are specified in the"Default server classpath" list in Tools-->WebLogic Server-->Server Properties are appended to the classpath.

Attach to process

When this option is selected the debugger is attached to a specified Java virtual machine that is already running and is configured to accept a debugger when you click Start.

Socket: Connects to the virtual machine over the TCP/IP connector. You must specify the port on which the VM is listening. If blank, the server defaults to localhost.

Shared memory: Connects to the virtual machine over the shared memory connector. You must specify the memory address on which the VM is listening.

Debugging Scenarios

The WebLogic Workshop integrated debugger can be used in many debugging scenarios, as listed in this topic.

Remote Debugging

If you're developing against a remote server, you can also debug against that remote server. Breakpoints and other debugging information will be stored on the local machine.

You can also debug on a managed server, as described below.

Debugging JSP Pages

Be aware that browser caching is always turned off when you are debugging. To turn caching on while you are debugging, place the following scriptlet in your JSP pages.

<%

response.setHeader( "Cache-Control", null );

%>

Page 23: webLogic

Note that browser caching is the default behavior when your web application is deployed to a production server. You do not need to take special measures, such as the scriptlet above, to turn on caching on a production server.

Debugging EJBs

The debugger supports debugging EJBs regardless of whether they have been developed within WebLogic Workshop. They can be debugged locally or remotely.

Use the following procedure to attach the debugger to an EJB:

Open the source in Workshop

From the Tools menu choose Project Properties.

In the Debugger tab, choose Attach to Process.

Enter the debug port number (8453 by default) and server name or IP address.

Click Start.

Set breakpoints as needed and start debugging.

Debugging on a Non-Workshop-Enabled Server

To debug a project on a server not configured as a Workshop Server, open the Project Properties dialog box for the project you want to debug. On the Debugger tab, choose the "Non Workshop Server" radio button, and enter the debugging port number (8453 by default), the Http port number, and the name or IP address of the remote server.

Debugging on a Managed Server

To debug a project on a managed server, set up the front end host and port for the cluster and/or managed servers. Cluster servers can be set up using a proxy. Run all of the managed servers except one, and the admin server with nodebug on the start line. Do all of your debugging against the managed server.

Debugging Unrunnable Files

Some files cannot be directly run by WebLogic Workshop; these include servlets, custom Java controls, Java files, and so on. Nevertheless, you can still set and hit breakpoints in these files. For example, to debug a servlet, set breakpoints in the servlet source code, add a JSP page to your project, run that JSP page (this will start the debugging process), and then enter the servlet's URL directly into the browser's address bar. You will now be able to halt at breakpoints in the servlet code. To debug custom Java controls or Java files, set breakpoints in the source code of those files, and then run a web service or some other runnable file that calls into the Java control or Java file.

Page 24: webLogic

Starting Two Debugging Proxies in the Same Domain

If you start two server instances in the same domain (for example, using the start up script [BEA_HOME]/weblogic81/samples/domains/portal/startWebLogic.cmd), the second server will fail with a TransportException.

ERROR: Proxy already running...

weblogic.debugging.comm.TransportException

at weblogic.debugging.comm.ServerConnectInfo.createTransport()Lweblogic.

debugging.comm.CommTransport;(ServerConnectInfo.java:63)

The failure is caused by the debugging proxy, which attempts to open the same server socket port already used by the first server. To start the second server running on a different port, send a port number parameter to (1) the WebLogic Workshop IDE, (2) the server, and (3) the debugger. These are described below.

To Set the Port Number on the WebLogic Workshop IDE

Add the following parameter to [BEA_HOME]\weblogic81\workshop\workshop.cfg.

-Dworkshop.debugProxyPort=PORT_NUMBER

To Set the Port Number on the Server

Add the following parameter to the server startup script (for example, [BEA_HOME]\weblogic81\samples\domains\workshop\startWebLogic.cmd/.sh).

-Dworkshop.debugProxyPort=PORT_NUMBER

To Set the Port Number on the Debugger Process

Add the following parameter to the server startup script (for example, [BEA_HOME]\weblogic81\samples\domains\workshop\startWebLogic.cmd/.sh).

-serverport=PORT_NUMBER

Testing Your Application

Testing your application goes hand-in-hand with debugging. The test facility that comes with Weblogic Workshop runs in a browser window and is known as Test View.

In addition to Test View, you can use JUnit for testing from within Workshop.

Follow the links below for more information on using Test View and JUnit.

Page 25: webLogic

Managing the Build Process

The topics in this section discuss the WebLogic Workshop build environment and provides tips on how to optimize your build process.

Understanding the Build Process

Describes when and why to build your project or application. Understanding the build process better can help you streamline your iterative development effort.

Using the Build Process More Efficiently

Provides tips on how to build applications and projects efficiently. You can significantly reduce build times by making a few small configurations to the build environment and following a few of the best practice guidelines outlined in this document.

Customizing the Build Process

Introduces the scripts that WebLogic Workshop uses to perform application and project level builds. This topic describes how you can export, edit and deploy these scripts to create a custom build process.

How Do I ...?

Contains topics that guide you through the various tasks associated with managing the WebLogic Workshop build process.

Understanding the Build Process

Building your WebLogic Workshop application can be a time-consuming part of the iterative development process. By understanding when and how to build your application and its respective projects, you can streamline the build process for your application.

When Do I Need to Build My Project?

How often you need to build your project depends on what type of project you are using and what you are doing, but you may not need to build the project as often as you think.

Web Service, Page Flow, JSP, and JPD Files

If you are developing and testing web service (JWS), page flow (JPF), JSP, and JPD files in a Web or Web Service project, you don't need to build the project that contains them at all until you are ready to deploy the project. You can simply run the file in Test View to build and test them iteratively. WebLogic Workshop will automatically build any dependencies of that file for you on an as-needed basis.

Web and Web Service Projects

Page 26: webLogic

You only need to build Web and Web Service projects when you are ready to deploy those projects to a server that is not running in iterative development mode (that is, a server that was started with the noiterativedev flag passed to the startWebLogic command).

You can specify that Web and Web Service projects be built incrementally when you do build, rather than cleaning the project each time, by setting the Use Incremental Build property for the project. This can speed up the process of making changes to a web application that is running on a production server. Note that there are a small number of situations where incremental build will not detect file changes (e.g. final static variables, changes in external XML files). In those cases, a clean build will be necessary to reflect the current state of the project. For information on setting the Use Incremental Build property, see Using the Build Process More Efficiently.

Java, Control, EJB, and Schema Projects

Java projects, Control projects, EJB projects, and Schema projects are similar in that the result of building any of these projects is a JAR file that is written to the application's APP-INF/lib folder, or in some cases, the APP-INF/classes folder. These JAR files can then be used by other projects within the application. You should build these projects when you need to update the JAR files so that the latest changes are available to any projects that are using them.

When you build one of these projects, WebLogic Workshop checks to see that the JAR file is indeed out-of-date. If the JAR file is up-to-date, WebLogic Workshop doesn't build the project.

When Do I Need to Build My Application?

You need to build the entire application only when you are ready to deploy your application to a server that is not running in iterative development mode (that is, a server that was started with the noiterativedev flag passed to the startWebLogic command).

Production Build

When you are ready to deploy your application to a production server, you most likely want to perform a clean operation and then build the full application to generate an EAR file. This approach ensures that you have a consistent means of controlling the quality of your production application, and that you will not deploy unnecessary build artifacts to the production server. To perform a production build, you can use the Build->Build EAR command in the IDE, or the wlwBuild command from the command line.

The Build EAR menu command and the wlwBuild command perform a clean operation and build the complete application as they did in prior releases. If a project has enabled incremental build or disabled JSP pre-compilation, those settings are ignored when building an EAR using Build EAR or wlwBuild.

Developer Testing

If you are developing your application iteratively and testing it in a local or shared environment, you may want to build the EAR file incrementally in order to save time when testing frequent changes. Building

Page 27: webLogic

an EAR incrementally affects only Web and Web Service projects. When you build the EAR file incrementally, only those files and dependencies that have changed since your last build are built. No clean operation is performed, and existing build artifacts are not removed. Incremental build can speed up the process of deploying and testing changes to a Web or Web Service project.

Incremental build applies only to Web and Web Service projects where the Use Incremental Build property for the project is set to true. To build an EAR file where projects are built incrementally, use Build->Build EAR (Incremental) from the IDE, or specify the –incremental command line option when building from the command line with the wlwBuild command. For more information on building incrementally, see Using the Build Process More Efficiently.

When Do I Need to Clean Before Building?

The clean operation cleans all build artifacts resulting from a previous build of a project or application. It's a good way to "start over" so that you know that your build output includes only the most up-to-date files based on your source code. However, you don't need to perform a clean operation every time you build. You should clean your project or application in the following scenarios:

Streamlining Project and Application Size

When you rename or delete files in your application, the corresponding build artifacts are not deleted until you perform a clean operation. These extraneous build artifacts are generally harmless, but it's a good idea to clear them out now and then so that they don't slow down server startup and redeployment.

Building the Production Quality Application

Before you deploy your application to a production environment, you will probably want to perform a clean operation followed by a complete build in a controlled environment. In this way you can ensure that you have a formal, repeatable build process that you use every time you deploy an application to production.

Restoring the Server State

Occasionally a project can get out of sync with the server, and not function properly. When this happens, you should perform a clean operation to restore the state of the server.

Customizing the Build Process

WebLogic Workshop provides you with full control over the way you build JAR and EAR files from WebLogic applications and their projects. WebLogic Workshop accomplishes this by giving you complete access to the Another Neat Tool (ANT) XML build files that it uses to create these archives. You can customize the contents of these build files to specify the order in which WebLogic Workshop carries out build tasks, introduce new logic in between build steps, or integrate multiple build processes. WebLogic

Page 28: webLogic

Workshop gives you access to both application-level or project-level ANT build files. The following sections discuss how to edit and use both files to customize your WebLogic Workshop build process.

Customizing Project-Level Builds

If you want to customize the way WebLogic Workshop builds an individual project, you can use the WebLogic Workshop IDE to export the ANT build file that WebLogic Workshop uses to build that project. WebLogic Workshop exports an ANT XML build file entitled exported_build to the home directory of that project. Change this file using syntax that conforms to the Apache ANT Specification. When you are through making your changes, simply reference that file in the project settings of the WebLogic Workshop IDE. When you build the project, WebLogic Workshop will use that custom build file to create the project JAR. For details on customizing a WebLogic Workshop project build, see How Do I: Use a Custom Ant Build for a Project?

If you want to automate the build process, simply use the BEA_HOME/weblogic81/workshop/wlwBuild.cmd and use the appropriate command line switch to specify that you only want to build that individual project. For more information on this command, see wlwBuild command.

Application-Level Builds

If you want to customize the way WebLogic Workshop builds an entire application, you can also use the WebLogic Workshop IDE to export the ANT XML build file that WebLogic Workshop uses to build the application. Like the project-level ANT file, WebLogic Workshop exports an XML file entitled exported_build to the home directory of the application. Use syntax that conforms to the Apache ANT Specification to execute logic from other archives, alter the order of project builds based on some condition, or make any other custom adjustment. Unlike project builds, you cannot execute this build file from within the WebLogic Workshop IDE. Instead you must execute the file using an ANT script. For more information on customizing an application build, see How Do I: Call wlwBuild.cmd from an ANT build.XML file?

Excluding Files From an Application-Level Build

When you build a WebLogic Workshop application, the Workshop compiler creates an Enterprise Archive (EAR) file. You can control what files WebLogic Workshop includes in that EAR by editing the excludefilesFromEar attribute in the applications .work file. The excludefilesFromEar attribute is shown below in red:

Note that WebLogic Workshop automatically sets the value of this attribute to [default]. This excludes file types with the extensions app, ctrl, dtf, ejbbean, java, jcs, jcx, jpd, jpf, jsx, jwf, jws, and wlbean by default.

How Do I: Compile a Single Java File?

Page 29: webLogic

To selectively compile a single JAVA file, you can integrate a custom compilation script into the Workshop IDE by declaring the custom script as an "external tool". You can then pass single JAVA files from the IDE to the custom script.

Declaring a Custom Compilation Script as an "External Tool"

On Windows operating systems, open the the Workshop Preferences file located at C:\Documents and Settings\[Windows_user_name]\.workshop.pref.

Edit the element <component name="workshop.workspace.tools.CustomToolAction"> to include your custom compilation script. This element determines the options that appear in the menu bar Tools-->External Tools.

<component name="workshop.workspace.tools.CustomToolAction">

<node name="javac">

<option name="capture" value="true" />

<option name="command" value="compile.cmd "${file.path}"" />

<option name="directory" value="C:\build_scripts" />

<option name="interactive" value="false" />

</node>

</component>

The element <node name="javac"> causes a menu option named "javac" to appear on the menu bar Tools-->External Tools.

The element <option name="directory" value="C:\build_scripts" /> tells Workshop where to look for your build script (you can place the build script in any local directory).

The element <option name="command" value="compile.cmd" "${file.path}" /> tells Workshop to pass the currently open file to the build script.

Place the Custom Compilation Script in the Appropriate Directory

Save your build script in the directory specified in the element <option name="directory" value="C:\build_scripts" />. Below is a build script that you can use as a template.

compile.cmd

set PATH=D:\jdk1.4.2_04\bin;

set CLASSPATH=MyClasses

Page 30: webLogic

set CLASS_DIR=C:\bea\weblogic81\samples\workshop\SamplesApp\WebApp\WEB-INF\classes

javac -d %CLASS_DIR% -classpath %CLASSPATH% %1

echo compiled %1

popd

To compile a JAVA file, open the file in the Workshop IDE, and select Tools-->External Tools-->javac. The compile results will be displayed on the javac tab.

How Do I: Use a Custom Ant Build for an Application?

WebLogic Workshop uses a standard Ant build process for all applications. You can create a custom Ant build file for an application that extends the standard build process or uses different build targets altogether. If you want to extend or modify the standard build process, you should first export the standard application build file and begin by modifying that file.

To Export the Standard Application Build File

Choose Tools-->Application Properties to display the Application Properties dialog.

In the left-hand pane, select Build.

In the Build Type pane, click Export to Ant File. A dialog appears informing that the exported_build.xml file has been stored in the root of the application folder. Click OK.

The exported Ant file contains a set of standard tasks and targets for managing the build for your application.

Note the class workshop.core.WlwBuildTask called by the "wlwBuild" task is the same class called by the command line tool wlwBuild.cmd.

<taskdef name="wlwBuild" classname="workshop.core.WlwBuildTask"

classpath="${weblogic.home}/workshop/wlw-ide.jar"/>

The most important target in the Ant file is the "build" target.

<target name="build">

<!-- Builds the full application creating an ear at the specified location.

The server classpath parameter is used, but may be omitted if the server home directory

configured in Workshop is accessible. -->

<wlwBuild work="${app.dir}/${work.file}" serverclasspath="${server.classpath}">

Page 31: webLogic

<build outputdir="${output.dir}" outputfilename="${output.file}"/>

</wlwBuild>

</target>

Note that the following parameters are available for the "build" target:

project: String. Name of a specific project within the application to build. If omitted, the entire application will be built.

outputdir: String file path. Directory where build output file(s) will be placed. Defaults to application directory. May not be applicable for some types of project build.

outputfilename: String file path. Filename to use for output archive. Defaults to appname.ear. May not be applicable for some types of project build.

nodebug: Boolean value. Turns debugging information on or off. If no value is specified, the value is set to false.

noear: Boolean value. Specifies whether an EAR file should be generated for the application build. If no value is specified, the value is set to false. Not applicable for a project build.

To Create a Custom Ant Build File

You can use the standard exported build task and add additional build (sub)targets, or you can create a new ant file. To add a new task, you must use the <taskdef> element:

<taskdef name="myTask" classname="myTask" classpath="AllMyClass.jar"/>

Use the classpath attribute to specify the physical location of the JAR file as shown above, or you can specify the location when you change the project properties to use the custom build file as is described next.

You can also create a custom build process for an individual project within your application. Again, you should begin by exporting the standard build file and modifying that file.

To Export the Standard Project Build File

Open the target application in WebLogic Workshop.

From the Tools menu, select Project properties, then the target project name.

In the Project Properties dialog, from the left-side navigation panel, select the Build node.

In the section labeled Build Type, click the Export to Ant file button.

Page 32: webLogic

An Ant file named exported_build.xml is generated and placed in the project's root directory, e.g., BEA_HOME/weblogic81/samples/workshop/SamplesApp/WebServicesexported_build.xml.

To Use the Project Build File

Choose Tools-->Project Properties--><projectname> to display the Project Properties dialog.

In the left-hand pane, select Build.

In the Ant Settings area, click Browse, navigate to the new build file and click Open.

If your build file contains a new task definition without a classpath attribute, click Add JAR to specify the location of the Ant task. Navigate and select the file, then click Select JAR.

In the Build Type area, select Use Ant Build.

From the Build Target drop-down list, select the build target.

Click OK.

The Ant window will now appear in WebLogic Workshop, listing the various targets. From this window you can run a target by double-clicking it.

How Do I: Call wlwBuild.cmd from an Ant build.xml file?

The following topic explains how to create an Ant task that calls the command line tool wlwBuild.cmd. wlwBuild.cmd is used to create application-level EAR files or project-level JAR files for deployment to a production server.

To create an Ant build.xml file, you can either auto-generate a build.xml file or you can write the file by hand.

To auto-generate an Ant build.xml file for the application

Open the target application in WebLogic Workshop.

From the Tools menu, select Application properties.

In the Application Properties dialog, from the left-side navigation panel, select the Build node.

In the section labeled Export, click the Export to Ant file button.

An Ant file named exported_build.xml is generated and placed in the application's root directory, e.g., BEA_HOME/weblogic81/samples/workshop/SamplesApp/exported_build.xml.

The generated Ant file contains two tasks by default: "build" and "clean". When calling the build file from the command line, use the -f flag to name the file exported_build.xml:

C:\bea\weblogic81\samples\workshop\SamplesApp>ant -f exported_build.xml build

Page 33: webLogic

To build selected projects with the application, modify the <build> element within the exported_build.xml file. By adding the attribute project="Schemas", only the Schemas project will be build:

<target name="build">

<!-- Builds the full application creating an ear at the specified location.

The server classpath parameter is used, but may be omitted if the server home directory

configured in Workshop is accessible. -->

<wlwBuild work="${app.dir}/${work.file}" serverclasspath="${server.classpath}">

<build outputdir="${output.dir}" outputfilename="${output.file}" project="Schemas"/>

</wlwBuild>

</target>

See the documentation within the exported_build.xml file for more information about specifying output directories, output file names, etc.

You can also export an Ant build.xml file for building an individual project in much the same way as you do for the application.

To auto-generate an Ant build.xml file for a project

Open the target application in WebLogic Workshop.

From the Tools menu, select Project properties, then the target project name.

In the Project Properties dialog, from the left-side navigation panel, select the Build node.

In the section labeled Build Type, click the Export to Ant file button.

An Ant file named exported_build.xml is generated and placed in the project's root directory, Integrating with Source Control Systems

WebLogic Workshop integrates directly with the following source control systems: CVS, Perforce, and IBM Rational ClearCase. Once you have added the files in your WebLogic Workshop application to a respository managed by one of these source control products, you can check files in and out using commands available in WebLogic Workshop.

Enabling Source Control Integration in WebLogic Workshop

If you are part of a team development project and the application you are working on is already in a source control repository, you can simply point at that repository from WebLogic Workshop to enable

Page 34: webLogic

source control integration from within the IDE. After you enable source control integration, the source control module's commands are available to you in WebLogic Workshop. For example, when you right-click on a file you will see a menu item for the name of the source control module (CVS, Perforce, or ClearCase), and beneath that menu item, the commands available for working with the file.

For more information on enabling source control integration with one of these source control systems,

To Configure WebLogic Workshop for Source Control Integration

Configure your source control system as advised by your system administrator. In most cases you will need at least a client configuration that specifies how your computer interfaces with the source control system.

From the Tools menu, select Application Properties.

Click the Source Control tab.

From the Source control module drop-down, select Perforce, CVS, or ClearCase.

Set the properties for the source control module to map to the configuration on your computer.

If you want to enable source control integration only for a project within your application, or if you have different projects within different source control repositories, you can specify source control settings at the project level. From the Tools menu, choose Project Properties--><projectname>, click the Source Control tab, and clear the Use application's source control settings option.

Using Source Control Commands from WebLogic Workshop

Once you've configured Workshop for source control integration, you can perform commands against individual files in your application or project. There are two ways to execute source control commands:

Right-click the file and choose the name of the source control system you're using -- CVS, Perforce, or ClearCase. The commands available for that file are listed on the submenu.

Open the file in WebLogic Workshop. From the Tools menu, choose your source control system; the available commands are listed on the submenu.

Which Files Should You Add to Source Control?

There are a lot of files in a WebLogic Workshop application, and not all of them need to be checked in. The files which should be checked in are those that are not modified by the build process. These files include source files and some other files that are created with the project but never modified. The project can be built while any of these are read-only (for source control systems that govern read/write access), so that you only have to check out the files that you wish to modify.

The files to add to source control are:

Page 35: webLogic

The .work file that represents the application. It appears at the root of the application directory.

All source files that you have added or modified -- JWS, JCX, JSX, JSP, and so on.

Any XML schema files that you have added to the Schemas project.

The files in the Resources folder in a web project.

Any JAR files that you have added to the Modules folder. These files are stored at the root of your application in the file system.

Any JAR files that you have added to the Libraries folder. These files are stored in the APP-INF/lib folder in the file system.

The following files in the WEB-INF folder in a web project: web.xml, weblogic.xml, wlw-config.xml.

The global.app file in the WEB-INF/src/global folder.

The tag libraries that appear in the WEB-INF folder in a web project, if you have page flows and JSP files in your project. These files end with the .tld and .tldx extensions.

The JAR files that appear in the WEB-INF/lib folder in a web project.

The files that are modified by the build process -- compiled classes, for example -- do not need to be added to source control. You can add them, but you'll have to check all of them out each time you build your application. And since many of them are binary files and can't be modified directly, you don't gain anything by keeping them under source control; if you're developing your application as part of a team, putting these files under source control is likely to generate confusion for team members.

The files that you do not need to add to source control are:

Files in the .workshop directory beneath the base application directory

Files in the META-INF directory

Files in the WEB-INF/.pageflow-struts-generated directory in a web application project

Files in the WEB-INF/classes directory in a web application project

Files in the WEB-INF/lib directory in a web application project

JAR files that are generated from a project in your application

Modifying the .work File Under Source Control

There is currently no way to check out the .work file manually from within WebLogic Workshop in the same way that you can check out other files in your application. However, if the .work file is read-only,

Page 36: webLogic

and you make a change that requires modifying the .work file, WebLogic Workshop will prompt you to check it out.

Changes to your application which modify the .work file include:

Adding, importing, or deleting a project

Changing settings in the Application Properties dialog.

Changing settings in the Project Properties dialog.

Note: You should be careful about checking in the modified .work file when you are working in a team development environment. When you save the file, WebLogic Workshop may change the server.path variable within the file from a relative path to an absolute path to the server directory on your computer. Since it's unlikely that other users have the exact same absolute path on their computers, the application may not function properly after they sync to your change. Unless you specifically want to check in a change to the .work file, you generally want to revert your changes rather than checking them in. A good way to know is to perform a diff operation between the file that's in the source control repository and the modified file on your local computer. If you do want to check in changes to the .work file, you may need to edit the .work file manually using a text editor to change the server.path variable back to a relative path value.

ClearCase Source Control Integration

WebLogic Workshop integrates with the IBM Rational ClearCase. This topic describes how to put your Workshop application under source control with ClearCase.

WebLogic workshop integrates with these ClearCase products: ClearCase, ClearCase MultiSite and ClearCase LT, versions V2003, V2002 and V4.2.

Setting Up Source Control Integration with ClearCase

WebLogic Workshop supports integration with ClearCase for a Workshop application and all of its projects, or for an individual project with an application. In either case, all of the files of the Workshop application or project must be associated with a single ClearCase Version Object Base (VOB). This restriction also means that:

The mapping between the files in a Workshop application or project and the ClearCase VOB must be defined by a single snapshot view.

The root directory for the application or project must reside beneath the root directory for the ClearCase VOB. If the root directory for the application or project is in a subdirectory of the VOB root directory, then all of the parent directories must also exist in the VOB.

Page 37: webLogic

It's possible for a single Workshop application to contain multiple projects that are mapped to different VOBs and have separate associated views.

Note: We recommend that you create a snapshot view in ClearCase to map your Workshop project files to the ClearCase VOB. You may encounter unexpected behavior with Workshop if you are using a dynamic view.

To Add Your Workshop Application or Project to ClearCase

Make sure that you have a snapshot view that provides access to the VOB where your application or project files will reside. If you need help creating this view, see the ClearCase documentation or ask your system administrator.

Create a new Workshop application or project in a directory that is beneath the root directory for the VOB. If you are copying or moving an existing application or project, you should clean it before you add it to source control, so that build artifacts are not added along with source files. To clean an application, select the application name in the Application pane, right-click, and select Clean Application. To clean a project, select the project name in the Application pane, right-click, and select Clean <projectname>.

If you're adding an application to source control, select Tools-->Application Properties, then select the Source Control tab. If you're adding a project, select Tools-->Project Properties--><projectname>, then select the Source Control tab and clear the Use application's source control settings option.

Set the Source control module option to ClearCase.

Set the cleartool directory option to point to the location of the ClearCase cleartool utility. If you accepted the defaults on installation, the directory containing the cleartool utility should look something like C:\Program Files\Rational\ClearCase\bin. Note that you should include the path only, not the file name. The cleartool utility is the command-line utility that WebLogic Workshop uses to integrate with ClearCase.

Set the ClearCase Version option to your server version. Be sure to verify that you have specified the right version, as you may experience problems with ClearCase integration if the version is incorrect.

Set the ClearCase view type setting to snapshot, if you are using a snapshot view.

Set other options in the properties dialog as desired.

When you click OK, WebLogic Workshop will verify the location of the cleartool utility and will verify that the application or project's root directory is beneath the ClearCase VOB. If your view is a snapshot view, WebLogic Workshop will also prompt you to perform an update against the parent directory of the application or project root directory.

Adding Files to ClearCase

Page 38: webLogic

After you've configured WebLogic Workshop to integrate with ClearCase, you can add the files in your application or project to ClearCase through the IDE. To add a file, select the file in the Application pane, right-click, and choose ClearCase-->Add or Add and Checkin.

There are some differences between versions of ClearCase in terms of how files and directories are added to source control. These differences are outlined in the following sections:

ClearCase V2003

With ClearCase version V2003, when you add a file to source control, its parent directories are automatically added as elements and checked out. If you add the application or project root directory, the parent of this directory, which is not visible in the Workshop IDE, is automatically checked out. You must use an external ClearCase tool to check this directory back in. If you execute the Add and Checkin command on a file, the parent directories of the file are automatically checked in.

If you execute the Add and Checkin command on a directory, you must check in the parent directories of that directory manually in order to commit the addition.

ClearCase V2002 or Earlier

With ClearCase version V2002 or earlier, all parent directories must already exist in the VOB and must be checked out before you can add a file that resides in a subdirectory. You must check in all checked out parent directories to commit the operation.

Using External ClearCase Tools

In some situations you will need to use external ClearCase tools, such as ClearCase Explorer or the cleartool utility, to perform certain operations on files in your application or project. These operations include: Adding the .work file to ClearCase or checking it in. However, once you've added the .work file to source control, WebLogic Workshop will prompt you to check it out if you make a change that affects the .work file.

Adding, checking out, or checking in the parent directory of the root directory of the application or project. In version V2003 only, this directory will be automatically checked out when the root directory is added to ClearCase, but an external tool is required to check it back in.

Checking in a file that is not the most recent version on the branch.

The ClearCase Find Checkouts utility may be useful in conjunction with WebLogic Workshop. This utility shows all checkouts in the view, including those that are not visible in WebLogic Workshop, like the parent directory of the root directory of the application or project.

Checking Out Files

To check out a file from within WebLogic Workshop, right-click on the file in the Application pane and choose ClearCase-->Checkout.

Page 39: webLogic

If the file you are checking out is not the latest version in the VOB, you'll see a warning in the checkout dialog. At this point it's recommended that you dismiss the dialog and update the file before continuing. You can also choose to check the file out and merge your changes in with the head version in the VOB when you submit the file.

Note that you cannot check out a file that is writeable.

Stopping ClearCase Commands

Once in awhile a ClearCase command may fail to finish executing. If this happens, you can halt the command by right-clicking in the ClearCase window and choosing Stop. Once you've enabled ClearCase integration, the ClearCase window is available by choosing View-->Windows-->ClearCase.

Warning: Use caution when halting executing ClearCase commands, as doing so can have unpredictable or undesirable results.

Message Logging

WebLogic Workshop writes diagnostic information to files that you can use to track activities of a WebLogic Workshop application. These logging messages originate from two distinct sources: the run-time environment and the Integrated Development Environment (IDE).

Run-time Environment Logging

IDE Logging

You can use this information to diagnose unexpected behaviors or monitor the general progress of any WebLogic Workshop application. This topic describes how WebLogic Workshop reports diagnostic information and where it writes the information. This topic also explains how you can configure WebLogic Workshop to report additional information to suit your needs.

Run-time Environment Logging

The run-time environment refers to events that happen after you click the start button in the IDE and your application begins to run. These run-time events are logged to three files:

workshop.log

workshop_errors.log

workshop_debug.log

These three files are always co-located in the root directory of the domain under which your WebLogic Workshop application runs. For example, if you are running the SamplesApp application that ships with WebLogic Workshop, you can find this file in the /samples/domains/workshop/directory. This is because the SamplesApp application runs in the workshop domain.

Page 40: webLogic

workshop.log: WebLogic Workshop automatically writes all internal log messages to workshop.log. If you use log4j to add log messages to your application code, WebLogic Workshop will append those messages to workshop.log as well. For information about adding logging messages to your application code, see workshopLogCfg.xml Configuration File.

workshop_errors.log: WebLogic Workshop writes all warning and error messages to a file named workshop_errors.log.

workshop_debug.log: The workshop_debug.log file contains messages that are only useful to internal BEA developers, support representatives, and quality assurance representatives. You can ignore workshop_debug.log.

Customizing the Way WebLogic Workshop Logs Run-time Messages

You might want to customize the way WebLogic Workshop reports diagnostic information. For instance, you might want to log information to a console or database instead of a file. Perhaps you would like to adjust the way these messages appear in the log file. If you want to have better control over these details, you can do so by editing the workshopLogCfg.xml file. This is WebLogic Workshop's default log configuration file. You can locate workshopLogCfg.xml at /common/lib/.

The workshopLogCfg.xml file defines which run-time libraries report information, the type of information they report, the display format of that information, and the log files to which that information is written. You can customize any of these details by editing workshopLogCfg.xml. Alternatively, you can override the settings in workshopLogCfg.xml by providing your own custom configuration file. For guidance on both approaches, see workshopLogCfg.xml Configuration File.

IDE Logging: WebLogic Workshop also has an IDE logging feature, which logs various events from the IDE, such as events that occur during startup. IDE logging is off by default, but you can turn it on by following the steps in How Do I: Turn On IDE Logging?. These messages can help BEA technical support troubleshoot issues you may encounter when developing applications with WebLogic Workshop. WebLogic Workshop writes IDE-related log messages to a file named ide.log. You can find this file at /workshop/.

Sample

The data shown below is an excerpt from /workshop/ide.log.

DEBUG: extensions=C:\bea\weblogic81\workshop\\extensions

INFO: Registering extension com.bea.portal.ide.CommonServices

INFO: Service com.bea.portal.ide.findrefs.FindRefsSvc registered

INFO: Handler for urn:com-bea-portal-ide:ref-finders registered

INFO: Registering extension workshop.control.ControlServices

Page 41: webLogic

INFO: Service com.bea.ide.control.ControlSvc registered

...

...

DEBUG: WorkspaceLoaded: 11063ms

DEBUG: *** CompilerProject constructor 1

DEBUG: getClasspathMapping initiated with 21 item list.

DEBUG: getClasspathMapping returning 21 item map.

SourceLoader roots: 16

DEBUG: Document Panel initialized: 14017ms

DEBUG: Source Load: 2172

INFO: Startup Complete

DEBUG: Loading template file wsrp-producer-project.zip

Because this information is of minimal use to most WebLogic Workshop developers, WebLogic Workshop disables IDE logging by default. If you contact BEA technical support, representatives might ask you to enable logging in order to better diagnose IDE related issues.

Working with Java Controls

WebLogic Workshop provides Java controls that make it easy for you to encapsulate business logic and to access enterprise resources such as databases, legacy applications, and web services. There are three different types of Java Controls: built-in Java controls, portal controls, and custom Java controls.

Built-in controls provide easy access to enterprise resources. For example, the Database control makes it easy to connect to a database and perform operations on the data using simple SQL statements, whereas the EJB control enables you to easily access an EJB. Built-in controls provide simple properties and methods for customizing their behavior, and in many cases you can add methods and callbacks to further customize the control.

A portal control is a kind of built-in Java control specific to the portal environment. If you are building a portal, you can use portal controls to expose tracking and personalization functions in multi-page portlets.

You can also build your own custom Java control from scratch. Custom Java controls are especially powerful when used to encapsulate business logic in reusable components. It can act as the nerve center of a piece of functionality, implementing the desired overall behavior and delegating subtasks to built-in Java controls (and/or other custom Java controls). This use of a custom Java control ensures

Page 42: webLogic

modularity and encapsulation. Web services, JSP pages, or other custom Java controls can simply use the custom Java control to obtain the desired functionality, and changes that may become necessary can be implemented in one software component instead of many.

If you are connecting to an enterprise resource that exposes a standards-based, J2EE, or Web Services interface, you can create a custom Java control to directly connect to that application. However, if you are connecting to an external resource that is proprietary or does not expose standard J2EE APIs, you may need to use a JCA (Java Connector Architecture) adaptor and an Application View control rather than a Java control to connect to that resource. JCA adaptors and the Application View control are available through WebLogic Integration.

Getting Started with Java Controls

When you're building WebLogic platform applications, Java controls provide a convenient way to incorporate access to resources and encapsulate business logic. If you've used WebLogic Workshop, you may be familiar with built-in Java controls such as the Database control, EJB control, Web Service control, and so on. These are included with the IDE, but you can also create your own custom Java control. You can use controls from within the many kinds of components that make up WebLogic platform applications. A good practice is to use the custom Java control to implement your business logic and call built-in controls when the implementation of the business logic requires this.

This topic provides an overview of Java controls in platform applications. It includes the following sections:

What Are Java Controls?

Java controls are reusable components you can use anywhere within a platform application. You can use built-in controls provided with WebLogic Workshop, or you can create your own.

Note: In previous versions, controls were represented as CTRL files. While applications built with these controls are still supported, they are deprecated for future versions. You should build new applications with Java controls based on the new model.

Uses for Java controls. The framework that supports Java controls is flexible, supporting a wide variety of uses for controls. Java controls can:

Contain business logic you want to keep separate from other application code, or which may be reused.

Provide access to resources such as databases or other resources.

Collect logic that coordinates multiple actions, such as those that involve multiple database queries, calls to Enterprise JavaBeans (with the EJB control), and so on. A control participates in the implicit transaction of a conversational container, such as a web service that is conversational.

Built-in and custom Java controls. WebLogic Workshop provides several built-in controls, and you can build your own.

Page 43: webLogic

WebLogic Workshop provides several built-in controls, mostly designed to provide access to resources. For example, you can use the EJB control for access to Enterprise JavaBeans, the JMS control for access to the Java Message Service, and so on. For more information about the built-in controls, see Using Built-In Java Controls.

You can build your own controls that are based on the same framework on which built-in controls are based. You design a custom control from the ground up, designing its interface and business logic, adding other controls as needed. You can design a custom control for use in one project, or you can design a custom control for easy reuse in multiple projects. For more information about the custom controls, see Building Custom Java Controls. The tutorial, Tutorial: Java Control, provides a hands-on introduction to building custom controls. Much of this topic also includes information on building your own controls.

Java Controls in the IDE

Built-in Java controls, and custom Java controls that have been set up for use in multiple projects, are listed in the WebLogic Workshop Data Palette. By default, the Data Palette is displayed in the lower-right corner of the IDE. You can add new controls to a design by clicking the Data Palette's Add menu, as shown here:

When a control is in your design, its methods and callbacks are also listed in the palette. You can also drag methods and callbacks onto your design to create "pass-through" methods. A pass-through is a shortcut way to call a control's method from your current design.

Page 44: webLogic

Java controls appear in Design View, but will look slightly different depending on the file type you are designing with. The following illustrations show a custom (POVerify) and built-in (EJB control) Java control in various types of component source files.

Controls in a web service (JWS) design:

Page 45: webLogic

Controls in a JavaServer Pages (JSP) design:

Controls in a Java page flow (JPF) action view:

Page 46: webLogic

Controls in a Java control (JCS) design:

Building Custom Java Controls

You can build your own Java controls. Java controls you build are like those provided with WebLogic Workshop in that they provide a way to encapsulate business logic or access a resource, and yet expose a simple interface. However, unlike controls that are built into WebLogic Workshop, where you have access to an interface that extends the source, you can use your own control source files nested within the project that accesses the control. This makes Java controls particularly useful as containers for code that should reside in the same project but which is best kept separate.

Ways to Think About Custom Controls

Local controls and control projects. You can use controls locally as source, or group them into control projects.

A control is said to be local when its source files reside in the same project as the code that uses the control. This is the simplest way to use Java controls. You can create a JCS file, add methods and callbacks to it, then call the methods from code in the same project. This is most likely the way you will use Java controls you create. For step-by-step instructions on creating and using local Java controls, see How Do I: Create and Use a Custom Java Control Within an

Page 47: webLogic

Existing Project? You might also be interested in Tutorial: Java Control. For examples of local controls, see the SamplesApp application installed with WebLogic Workshop; there, look in the WebServices project, in its localControls subfolder.

Control projects provide a way to group related controls, and to package them for distribution among multiple projects. You create a control project just as you would other kinds of projects, then add files for your controls. The result of a control project is a JAR file you can distribute for use in any WebLogic Workshop application. By default, building a control project will automatically copy the resulting JAR to the Libraries folder of the application containing the project. Tutorial: Java Control includes information about packaging controls into a control project. The ControlProject project in the SamplesApp application installed with WebLogic Workshop is an example of a control project. For step-by-step instructions on beginning a control project, see How Do I: Create and Use a Java Control Within a Control Project?

Regular and customizable controls. Some controls provide a static interface, some are customizable.

Most of the custom controls you build will probably be regular controls. They don't provide a customizable interface. That is, their interface is already defined when an application developer adds them to an application. In this way, a regular control is like a library of reusable code. The built-in Timer control is an example of a regular control, as are the controls whose source code is included in the SamplesApp application installed with WebLogic Workshop.

Most of the built-in controls provided with WebLogic Workshop are customizable controls. That is, when you add a new one to a project, WebLogic Workshop generates a JCX file that extends the control. In some cases, such as with the Database control or JMS control, you can customize the control by adding or editing methods defined in the JCX file. Others are customized for you, as with the EJB control, which is customized based on the EJB the control will be accessing. Building customizable custom controls is an advanced subject beyond the scope of this documentation. For an example of a customizable custom control, see the JcxCreate sample in the ControlDevKit sample application available with WebLogic Workshop.

Working with Java Control Sources

Design view for custom controls. You begin building a Java control much as you would start building other WebLogic Workshop components. After you create a Java control source (JCS) file,

Design View provides a space in which you can create a visual representation of your control's interface as well as the controls it may itself be using. The Java control design space is very much like the web service design space. The left side displays operations that will be visible to the control's clients, while the right side displays nested controls.Note: You have easy access to a control's source file when the source is in the same project as the design you're editing. When you are building a web service, page flow, or Java control that includes a

Page 48: webLogic

control whose source is in the same project, you can double-click the control at the right side of the design to open its JCS.

When you add a new Java control source file to a project, WebLogic Workshop also adds a JAVA file that contains the control's public interface. By default, as you work in the JCS file, adding methods, callbacks, and implementation code, WebLogic Workshop keeps the interface in sync. For example, adding an operation to the JCS will also add a corresponding method to the JAVA file. Note that the JAVA file will be kept in sync only with respect to those methods with an @common:operation annotation. This means that if you add a method to the JCS, then remove it's @common:operation annotation, WebLogic Workshop will remove the method from the JAVA file.

For step-by-step information on beginning a Custom Java control, see How Do I: Begin a New Custom Java Control. You might also be interested in How Do I: Create and Use a Custom Java Control Within an Existing Project?

Properties for Java controls. Controls you create can expose properties. For example, the Database control provides properties that specify its database connection, log category name, and so on.

You define properties by creating an annotation XML file that describes them. You then associate the file with the control source code through the JCS file's control-tags property. When a developer is using the control, setting its properties, the settings are saved as annotations in the developer's code.

For step-by-step information on defining control properties, see How Do I: Define Properties for a Java Control?

IDE characteristics for a control. You can define certain IDE characteristics for your Java control. These include the icon that represents it in palettes and menus (and whether it is displayed in the palette at all), its description in the Property Editor, and so on. You'll find settings for these characteristics in the JCS file's jc-jar property. For more information, see How Do I: Specify IDE Characteristics for a Java Control?

Testing Java controls. While you can't "run" a JCS file in Test View, as you can with the similar JWS file, WebLogic Workshop does provide a shortcut for easy testing. You can generate a JWS file through which you can exercise the control's code as you're writing it. For more information, see How Do I: Generate a JWS File to Test a Java Control?

Keep in mind that testing isn't complete until you've tried out the control in all the scenarios you expect it to support. Whether the control's container is likely to be a JWS file, a JSP file, or a JPF file, it's a good idea to build a test application that uses your control for the purpose for which you've designed it.

Invoking a Control Method

Once you've added a Java control to your application, you can invoke the methods of the Java control from Source view using the standard Java dot notation. For example, assume that you have added the CustomerDb Java control and declared a variable for the control as custDb, and that the control defines a method as follows:

String [] getAllCustomerNames()

You can invoke this method from your code as follows:

String [] custNames;

custNames = custDb.getAllCustomerNames();

Page 49: webLogic

Overriding Control Property Settings

Note that when you declare a control (a JCS or JCX file) within a client you can override the control's default properties.

Suppose you have a database control with the connection property defined so that the data-source-jndi-name attribute points at the data source dataSource.

DatabaseControl.jcx

/** * @jc:connection data-source-jndi-name="dataSource" */ public interface DBControl extends com.bea.control.ControlExtension, DatabaseControl

The database control is declared with its default properties in the following way.

MyWebService.jws

/** * @common:control

*/private DatabaseControl dbControl;

To override the default connection property on the database control, use the following declaration.

/** * @common:control

* @jc:connection data-source-jndi-name="myOtherDataSource" */private DatabaseControl dbControl;

In the above declaration, the database control will use myOtherDataSource instead of its default dataSource. This override value will apply to all method calls from within MyWebService.jws.

There are two important caveats when overriding control properties in this way.

(1) The property must be at the class level, not the method level. Only those properties that are scoped to the entire control class may be overriden in this way.

(2) The override occurs at the property level, not at the attribute level. It not possible to override only a single attribute on a property. You must override all of the property's attribute values. For example, suppose that the connection property had three attributes instead of just one.

DatabaseControl.jcx

/** * @jc:connection data-source-jndi-name="dataSource" attribute2="value2" attribute3="value3" */ public interface DBControl extends com.bea.control.ControlExtension, DatabaseControl

In this case, when you override the connection property, you override all of that property's attributes, not merely the data-source-jndi-name attribute. In short, the following override sets the data-source-jndi-name attribute to myOtherDataSource and attribute2 and attribute3 to null.

Page 50: webLogic

MyWebService.jws

/** * @common:control

* @jc:connection data-source-jndi-name="myOtherDataSource" */private DatabaseControl dbControl;

For this reason, you should specify all of the attributes when you override a control property.

/** * @common:control

* @jc:connection data-source-jndi-name="myOtherDataSource" attribute2="otherVal2" attribute3="otherVal3" */private DatabaseControl dbControl;

Handling Control Method Exceptions

The designer of a Java control may choose whether or not to explicitly declare that exceptions are thrown by the control's methods. If a control method is declared to throw exceptions, you must enclose your invocations of that method in a try-catch block.

Even if the designer of the control chooses not to declare exceptions, the support code that implements the control can still throw exceptions. The type of exception thrown is com.bea.control.ControlException.

You should strongly consider handling all control exceptions that may be thrown by the controls you use in a web service. If you do not handle the exception, the web service method will fail and the exception will be passed on to the client of your web service. In most cases, the exception is useless to the client and the client does not have the necessary information to diagnose or remedy the problem.

Control Factories: Managing Collections of Controls

This topic describes control factories, which are collections of built-in or custom Java control instances.

What Is a Control Factory?

A control factory allows a single application to manage multiple instances of the same control. For example, imagine a credit approval application that accepts batches of approval requests (one per applicant) and uses an external web service, via a Web Service control, to evaluate the requests. The application could use a control factory to create multiple instances of the Service control and dispatch requests to the Service control instances in parallel. If the control uses callbacks, a single parameterized callback handler in the calling application handles the callbacks received from all of the control instances.You can only use control factories within a Java Web Service (JWS) or Java Process Definition (JPD) file. For more information on building Java Web Services with WebLogic Workshop, see Building Web Services. For more information on using JPD files, see Guide to Building Business Processes.

Automatically Generated Factory Classes

For any control interface called MyControl, WebLogic Server generates a control factory interface

Page 51: webLogic

called MyControlFactory that has the following very simple shape:

interface MyControlFactory{ MyControl create();}

The implicit factory class is located in the same package as the control class; that is, if the full classname of the control interface is com.myco.mypackage.MyControl, then the full classname of the factory is com.myco.mypackage.MyControlFactory. An automatic factory class is not generated if there is a name conflict (i.e., if there is already an explicit user class called MyControlFactory.). Therefore, if you want WebLogic Workshop to automatically generate factory classes for a built-in or custom control, make sure that the name of that control does not end with the word "Factory". A control factory instance can be included in a file just as a control instance can, with the same Javadoc annotation preceding the factory declaration that would precede a single control declaration.

For example, an ordinary Web Service control is declared as follows:

/** * @common:control */ MyServiceControl oneService;

Meanwhile, a Web Service control factory is declared as follows:

/** * @common:control */ MyServiceControlFactory manyServices;

Note again that the set of annotations allowed and required on a factory are exactly the same as the set of annotations on the corresponding control. The factory behaves as if those annotations were on every instance created by the factory. Once an application includes a control factory declaration, a new instance of a single control can be created as follows:

// creates one control MyServiceControl c = manyServices.create();

// then you can just use the control, store it, or whatever. c.someMethod();

// For example, let's associate a name with the service... serviceMap.put("First Service", c);

Factory classes are automatically generated on-demand, as follows. When resolving a class named FooFactory:

1. First the class is resolved normally. For example, if there is a CLASS file or JAVA file or JCX file that contains a definition for FooFactory, then the explicitly defined class is used.

2. If there is no explicit class FooFactory, then, since the classname ends in "Factory", we remove the suffix and look for an explicit class called Foo (in the same package).

3. If Foo is found but does not implement the Control interface (i.e., is not annotated with @common:control), it's considered an error (as if Foo were never found).

4. However, if Foo is found and implements the Control interface, then the interface FooFactory is

Page 52: webLogic

automatically created; the interface contains only the single create() method that returns the Foo class.

All instances of the control are destroyed when the application instance that created them is destroyed.

Parameterized Callback Handlers

Since there may be multiple controls that were created with a single control factory, and they all have the same instance name, a mechanism is provided to enable you to tell which instance of the control is sending a callback.

For example, for the oneService example above, an event handler still has the following form:

void oneService_onSomeCallback(String arg) { System.out.println("arg is " + arg); }

For callback handlers that are receiving callbacks from factory-created control instances, the callback handler must take an extra first parameter that is in addition to the ordinary parameters of the callback. The first parameter is typed as the control interface, and the control instance is passed to the event handler.

The manyServices factory callback handler looks like this:

void manyServices_onSomeCallback(MyServiceControl c, String arg) { // let's retrieve the remembered name associated with the control String serviceName = (String)serviceMap.get(c);

// and print it out System.out.println("Event received from " + serviceName); }

Developing Web Applications

Enterprise web applications today can easily contains hundreds, if not thousands of pages. These pages should not only look great visually, but also offer services to customers that require the implementation of complex business logic. Managing a complex web site can be a daunting task, especially where the business logic is implemented directly in the web pages, and changing the logic requires many edits in many locations.

WebLogic Workshop provides you with the tools to manage complex web applications using JavaServer Pages (JSPs) and Page Flows.

Separation of presentation and business logic allows for modularity of business logic implementation, such that the impact of changing business logic can be minimal. Furthermore, this separation allows the application developer to concentrate on implementing the business process using Java controls and EJBs, while the web developer can focus on the presentation. Page flows provide the navigational control, allowing a web application architect to easily design the flow between the JSP pages in the web application.

Guide to Building Page Flows

Page 53: webLogic

WebLogic Workshop provides you with the tools to develop web applications using JavaServer Pages (JSPs) and Page Flows, separating presentation, business logic, and navigational control to manage complexity. The topics in this section discuss these concepts and provide detailed information on how to use WebLogic Workshop to develop web applications based on page flows and JSP pages.

Why Use Page Flows?

By using page flows, you can avoid making the typical mistakes that often happen during web application development, by separating presentation, business logic implementation, and navigational control. In many web applications, web developers using JSP (or any of the other dynamic web languages such as ASP or CFM) combine presentation and business logic in their web pages. As these applications grow in complexity and are subject to continual change, this practice leads to expensive, time-consuming maintenance problems, caused by:

Limited reuse of business logic Cluttered JSP source code Unintended exposure of business-logic code to team members who focus on other aspects of

web development, such as content writers and visual designers

Page flows allow you to separate the user interface code from navigational control and other business logic. User interface code can be placed where it belongs, in the JSP files. Navigational control can be implemented easily in a page flow's single controller file, which is the nerve center of your web application. A controller file is a special Java file that uses a JPF file extension. Business logic can be implemented in the page controller file, or in Java controls that you call from JPF files.

The separation of presentation and business logic offers a big advantage to development teams. For example, you can make site navigation updates in a single JPF file, instead of having to search through many JSP files and make multiple updates. In WebLogic Workshop you can as easily navigate between page flows as between individual JSP pages. This allows you to group related web pages under one page flow, and create functionally modular web components. This approach to organizing the entities that comprise web applications makes it much easier to maintain and enhance web applications by minimizing the number of files that have to be updated to implement changes, and lowers the cost of maintaining and enhancing applications.

Another advantage of page flows is that an instance of the page flow controller class is kept alive on a per-user-session basis while the user is navigating within the scope of the page flow. This instance ends when the user exits from the page flow. You can use instance member variables in page flow classes to hold user session state.

For more information about the advantages of page flows, especially in comparison to "pure Struts" applications, see Advantages of Using Page Flows.

How Does a Page Flow Work?

A page flow is a Java class, called the "controller" class, that controls the behavior of a web application through the use of specially designed annotations and methods. The directory that contains the controller class also includes the JavaServer Pages (JSPs) used in the page flow. For a JSP to be considered part of a page flow, it must reside within the page flow directory. The JSP files use special tags which help bind to data and business logic actions. The action methods in the controller file implement code that can result in site navigation, passing data, or invoking back-end business logic via controls. Significantly, the business logic in the controller class is separate from the presentation code defined in the JSP files.

The overall purpose of a page flow is to provide you with an easy-to-use framework for building dynamic, sophisticated web applications. WebLogic Workshop provides graphical and code-level tools to simplify the development cycle. While page flows give you access to advanced features of J2EE, you do not have to be a J2EE expert to quickly develop and deploy Java-based applications built on page flows. Wizards can be used to create different types of page flows, generating the Java and JSP files

Page 54: webLogic

that serve as a starting point for your work. Graphical tools let you draw the relationships between web components in a controller's Flow View. In Source View, syntax completion, validation, and other programmer's aids reduce the amount of work required to get your application running.

Note: WebLogic Workshop's web application functionality is built on Struts, which is an open-source framework for building web applications in a J2EE environment.

Components of the Page Flow Programming Model

Page flows implement user interface control logic, and contain:

Action Methods Form Beans Forward Objects The Tag Library

Action Methods

In the controller class, action methods are methods that are annotated with a @jpf:action tag.

/** * @jpf:action * @jpf:forward name="success" path="page_A.jsp" */ protected Forward begin() { return new Forward( "success" ); }

Action methods can perform several functions. They can (1) implement navigation decisions, (2) move data into and out of JSP pages, and (3) invoke back-end business logic via calls to controls.

Form Beans

Form Beans are Java data structures that correspond to HTML forms. When a user submits data from an HTML form, the data is stored in a Form Bean instance. Once the data is stored in a Form Bean instance, the data is available for processing by the action methods in the controller file. Form Bean instances (containing submitted data) are typically passed as parameters to action methods.

/** * @jpf:action */ protected Forward ProcessData( MyFormBean form ) {

//Submitted data is processed here...

}

Form Beans are simple Java classes contained within the controller file. They consist of some number of fields with setter and getter methods associated with those fields. Below is a Form Bean with one field, the String name, and setter and getter methods for that field. Form Bean must extend the class com.bea.wlw.netui.pageflow.FormData.

public static class MyFormBean extends FormData {

Page 55: webLogic

private String name;

public void setName(String name) { this.name = name; }

public String getName() { return this.name; }

Forward Objects

Forward objects are returned by action methods. They can be used to control navigation and pass data throughout the application.

The Tag Library

The tag library contains JSP tags specifically designed to work with the controller class. Tags in the library all begin with the prefixes "netui", "netui-databinding", and "netui-template". Some of these tags perform much like familiar HTML tags, while others perform function particular to page flow web applications. The most important feature of the tag library is its ability to "data bind" to data in the controller file. Data binding allows the JSP pages to both read from and write to Java code in the controller class. This is accomplished without placing any Java code on the JSP pages, greatly enhancing the separation of data presentation and data processing.

Flow, Action, and Source Views

In the WebLogic Workshop IDE, you can switch between the Flow View, Action View, and Source View to create, modify, and view page flow components. Let's start with a simple page flow to understand the basic icons you will encounter in the Flow View, and to find out how the Flow View relates to methods and object in the Source View. In the example, navigation control is forwarded from one JSP to another. You can find this example in WebLogic Workshop at:

\weblogic81\samples\workshop\SamplesApp\WebApp\navigation\simpleNavigation\

Here is the Flow View diagram that we created for this page flow in WebLogic Workshop:

Page 56: webLogic

All page flow controller classes have a begin action method to define what happens each time this page flow is first navigated to. For this page flow, page_A.jsp is the first page that the user will see when the page flow's URL is accessed. The begin action is shown with a blue and green circular icon:

All other actions are represented by a blue circular icon in the Flow View:

Each JSP file that resides in a page flow's directory is shown on the Flow View, and is represented by a rectangular icon with a folded upper-right corner:

An arrow from a JSP page icon to an action icon indicates that the action can be invoked from the JSP page. For example, if there is a link on the JSP that calls the action method, this is depicted in Flow View by the following arrow.

An arrow from an action to a JSP page indicates that the execution of the action will load the target JSP page into the browser. For example:

The name of each action and JSP page is shown below the icon. The name on the arrow next to the action's circular icon corresponds to the logical name of the Forward object that is returned by the action method. The Forward object's role will be clearer when we look at the source code below.

In the WebLogic Workshop IDE, use the tabs at the bottom of the main window to switch between the graphical views and source view. When a page flow is open, its graphical representation is displayed in the Flow View window. You can switch to the page flow's graphical Action View or to its code-level Source View:

The Action View allows you to focus on a smaller portion of the page flow, for instance to examine a particular action and its form bean. The Source View is where you can customize the generated code and add business logic, or call controls that implement business logic.

Let's turn to a few examples that demonstrate some of the key features of navigational control and data processing.

Page 57: webLogic

Navigation: a Simple Example

As shown in the Flow View diagram, the page flow class defines an action method named toPageB. This action can be invoked by a link on the JSP page page_A.jsp.

... action="toPageB">Link to page_B.jsp

A special JSP tag library named netui-tags-html.tld is referenced. WebLogic Workshop provides this tag library and several others to help you develop dynamic web applications. The tag used here is simply invoking an action (toPageB) with a hyperlink. (For more information about the page flow tag library, see Designing User Interfaces in JSPs.)

In the controller file SimpleNavigationController.jpf, the toPageB action method is defined as follows:

SimpleNavigationController.jpf

import com.bea.wlw.netui.pageflow.Forward;

...

/** * @jpf:action * @jpf:forward name="success" path="page_B.jsp" */ public Forward toPageB() { return new Forward( "success" ); }

When the link on page_A.jsp is clicked, the page flow runtime detects the action and runs the toPageB action method. This action method is coded to return a Forward object which passes the parameter "success". (Notice that this name "success" matches the name on the corresponding action arrow in Flow View.)

Look at the two @jpf annotations that appear on the lines above this action method. These annotations are enclosed in Javadoc comments. The @jpf:action tag indicates that the toPageB method is an action method. The @jpf:forward tag describes the behavior of that method.

Putting it all together, a Forward object is returned by an action method. The Forward object passes the string "success", indicating that it should behave according to the directions encoded in the annotation @jpf:forward name="success". That annotation's path attribute has the value "page_B.jsp", which causes the page flow controller to load page_B.jsp into the browser.

The following diagram summarizes the flow in the example:

Page 58: webLogic

To change the navigation target of this action method, simply change the value of the path attribute. For example, if you want this action method to navigate to page_C.jsp, you would make the following change to the controller file (no change to the JSP page is necessary).

/** * @jpf:action * @jpf:forward name="success" path="page_C.jsp" */ public Forward toPageB() { return new Forward( "success" ); }

As you will see in later sections, the WebLogic Workshop IDE generates this code for you when you create a new page flow or JSP file from the graphical view. This code generation and subsequent validation of your changes saves you considerable time.

Submitting Data: A Simple Example

Suppose you want to your web application to collect data from users and then process that data in some way. The following example demonstrates how to set up a data submission process using page flows. The sample code referred to in this example can be found at:

\weblogic81\samples\workshop\SamplesApp\WebApp\handlingData\simpleSubmit\

Page 59: webLogic

Submitting data is a two step process: (1) the data submitted from a JSP page is loaded into a Form Bean instance and (2) the Form Bean instance is passed to an action method for processing.

Form Beans are simple Java classes with fields and setter and getter methods for accessing those fields. Form Beans classes are contained within the controller file. In most cases, Form Beans are designed to accept data submitted from JSP forms. For example, if a JSP page has input elements for name, eye_color, and height, then the Form Bean will have corresponding fields for name, eye_color, and height. The following example Form Bean can be found in the controller file SimpleSubmitController.jpf. It contains one field, name, and setter and getter methods for that field.

SimpleSubmitController.jpf

public class SimpleSubmitController extends PageFlowController { ... public static class SubmitNameForm extends FormData { private String name; public void setName(String name) { this.name = name; } public String getName() { return this.name; } } }

Page 60: webLogic

The input elements on the JSP page are said to be "data bound" to the fields in the Form Bean. Data binding allows the the data submitted from the JSP page to be loaded into the Form Bean instance. For example, the input element on index.jsp contains a data binding expression that refers to the name field of the Form Bean: {actionForm.name}. The expression "actionForm" refers to the Form Bean SubmitNameForm, the property ".name" refers to the name field of the Form Bean. For detailed information about data binding see Using Data Binding in Page Flows.

index.jsp

Name: ....

Finally the Form Bean instance (carrying the submitted data) is passed to the action method for processing.

/** * @jpf:action * @jpf:forward name="success" path="showName.jsp" */ protected Forward SubmitName(SubmitNameForm form) { // // The data is processed here //

return new Forward("success"); }

The submitted data can be accessed by calling the getter methods on the Form Bean.

/** * @jpf:action * @jpf:forward name="success" path="showName.jsp" */ protected Forward SubmitName(SubmitNameForm form) { if( form.getName() != null )

// do something here else // do something else here

return new Forward("success"); }

By default the Form Bean instance that is passed to the action method exists only as long as the HTTP request. This is called a "request-scoped Form Bean". When the HTTP request is destroyed, the Form Bean instance, along with the user submitted data, is destroyed. As an alternative, you can use a Page Flow-scoped Form Bean, which has a longer life cycle. For details see Form Bean Scopings.

Displaying Data: A Simple Example

Suppose that once you have collected data, you want to display it back to the user. The following example shows how to use data binding to display data to the user. The sample code referred to can be found at:

\weblogic81\samples\workshop\SamplesApp\WebApp\handlingData\simpleSubmit\

Page 61: webLogic

Displaying data using data binding requires that (1) the data is located somewhere where it can accessed by the JSP page and (2) the JSP page uses a data binding expression to retrieve the data from that location.

Notice the syntax of data binding expression on the JSP page. (1) It is framed by curley braces, (2) it begins with a data binding context, in this case the request context, and (3) the context is followed by an attribute, in this case "name".

In the following example, an action method places data on the name attribute of the request object.

SimpleSubmitController.jpf

/** * @jpf:action * @jpf:forward name="success" path="showName.jsp" */ protected Forward SubmitName(SubmitNameForm form) { getRequest().setAttribute("name", form.getName()); return new Forward("success"); }

After the data has been located on the name attribute of the request object, it is displayed on a JSP page using a data binding expression.

showName.jsp

Here is the data you submitted:

Note that the request object has a relatively short life-cycle. When the user makes a new request, by navigating to a new JSP page or invoking another action method, the current request object is destroyed along with the data it contains. If your application requires the data to be more persistent,

Page 62: webLogic

then you could use a different data binding context, for example the session object or a Page Flow-scoped Form Bean, which both have longer life-cycles. For detailed information about the different data binding contexts available, see Using Data Binding in Page Flows.

Advantages of Using Page Flows

This topic outlines the advantages of using page flows in your web applications. You may be familiar already with the Struts framework, which is a part of the Jakarta Project by the Apache Software Foundation™. Struts is an open-source framework for building Web applications based on the model-view-controller (MVC) design paradigm. WebLogic Workshop page flows extend the Struts framework to provide a simplified development model with numerous additional features:

Ease of use

Typically, native Struts development requires management and synchronization of multiple files for each Action, form bean, and the Struts configuration file. Even in the presence of tools that help edit these files, developers are still exposed to all the underlying plumbing, objects, and configuration details. Page flows provide a dramatically simpler, single-file programming model that allows you to focus on the code you care about, see a visual representation of the overall application flow, and easily navigate between pages, actions, and form beans. Page flows also provide a number of wizards to automate common tasks and visualize tag libraries. Furthermore, page flows provide key programming model benefits like thread safety. As a developer, this means that you can be insulated from some of the complexities that are pervasive in other web development models today like Struts and servlets. The result is that page flows enable you to become immediately productive in building sophisticated web applications, without the learning curve typically associated with Struts.

Nested page flows

Struts provides a useful framework for smaller applications, but has trouble scaling to larger applications. Every page and action is referenced from a single configuration file, and the manageability of applications and projects quickly degrades as the size of the application increases. But with the nesting feature of page flows, you can easily create smaller nested applications that are linked together, helping to enforce a modular design paradigm and supporting larger team development projects. Importantly, nested page flows automatically manage session state as a user moves between them, ensuring that the minimum possible level of system resources is used.

State management

Page flows make state management easy. You can put data in session state simply by using a variable in your JPF controller class, unlike with Struts action classes. Or you can easily pass data (as Java beans) to individual pages. Data stored in the session state is automatically freed as a user leaves the page flow for efficient use of session data.

Rich Data binding features

The WebLogic Workshop data binding tags and wizards make it easy to create rich, dynamic pages within a page flow. These features enable binding of user interface (UI) components to numerous data contexts (not just limited to form beans) and the data may come from any source: a database, a web service, an EJB, a custom application, and so on. In the IDE, you can drag-and-drop the data binding tags to your JSP page and bind to data, including complex types such as method invocations, repeating data, and grids. For more information, see Using Data Binding in Page Flows and Presenting Complex Data Sets in JSPs.

Service-oriented design with Java controls

Page 63: webLogic

Page flows have full support for Java controls, a simple programming model abstraction for accessing enterprise resources and packaging business logic. Java controls give developers access to the powerful features of the J2EE platform (security, transactions, asynchrony) in a simple, graphical environment with methods, events and properties, and enable developers to build Web applications conforming to best practices for service-oriented architecture. For more information, see Tutorial: Java Control.

Integration with Portal

Have a page flow? You can easily also have a portlet! Page flow applications can be instantly turned into portlets via a wizard in WebLogic Workshop. For more information, see How Do I: Create a Portlet? and How Do I: Add Portal Functionality to an Existing Page Flow Application?

Strong data typing

Struts treats all data as a String, making it difficult to work with rich form data. Page Flows, on the other hand, allow developers much easier access to strongly-typed data, making it a lot easier to work with form information.

Powerful exception handling

You can handle exceptions by pointing to local actions in your page flows, Page Flows, and handle not-logged-in errors globally across a set of page flows. This makes it much easier to manage errors and centralized login processes for your entire application versus managing a cloud of exception handler classes in Struts. WebLogic Workshop provides a number of exception types that represent common exception scenarios for page flow applications, such as ActionNotFoundException, LoginExpiredException, and UnfulfilledRolesException. For more information, see Handling Exceptions in Page Flows.

Iterative development experience

With the WebLogic Workshop IDE and page flows, you do not need to go through the tedious development cycle of edit, build, deploy, and test. Simply make a change in the IDE and click the Run button. The WebLogic Workshop model for automated deployment and integrated testing displays the results of your code change immediately. Plus, more errors are caught up-front through the WebLogic Workshop page flow compiler, instead of discovering the errors at runtime through exceptions or unintended behavior.

Built on the open-source Struts framework

While page flows provide a number of compelling advantages relative to Struts, keep in mind that page flows are based on Struts. This means that page flows can interoperate with existing Struts applications. You can always use the Struts Merge feature of page flows to obtain full access to underlying Struts artifacts and their configuration details. And page flows can interoperate with existing Struts applications, with both residing in the same web project. Also, with the page flow portability kit, you can run a page flow application on Apache Tomcat™ and any J2EE-compliant Servlet/JSP 2.3 container.

Designing Asynchronous Interfaces

Interactions between software components can be synchronous or asynchronous. An interaction is synchronous if the caller of a method must wait for the method's work to complete before the caller can continue its processing. An interaction is asynchronous if the called method returns immediately, allowing the caller to continue its processing without delay.An asynchronous interaction typically initiates a computation but does not wait for the result to be available, which means it must provide some way for the caller to obtain the results of the computation at a later time.

Page 64: webLogic

The distributed nature of web applications introduces unpredictable and sometimes very long latencies, which means it may take an operation a long time to complete. If a business process executing over the network involves human interaction at the back end, an operation can take on the order of days. If all interactions over the web were synchronous, clients with pending operations could consume resources on their host systems for unacceptably long periods of time.

WebLogic Workshop provides tools that make it easy for you to build asynchronous web services and Java controls that don't require clients to block execution while waiting for results. WebLogic Workshop provides multiple approaches for returning results to your web services' and Java controls' clients; you can choose the one that best suits each situation.

Getting Started: Using Asynchrony to Enable Long-Running Operations

WebLogic Workshop provides tools that make it easy for you to build asynchronous web services and asynchronous Java controls. This section introduces the concept of a callback, which is one of the critical design components when building an asynchronous web service or Java control, and describes the requirements for using callbacks. In addition, this section describes how to add buffering to methods and callbacks to enable the handling of high-volume traffic.

Introduction to Asynchronous Java Controls

Before reading this topic, you should understand the general concepts related to asynchronous interfaces. To learn about asynchronous interfaces, see Introduction to Asynchronous Interfaces.

In WebLogic Workshop, Java controls can have the same asynchronous behavior as web services. However, the behavior of a Java control is dependent on the nature of the Java control's client.

To understand this concept, think about how Java controls are used by their clients: the client is a web service, a page flow or another Java control and the Java control instance is declared as a member variable of the client. This means that the Java control instance cannot have a lifetime that exceeds that of its client.

Using Java Controls from Web Services

WebLogic Workshop web services can be conversational. Conversations allow you to control the lifetime of an instance of a web service. Since the lifetime of member variables of a web service is the same as the lifetime of the instance of the web service, Java controls references by a web service also have the same lifetime. Therefore, if a Java control's client is a web service the Java control may freely use callbacks to communicate with its client because the client is guaranteed to exist if the Java control instance exists. Note that the Java control's client must still explicitly implement handlers for each Java control callback it wishes to receive. To learn more about conversations and WebLogic Workshop web services, see Designing Conversational Web Services.

Using Java Controls from Page Flows

A page flow may also declare a Java control member variable. However, page flows ultimately represent web pages, and web pages operate on a strictly request-response basis from the user's browser. There is no way to "push" information to the browser with a browser-originated request initiated by or on behalf of the user. Since data cannot be "pushed" to the browser, it doesn't make sense to "push" data to a page flow, which is what a callback would represent. Therefore, page flows are not capable of receiving callbacks from a Java control.

However, it is possible to use an intermediary Java control with a polling interface to provide an "adapter" between a page flow and a Java control that uses callbacks. See Example 2, below, but substitute page flow for the non-conversational web service in the example.

Page 65: webLogic

With page flows, the limiting issue is not conversational lifetime as it is for web services. The limiting issue with page flows is the inability to "push" information out to the browser. The scenario in Example 2 below hides the "push" (the callback) in Java control A, which presents only a "pull" interface to its client. To learn more about polling interfaces, see Using Polling as an Alternative to Callbacks.

Using Java Controls from Other Java Controls

Whether callbacks can be sent form one Java control to another depends on the ultimate client at the end of the chain of Java controls. This is probably best illustrated by examples:

Example 1

Assume that you have a conversational web service that uses Java control A, which in turn uses Java control B. The lifetime of the Java control A instance is the same as the lifetime as the web service's conversation, and the lifetime of the Java control B instance is the same as that of Java control A (everything has the same lifetime: that of the web service's conversation). In this situation Java control B may use callbacks to communicate with Java control A, and Java control A may use callbacks to communicate with the web service.

Example 2

Assume the same situation as Example 1, but with a non-conversational web service. Since the web service is non-conversational, the lifetime of an instance of the web service spans only a single invocation of any of the web service's methods. Therefore the lifetime of the web services member variables, including its instance of Java control A, is the same, and the lifetime of the member variables of Java control A, including Java control B, is also the same. Java control A cannot use callbacks to the web service because once the web service method completes Java control A no longer exists. However, if Java control A were to provide a polling interface to be used by the web service, then Java control B may use callbacks to communicate with Java control A. Here is a scenario:

1. A web service client calls a web service method and an instance of the web service is created. 2. An instance of Java control A is created because it is a member variable of the web service. 3. An instance of Java control B is created because it is a member variable of Java control A. 4. The web service method calls the "start request" method of a polling interface provided by

Java control A. 5. The "start request" method of Java control A calls a "start request" method of Java control B

that will eventually result in a callback to Java control A. 6. The web service method repeatedly calls a "check status" method of Java control A. The

method returns false until the result is available. 7. When Java control B's work is completed, it calls a callback of Java control A. 8. The callback handler of Java control A stores the result. 9. The next time the web service calls the "check status" method of Java control A, it returns true. 10. The web service calls a "get result" method on Java control A. 11. The web service returns the result as the return value of the method invoked in step 1. 12. The web service instance is released, causing the release of the instance of Java control A and

in turn the release of the instance of Java control B.

Note that step 6 is not advisable if Java control B's work will take a long time. The initial request to the web service in step 1 may time out.

Designing Conversational Web Services

A single web service may communicate with multiple clients at the same time, and it may communicate with each client multiple times. In order for the web service to track data for the client during asynchronous communication, it must have a way to remember which data belongs to which client and to keep track of where each client is in the process of operations. In WebLogic Workshop,

Page 66: webLogic

you use conversations to uniquely identify a given communication between a client and your web service and to maintain state between operations.

Conversations are essential for any web service involved in asynchronous communication. This includes web services that communicate with clients using callbacks or polling interfaces, and web services that use controls with callbacks.

Best Practices for Designing Asynchronous Interfaces

This section discusses the best practices for creating and using web services and Java controls with asynchronous interfaces. The first topic describes how to use polling as an alternative to callbacks. Then, various design principles are recommended for designing web services and Java controls that can be called by both other web services and JSP (web) pages.

Designing Robust Asynchronous Interfaces

The preceding sections have presented various design options that can be included when building web services and Java controls. Given these options, what exactly constitutes a good design and creates a successful and robust web service or Java control? This topic explores several typical design solutions.

Do I Need an Asynchronous Interface?

The first question you might need to answer for a web service or Java control is whether the service or control needs to be asynchronous. There are certainly cases where a non-conversational, synchronous service or control will suffice, especially when the functionality it implements is relatively small, the request handling is relatively short, and the underlying infrastructure supporting this web service is solid, for instance if you are working on a fail-proof intranet or if your control is called by a (synchronous) web service on the same server. However, if any of these factors are not true or uncertain at the time of design, you will want to make your service or control asynchronous.

Do I Need to Use Callbacks?

Callbacks are a powerful approach to designing asynchronous web services or Java controls, relieving the client from periodically checking a request's status, as is required with polling. Especially when it is unclear how long a request will take to process, or if processing times vary wildly, using a callback is likely the most elegant implementation of asynchrony and loose coupling. Using callbacks in combination with buffering of both methods and callbacks is particularly effective in dealing with high-volume traffic. However, callbacks require that the client is designed to accept incoming messages and is hosted in an environment that supports message delivery.

Do I Need to Use Polling?

All asynchronous web services and Java controls should provide a polling interface. If the web service or Java control is asynchronous, a polling interface is required by any client that cannot accept callbacks; a polling interface is the only way such a client can obtain the results of operations initiated by asynchronous method invocations. You should think of a polling interface as the foundation interface of a web service or Java control, and callbacks as "extra" functionality that is convenient for clients who can handle callbacks.

The exception to this guideline is a Java control for which the only clients will be conversational web services or Java controls invoked by conversational web services. Conversational WebLogic Workshop web services can always accept callbacks. However, Java controls should be designed to be reusable. Assuming that the only clients a Java control will ever have are WebLogic Workshop web services limits the reusability of the Java control.

Page 67: webLogic

A Robust Web Service or Java Control

To create an asynchronous web service or Java control that is robust and handles all situations, it is recommended that you implement both a callback and a polling interface. Your design might (among others) include the following methods:

A start_request_asynch buffered method that the client will call to initiate a request. The method starts a conversation and notes that the callback mechanism will be used when the results are ready.

A callback_results buffered callback that sends the results to the client when the request is completed and finishes the conversation.

A start_request_synch buffered method that the client will call to initiate a request. The method starts a conversation and notes that the polling mechanism will be used when the results are ready.

A check_status unbuffered method that the client will periodically call to check the status of the request. The method continues a conversation and returns a Boolean value indicating whether or not the request has been completely handled.

A get_results unbuffered method that the client will call to get the results of the request. The method finishes the conversation.

Handling XML with XMLBeans

XMLBeans provides a simple, easy-to-use means for accessing XML. With XMLBeans, you can compile schema to generate Java types that can be bound to XML based on the schema. You can also access XML with schema by using an XML cursor, which provides an access model that is an alternative to DOM-based models.

Getting Started with XMLBeans

XMLBeans provides intuitive ways to handle XML that make it easier for you to access and manipulate XML data and documents in Java.

Characteristics of XMLBeans approach to XML:

It provides a familiar Java object-based view of XML data without losing access to the original, native XML structure.

The XML's integrity as a document is not lost with XMLBeans. XML-oriented APIs commonly take the XML apart in order to bind to its parts. With XMLBeans, the entire XML instance document is handled as a whole. The XML data is stored in memory as XML. This means that the document order is preserved as well as the original element content with whitespace.

With types generated from schema, access to XML instances is through JavaBean-like accessors, with get and set methods.

It is designed with XML schema in mind from the beginning — XMLBeans supports all XML schema definitions.

Access to XML is fast.

The starting point for XMLBeans is XML schema. A schema (contained in an XSD file) is an XML document that defines a set of rules to which other XML documents must conform. The XML Schema specification provides a rich data model that allows you to express sophisticated structure and constraints on your data. For example, an XML schema can enforce control over how data is ordered in a document, or constraints on particular values (for example, a birth date that must be later than 1900). Unfortunately, the ability to enforce rules like this is typically not available in Java without writing custom code. XMLBeans honors schema constraints.

Page 68: webLogic

Note: Where an XML schema defines rules for an XML document, an XML instance is an XML document that conforms to the schema.

You compile a schema (XSD) file to generate a set of Java interfaces that mirror the schema. With these types, you process XML instance documents that conform to the schema. You bind an XML instance document to these types; changes made through the Java interface change the underlying XML representation.

Previous options for handling XML include using XML programming interfaces (such as DOM or SAX) or an XML marshalling/binding tool (such as JAXB). Because it lacks strong schema-oriented typing, navigation in a DOM-oriented model is more tedious and requires an understanding of the complete object model. JAXB provides support for the XML schema specification, but handles only a subset of it; XMLBeans supports all of it. Also, by storing the data in memory as XML, XMLBeans is able to reduce the overhead of marshalling and demarshalling.

Accessing XML Using Its Schema

To get a glimpse of the kinds of things you can do with XMLBeans, take a look at an example using XML for a purchase order. The purchase order XML contains data exchanged by two parties, such as two companies. Both parties need to be able to rely on a consistent message shape, and a schema specifies the common ground.

Here's what a purchase order XML instance might look like.

Gladys Kravitz Anytown, PA 2003-01-07T14:16:00-05:00 Burnham's Celestial Handbook, Vol 1 5 21.79 2 Burnham's Celestial Handbook, Vol 2 5 19.89 2

ZipShip 0.74

This XML includes a root element, purchase-order, that has four kinds of child elements: customer, date, line-item, and shipper. An intuitive, object-based view of this XML would provide an object representing the purchase-order element, and it would have methods for getting the date and for getting subordinate objects for customer, line-item, and shipper elements. Each of the last three would have its own methods for getting the data inside them as well.

Looking at the Schema

The following XML is the the schema for the preceding purchase order XML. It defines the XML's "shape" — what its elements are, what order they appear in, which are children of which, and so on.

<xs:schema targetNamespace="http://openuri.org/easypo" xmlns:po="http://openuri.org/easypo"

Page 69: webLogic

xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

<xs:element name="purchase-order"> <xs:complexType> <xs:sequence> <xs:element name="customer" type="po:customer"/> <xs:element name="date" type="xs:dateTime"/> <xs:element name="line-item" type="po:line-item" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="shipper" type="po:shipper" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="customer"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="address" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="line-item"> <xs:sequence> <xs:element name="description" type="xs:string"/> <xs:element name="per-unit-ounces" type="xs:decimal"/> <xs:element name="price" type="xs:double"/> <xs:element name="quantity" type="xs:int"/> </xs:sequence> </xs:complexType> <xs:complexType name="shipper"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="per-ounce-rate" type="xs:decimal"/> </xs:sequence> </xs:complexType></xs:schema>This schema describes the purchase order XML instance by defining the following:

Definitions for three complex types — customer, line-item, and shipper. These are the types used for the children of the purchase-order element. In schema, a complex type is one that defines an element that may have child elements and attributes. The sequence element nested in the complex type lists its child elements.

These are also global types. They are global because they are at the top level of the schema (in other words, just beneath the schema root element). This means that they may be referenced from anywhere else in the schema.

Use of simple types within the complex types. The name, address, and description elements (among others) are typed as simple types. As it happens, these are also built-in types. A built-in type (here, one with the "xs" prefix) is part of the schema specification. (The specification defines 46 built-in types.)

A global element called purchase-order. This element definition includes a nested complex type definition that specifies the child elements for a purchase-order element. Notice that the complex type includes references to the other complex types defined in this schema.

In other words, the schema defines types for the child elements and describes their position as subordinate to the root element, purchase-order.

When you use the XMLBean compiler with an XSD file such as this one, you generate a JAR file containing the interfaces generated from the schema.

Page 70: webLogic

Writing Java Code That Uses the Interfaces

With the XMLBeans interfaces in your application, you can write code that uses the new types to handle XML based on the schema. Here's an example that extracts information about each of the ordered items in the purchase order XML, counts the items, and calculates a total of their prices. In particular, look at the use of types generated from the schema and imported as part of the org.openuri.easypo package.

The printItems method receives a File object containing the purchase order XML file.

package docs.xmlbeans;

import java.io.File;import com.bea.xml.*;import org.openuri.easypo.PurchaseOrderDocument;import org.openuri.easypo.PurchaseOrder;import org.openuri.easypo.LineItem;

public class POHandler { public static void printItems(File po) throws Exception { /* * All XMLBeans schema types provide a nested Factory class you can * use to bind XML to the type, or to create new instances of the type. * Note that a "Document" type such as this one is an XMLBeans * construct for representing a global element. It provides a way * for you to get and set the contents of the entire element. * * Also, note that the parse method will only succeed if the * XML you're parsing appears to conform to the schema. */ PurchaseOrderDocument poDoc = PurchaseOrderDocument.Factory.parse(po);

/* * The PurchaseOrder type represents the purchase-order element's * complex type. */ PurchaseOrder po = poDoc.getPurchaseOrder();

/* * When an element may occur more than once as a child element, * the schema compiler will generate methods that refer to an * array of that element. The line-item element is defined with * a maxOccurs attribute value of "unbounded", meaning that * it may occur as many times in an instance document as needed. * So there are methods such as getLineItemArray and setLineItemArray. */ LineItem[] lineitems = po.getLineItemArray(); System.out.println("Purchase order has " + lineitems.length + " line items.");

double totalAmount = 0.0; int numberOfItems = 0;

/* * Loop through the line-item elements, using generated accessors to * get values for child elements such a description, quantity, and * price. */

Page 71: webLogic

for (int j = 0; j < lineitems.length; j++) { System.out.println(" Line item: " + j); System.out.println( " Description: " + lineitems[j].getDescription()); System.out.println(" Quantity: " + lineitems[j].getQuantity()); System.out.println(" Price: " + lineitems[j].getPrice()); numberOfItems += lineitems[j].getQuantity(); totalAmount += lineitems[j].getPrice() * lineitems[j].getQuantity(); } System.out.println("Total items: " + numberOfItems); System.out.println("Total amount: " + totalAmount); }}

Notice that types generated from the schema reflect what's in the XML:

A PurchaseOrderDocument represents the global root element. A getPurchaseOrder method returns a PurchaseOrderDocument.PurchaseOrder type that

contains child elements, including line-item. A getLineItemArray method returns a LineItem array containing the line-item elements.

Other methods, such as getQuantity, getPrice, and so on, follow naturally from what the schema describes, returning corresponding children of the line-item element.

The name of the package containing these types is derived from the schema's target namespace.

Capitalization and punctuation for generated type names follow Java convention. Also, while this example parses the XML from a file, other parse methods support a Java InputStream object, a Reader object, and so on.

The preceding Java code prints the following to the console:

Purchase order has 3 line items. Line item 0 Description: Burnham's Celestial Handbook, Vol 1 Quantity: 2 Price: 21.79 Line item 1 Description: Burnham's Celestial Handbook, Vol 2 Quantity: 2 Price: 19.89Total items: 4Total amount: 41.68

Creating New XML Instances from Schema

As you've seen XMLBeans provides a "factory" class you can use to create new instances. The following example creates a new purchase-order element and adds a customer child element. It then inserts name and address child elements, creating the elements and setting their values with a single call to their set methods.

public PurchaseOrderDocument createPO(){ PurchaseOrderDocument newPODoc = PurchaseOrderDocument.Factory.newInstance(); PurchaseOrder newPO = newPODoc.addNewPurchaseOrder(); Customer newCustomer = newPO.addNewCustomer(); newCustomer.setName("Doris Kravitz"); newCustomer.setAddress("Bellflower, CA");

Page 72: webLogic

return newPODoc;}

The following is the XML that results. Note that XMLBeans assigns the correct namespace based on the schema, using an "ns1" (or, "namespace 1") prefix. For practical purposes, the prefix itself doesn't really matter — it's the namespace URI (http://openuri.org/easypo) that defines the namespace. The prefix is merely a marker that represents it.

Doris Kravitz Bellflower, CA

Note that all types (including those generated from schema) inherit from XmlObject, and so provide a Factory class. For an overview of the type system in which XmlObject fits, see XMLBeans Support for Built-In Schema Types. For reference information, see XmlObject Interface.

XMLBeans Hierarchy

The generated types you saw used in the preceding example are actually part of a hierarchy of XMLBeans types. This hierarchy is one of the ways in which XMLBeans presents an intuitive view of schema. At the top of the hierarchy is XmlObject, the base interface for XMLBeans types. Beneath this level, there are two main type categories: generated types that represent user-derived schema types, and included types that represent built-in schema types.

This topic has already introduced generated types. For more information, see Java Types Generated from User-Derived Schema Types.

Built-In Type Support

In addition to types generated from a given schema, XMLBeans provides 46 Java types that mirror the 46 built-in types defined by the XML schema specification. Where schema defines xs:string, xs:decimal, and xs:int, for example, XMLBeans provides XmlString, XmlDecimal, and XmlInt. Each of these also inherits from XmlObject, which corresponds to the built-in schema type xs:anyType.

XMLBeans provides a way for you to handle XML data as these built-in types. Where your schema includes an element whose type is, for example, xs:int, XMLBeans will provide a generated method designed to return an XmlInt. In addition, as you saw in the preceding example, for most types there will also be a method that returns a natural Java type such as int. The following two lines of code return the quantity element's value, but return it as different types.

// Methods that return simple types begin with an "x".XmlInt xmlQuantity = lineitems[j].xgetQuantity();// Methods that return a natural Java type are unadorned.int javaQuantity = lineitems[j].getQuantity();

In a sense both get methods navigate to the quantity element; the getQuantity method goes a step further and converts the elements value to the most appropriate natural Java type before returning it. (XMLBeans also provides a means for validating the XML as you work with it.)

If you know a bit about XML schema, XMLBeans types should seem fairly intuitive. If you don't, you'll learn a lot by experimenting with XMLBeans using your own schemas and XML instances based on them.

For more information on the methods of types generated from schema, see Methods for Types Generated From Schema. For more about the how XMLBeans represents built-in schema types, see XMLBeans Support for Built-In Schema Types.

Page 73: webLogic

Using XQuery Expressions

With XMLBeans you can use XQuery to query XML for specific pieces of data. XQuery is sometimes referred to as "SQL for XML" because it provides a mechanism to access data directly from XML documents, much as SQL provides a mechanism for accessing data in traditional databases.

XQuery borrows some of its syntax from XPath, a syntax for specifying nested data in XML. The following example returns all of the line-item elements whose price child elements have values less than or equal to 20.00:

PurchaseOrderDocument doc = PurchaseOrderDocument.Factory.parse(po);

/* * The XQuery expression is the following two strings combined. They're * declared separately here for convenience. The first string declares * the namespace prefix that's used in the query expression; the second * declares the expression itself. */String nsText = "declare namespace po = 'http://openuri.org/easypo'";String pathText = "$this/po:purchase-order/po:line-item[po:price <= 20.00]";String queryText = nsText + pathText;

XmlCursor itemCursor = doc.newCursor().execQuery(queryText);System.out.println(itemCursor.xmlText());

This code creates a new cursor at the start of the document. From there, it uses the XmlCursor interface's execQuery method to execute the query expression. In this example, the method's parameter is an XQuery expression that simply says, "From my current location, navigate through the purchase-order element and retrieve those line-item elements whose value is less than or equal to 20.00." The $this variable means "the current position." For more information about XQuery, see XQuery 1.0: An XML Query Language at the W3C web site.

Using XML Cursors

In the preceding example you may have noticed the XmlCursor interface. In addition to providing a way to execute XQuery expression, an XML cursors offers a fine-grained model for manipulating data. The XML cursor API, analogous to the DOM's object API, is simply a way to point at a particular piece of data. So, just like a cursor helps navigate through a word processing document, the XML cursor defines a location in XML where you can perform actions on the selected XML.

Cursors are ideal for moving through an XML document when there's no schema available. Once you've got the cursor at the location you're interested in, you can perform a variety of operations with it. For example, you can set and get values, insert and remove fragments of XML, copy fragments of XML to other parts of the document, and make other fine-grained changes to the XML document.

The following example uses an XML cursor to navigate to the customer element's name child element.

PurchaseOrderDocument doc = PurchaseOrderDocument.Factory.parse(po);

XmlCursor cursor = doc.newCursor();cursor.toFirstContentToken();cursor.toFirstChildElement();cursor.toFirstChildElement();System.out.println(cursor.getText());

cursor.dispose();

Page 74: webLogic

What's happening here? As with the earlier example, the code loads the XML from a File object. After loading the document, the code creates a cursor at its beginning. Moving the cursor a few times takes it to the nested name element. Once there, the getText method retrieves the element's value.

This is just an introduction to XML cursors. For more information about using cursors, see Navigating XML with Cursors.

Where to Go Next

XMLBeans provides intuitive ways to handle XML, particularly if you're starting with schema. If you're accessing XML that's based on a schema, you'll probably find it most efficient to access the XML through generated types specific to the schema. To do this, you begin by compiling the schema to generate interfaces. For more information on using XMLBeans types generated by compiling schema, see Java Types Generated From User-Derived Schema Types and Methods for Types Generated From Schema.

You might be interested in reading more about the type system on which XMLBeans is based, particularly if you're using types generated from schema. XMLBeans provides a hierarchical system of types that mirror what you find in the XML schema specification itself. If you're working with schema, you might find it helps to understand how these types work. For more information, see XMLBeans Support for Built-In Schema Types and Introduction to Schema Type Signatures.

XMLBeans provides access to XML through XQuery, which borrows path syntax from XPath. With XQuery, you can specify specific fragments of XML data with or without schema. To learn more about using XQuery and XPath in XMLBeans, see Selecting XML with XQuery and XPath.

You can use the XmlCursor interface for fine-grained navigation and manipulation of XML. For more information, see Navigating XML with Cursors.

Selecting XML with XQuery and XPath

You can use XQuery and XPath to retrieve specific pieces of XML as you might retrieve data from a database. XQuery and XPath provide a syntax for specifying which elements and attributes you're interested in. The XMLBeans API provides two methods for executing XQuery and XPath expressions, and two differing ways to use them. The methods are selectPath and execQuery, and you can call them from XmlObject (or an object inheriting from it) or XmlCursor. The results for the methods differ somewhat.

Using the selectPath Method

The selectPath method is the most efficient way to execute XPath expressions. The selectPath method is optimized for XPath. When you use XPath with the selectPath method, the value returned is an array of values from the current document. In contrast, when you use execQuery, the value returned is a new document.

Calling from XmlObject

When called from XmlObject (or a type that inherits from it), this method returns an array of objects. If the expression is executed against types generated from schema, then the type for the returned array is one of the Java types corresponding to the schema.

For example, imagine you have the following XML containing employee information. You've compiled the schema describing this XML and the types generated from schema are available to your code.

Fred Jones 900 Aurora Ave.

Page 75: webLogic

Seattle WA 98115 2011 152nd Avenue NE Redmond WA 98052 (425)555-5665 (206)555-5555 (206)555-4321 If you wanted to find the phone numbers whose area code was 206, you could capture the XPath expression in this way:

String queryExpression = "declare namespace xq='http://openuri.org/selectPath'" + "$this/xq:employees/xq:employee/xq:phone[contains(., '(206)')]"

Notice in the query expression that the variable $this represents the current context node (the XmlObject that you are querying from). In this example you are querying from the document level XmlObject.

You could then print the results with code such as the following:

/* * Retrieve the matching phone elements and assign the results to the corresponding * generated type. */PhoneType[] phones = (PhoneType[])empDoc.selectPath(queryExpression);/* * Loop through the results, printing the value of the phone element. */for (int i = 0; i < phones.length; i++){ System.out.println(phones[i].stringValue());}

Calling from XmlCursor

When called from an XmlCursor instance, the selectPath method retrieves a list of selections, or locations in the XML. The selections are remembered by the cursor instance. You can use methods such as toNextSelection to navigate among them.

The selectPath method takes an XPath expression. If the expression returns any results, each of those results is added as a selection to the cursor's list of selections. You can move through these selections in the way you might use java.util.Iterator methods to move through a collection.

For example, for a path such as $this/employees/employee, the results would include a selection for each employee element found by the expression. Note that the variable $this is always bound to the current context node, which in this example is the document. After calling the selectPath method, you would use various "selection"-related methods to work with the results. These methods include:

getSelectionCount() to retrieve the number of selections resulting from the query. toNextSelection() to move the cursor to the next selection in the list (such as to the one

pointing at the next employee element found).

Page 76: webLogic

toSelection(int) to move the cursor to the selection at the specified index (such as to the third employee element in the selection).

hasNextSelection() to find out if there are more selections after the cursor's current position. clearSelections() clears the selections from the current cursor. This doesn't modify the

document (in other words, it doesn't delete the selected XML); it merely clears the selection list so that the cursor is no longer keeping track of those positions.

The following example shows how you might use selectPath, in combination with the push and pop methods, to maneuver through XML, retrieving specific values. public void printZipsAndWorkPhones(XmlObject xml){ // Declare the namespace that will be used. String xqNamespace = "declare namespace xq='http://openuri.org/selectPath'";

// Insert a cursor and move it to the first element. XmlCursor cursor = xml.newCursor(); cursor.toFirstChild(); /* * Save the cursor's current location by pushing it * onto a stack of saved locations. */ cursor.push(); // Query for zip elements. cursor.selectPath(xqNamespace + "$this//xq:zip"); /* * Loop through the list of selections, getting the value of * each element. */ while (cursor.toNextSelection()) { System.out.println(cursor.getTextValue()); } // Pop the saved location off the stack. cursor.pop(); // Query again from the top, this time for work phone numbers. cursor.selectPath(xqNamespace + "$this//xq:phone[@location='work']"); /* * Move the cursor to the first selection, them print that element's * value. */ cursor.toNextSelection(); System.out.println(cursor.getTextValue()); // Dispose of the cursor. cursor.dispose();}

Using selections is somewhat like tracking the locations of multiple cursors with a single cursor. This becomes especially clear when you remove the XML associated with a selection. When you do so the selection itself remains at the location where the removed XML was, but now the selection's location is immediately before the XML that was after the XML you removed. In other words, removing XML created a kind of vacuum that was filled by the XML after it, which shifted up into the space — up into position immediately after the selection location. This is exactly the same as if the selection had been another cursor.

Finally, when using selections keep in mind that the list of selections is in a sense "live". The cursor you're working with is keeping track of the selections in the list. In other words, be sure to call the clearSelections method when you're finished with the selections, just as you should call the XmlCursor.dispose() method when you're finished using the cursor.

Page 77: webLogic

Using the execQuery Method

Use the execQuery method to execute XQuery expressions that are more sophisticated than paths. These expressions include more sophisticated loops and FLWR (For, Let, Where, and Results) expressions.

Note: Be sure to see the simpleExpressions sample in the SamplesApp application for a sampling of XQuery expressions in use.

Calling from XmlObject

Unlike selectPath, calling execQuery from an XmlObject instance will return an XmlObject array. If the XmlObject instances resulting from the XQuery match a recognized XMLBeans type (the namespace and top level element name match up with an XMLBeans type) then the XmlObject will be typed; otherwise the XmlObject will be untyped.

Calling from XmlCursorCalling execQuery from an XmlCursor instance returns a new XmlCursor instance. The cursor returned is positioned at the beginning of a new xml document representing the query results, and you can use it to move through the results, cursor-style (for more information, see Navigating XML with Cursors). If the document resulting from the query execution represents a recognized XMLBeans type (the namespace and top level element name match up with an XMLBeans type) then the document resulting from the xquery will have that Java type; otherwise the resulting document will be untyped.

Building Integration Applications

The integrated development environment in WebLogic Workshop includes a framework and tools for building WebLogic Integration applications. The topics in this section provide information about designing business processes that span applications, users, enterprise networks, and trading partners.

Tutorial: Building Your First Business Process

Provides a tour of the features available to design business processes for a WebLogic Workshop application by describing how to create a process that orchestrates the processing of a request for quote. Includes designing asynchronous communication with Web Service controls and Process controls, designing decision nodes, looping logic, parallel nodes, data transformations, Message Broker publish and subscription logic, and so on.

Tutorial: Building Your First Data Transformation

Introduces the basics of building a data transformation by describing how to create and test an XML-to-XML data transformation.

Guide to Building Business Processes

Describes how to build and test business processes using graphical tools. This topic includes how to design your business process logic, including designing looping constructs, decision nodes, switch nodes, interactions with clients and external resources, transactions, stateful and stateless processes, versioning business processes, and so on.

Guide to Data Transformation

Page 78: webLogic

Describes how to use the mapper functionality to create a data transformation graphically and how to import an existing eXtensible Stylesheet Language Transformation (XSLT) into WebLogic Workshop for data transformation.

Using Integration Controls

Describes how to use controls that make it easy to access enterprise resources, such as databases, file systems, Enterprise Java Beans, the Worklist, RosettaNet, ebXML, Trading Partner Management systems, and so on from within your application.

How Do I ...?

Provides step-by-step instructions for common tasks needed to build business processes, including creating new applications and business processes, and importing Schemas and Message Broker channel files. This topic also includes descriptions of the keyboard shortcuts and productivity accelerators you can use while building your business processes.

Java Class Reference

Provides reference information for WebLogic Integration API Javadoc for WebLogic Integration controls, business processes (JPDs), data transformation, Worklist, business calendars, WLXT, XML, and so on.

Annotations Reference

Provides reference information about WebLogic Integration-specific Workshop annotations, which are formatted like Javadoc tags.

Samples

Explains how to use samples that demonstrate WebLogic Integration functionality.

Building and Deploying Integration Applications

References information about building and deploying applications

as enterprise archive (EAR) files and as exploded directories.

Building Portal Applications

Welcome to portal development. This section of the help system provides overview information, reference topics, and procedures that guide you through the portal development process using the WebLogic Workshop Portal Extensions.

The WebLogic Workshop Portal Extensions provide more than a powerful, flexible, extensible framework for surfacing applications in portals. They also provide personalization, campaign, and behavior tracking services, a rules engine, JSP tags, integration services, intelligent administration, reusable samples, and a complete API.

Choose from the following subsections to learn more about WebLogic Portal, explore the power of the product with tutorials and samples, start developing or integrating your own portal applications, or access reference information.

Page 79: webLogic

Overview

Introduces portals and the WebLogic Portal architecture and provides guidance on getting started with WebLogic Portal.

Developing Portal Applications

Provides instructions on adding portal functionality to existing applications, developing new portal applications, and building portlets. This section includes information on integrating Web applications, struts applications, and Web services; building Web, JSP, Java Page Flow, and commerce applications; and creating portlets.

Developing Personalized Applications

Provides instructions for adding personalization and campaigns to your portal applications.

Developing Portal User Interfaces

Describes the WebLogic Portal user interface framework and provides instructions for creating a portal user interface and developing user interface resources. This section also provides guidance on building user interfaces to address accessibility guidelines.

Assembling Portal Applications

Provides instructions for assembling portals with existing portal resources, such as creating a portal file, adding books and pages to desktops, changing page layouts, changing the look & feel, and changing the shell.

Securing Portal Applications

Describes the security touch points in a portal development scenario and provides links to instructions that relate to those touch points. This section also describes how WebLogic Portal implements the WebLogic Server security service provider interface (SSPI).

Deploying Portal Applications (edocs)

Provides detailed information and best practices for deploying portal applications.

Portal Reference

Includes Javadoc for WebLogic Portal and partner APIs, a WebLogic Portal JSP tag reference, WebLogic Portal samples, and other reference information.

What is a Portal?

A portal represents a Web site that provides a single point of access to applications and information and may be one of many hosted within a single WebLogic Portal server.

Portals are becoming more and more important to companies, who have an ever-increasing need to provide employees, partners, and customers with an integrated view of applications, information, and business processes. WebLogic Portal meets these needs, allowing companies to build portals that combine functionality and resources into a single interface while enforcing business policies, processes, and security requirements, and providing personalized views of information to end users.

Page 80: webLogic

From an end user perspective, a portal is a Web site with pages that are organized by tabs or some other form of navigation. Each page contains a nesting of sub-pages, or one or more portlets—individual windows that display anything from static HTML content to complex Web services. A page can contain multiple portlets, giving users access to different information and tools in a single place. Users can also customize their view of a portal by adding their own pages, adding the portlets they want to it, and changing the look and feel of the interface.

The business problem that portals solve is illustrated in the following example. A company has the need for several types of Web presence: an Intranet for its employees, a secure site for interactions with partners, and a public Web site. WebLogic Portal’s flexible portal network architecture supports multiple implementation choices which allow re-use of resources across portals.

Portals in Java 2 Enterprise Edition (J2EE) Terms

From a J2EE standpoint, WebLogic Portal is an enterprise application consisting of Enterprise Java Bean (EJB) components and a set of Web applications. The enterprise application contains the core application programming interfaces (API), and the Web applications contain servlets, Java Server Pages (JSPs), JSP tag libraries, and supporting Java classes.

The WebLogic Portal architecture allows multiple portals per Portal Web application, letting you flexibly build and leverage Web application resources and security in multiple portal deployments.

Technically speaking, a portal is a container of resources and functionality that can be made available to end-users. These portal views, which are called Desktops in WebLogic Portal, provide the uniform resource location (URL) that users access.

Components that Make up a Portal

In WebLogic Portal, a portal definition is a single XML file. The XML file is created automatically as you build a portal with the Portal Designer that is provided as part of the WebLogic Workshop Portal Extensions. The portal file contains all the components that make up that particular instance of the portal, such as books, pages, portlets, and look and feel components.

Many components have a hierarchical relationship to each other. For example, a book contains pages and pages contain portlets. The Document Structure illustration shows the relationship between components in a portal file. Following are descriptions of the components that make up a portal interface.

Desktop - A desktop is is an audience specific view of portal components. It contains the portal header, footer, and body. The body contains the bulk of the portal content: books, pages, portlets, and look and feel elements. A portal can support one or more desktops. After a portal administrator sets entitlements on the desktop and makes it ready for public consumption, the desktop is the view of the portal accessed by end users. From there, users may configure their own views through customization of the desktop. Think of a desktop as a user view of a Web site or a portal, exposing a different set of information or tools based on user context. For example, each department in an organization (Human Resources, Accounting, Legal, Sales) can define a portal desktop containing its own portlets, navigation, and look and feel, yet these desktops are all supported by a single portal definition.

Shell - A desktop's header and footer, controlled by a portal shell (.shell file), are the areas that are typically above and below the main body. These areas usually display such things as personalized content, banner graphics, legal notices, and related links.

Page 81: webLogic

Book - A Book is a component that provides high-level content organization and navigation. Books contains pages or other books, providing a mechanism for hierarchical nesting of pages and content. Books are identified by a control such as a tab set.

Page - Pages contain the portlets that display the actual portal content. Pages can also contain books and other pages. Pages are identified by a control such as a tab set.

Layout and Placeholder - A layout is an HTML table definition used by a page to determine the physical locations of portlets on the page. Administrators and users can choose different available layouts for pages. Placeholders are the individual cells in a layout in which portlets are placed.

Portlet - Portlets are the windows that surface your applications, information, and business processes. They can contain anything from static HTML content to Java Controls to complex Web services and process-heavy applications. Portlets can communicate with each other and take part in Java Page Flows that use events to determine a user's path through an application. You can have multiple portlets on a page. You can also have multiple instances of a single Portlet. For example, you can put instances of a portlet on multiple pages; so that if users don't have rights to view one page with that portlet on it, they can see the portlet on a page they do have rights to view. Portlets can have different modes, such as minimize, maximize, edit, delete, configure, and help, selectable from their title bars.

Portal Rendering and Look and Feel Components (not shown in the illustration) - A desktop's appearance is determined by the Look and Feel. A look and feel definition contains two major elements: skins and skeletons.

Skins - Skins provide the overall colors, graphics, and styles used by all components in a desktop interface. Skins are collections of graphics and cascading style sheets (CSS) that allow changes to be made to the look and feel of a portal without modifying the portal components directly. References to images and styles are made in the skin rather than being hard coded into the portal definition. The look and feel file provides a path to the skin directory to be used. Themes are subsets of skins that you can apply to books, pages, and portlets, providing a way of using a different set of styles for individual desktop components.

Skeletons - The look and feel file also provides a path to the skeleton directory to be used. Every type of component, from a desktop to a portlet's title bar, has an associated JSP file, called a skeleton file, that renders it. Some skeleton files are simple, others are more complex. For example, each desktop uses a skeleton file called shell.jsp that simply provides the opening and closing tags to render the desktop. A portlet title bar, on the other hand, has a skeleton file called titlebar.jsp that is more complex. It contains Java calls to various windowing methods in the API, references the button graphics to use on the title bar, and determines the placement of title bar elements with an HTML table definition.

After the logic in the skeleton servlets executes for a look and feel, components are rendered hierarchically into a single HTML instance that is the user view of the desktop.

Administrators and users can select from a list of available look and feel definitions, which changes the appearance, and sometimes the behavior, of a user's view of a desktop. For example, the header of one look and feel can contain a static graphic, while the header of another look and feel can contain a campaign that targets a user with personalized content from a content repository.

Portal Development Tools and Services

WebLogic Portal includes many powerful tools and services that make portal development fast and easy.

Designers and Samples - The WebLogic Workshop Portal Extensions include a Portal Designer and a Portlet Designer that provide graphical drag and drop functionality and grid-based property setting, letting you create a sophisticated portal in minutes. For example, you can create a portal file (that

Page 82: webLogic

appears with a default page), drag one of the sample JSPs from the file tree onto the default page, and a portlet is created for you automatically. You can then save the file and view the portal desktop in a browser.

Java Controls - WebLogic Workshop Enterprise Edition includes many powerful Java Controls that insulate developers from lower-level coding, reducing the lines of code they must write (and therefore reducing the number of bugs). WebLogic Portal provides several Java Controls to assist development of personalized applications, such as a User Profile Control and a Display Content Control.

Portal Java Controls increase developer productivity for application development. Instead of writing code to access an API or J2EE resource directly or even using JSP tags, a developer can insert the User Profile Control into a JSP or Java Page Flow and select the appropriate methods for retrieving and updating user profile information, determining whether or not a user exists, or retrieving a list of users based on search parameters.

JSP Tags - The WebLogic Workshop Portal Extensions include a library of JSP tags that let you perform useful tasks in JSPs with minimal coding.

Content Management - WebLogic Portal includes powerful content management functionality, letting you integrate and manage multiple content management systems in a single virtual content repository. As a developer you can query the repository and retrieve and display personalized content in your portal applications. The Virtual Content Repository is set up and managed in the WebLogic Administration Portal and supports the full development lifecycle.

Unified User Profile - WebLogic Portal includes a unified user profile service that lets you add, access, and manage users and their properties in a single logical location—even if the base set of user data is stored on an external system such as an LDAP server. The unified user profile is a key element in such things as triggering personalization, setting role-based administration, and creating end user entitlements to portal resources.

Personalization, Interaction Management, and Behavior Tracking - The Portal Resources Designer lets you define the properties, rules, and actions that display personalized Web content to users, send automatic e-mails, or provide automatic discounts. The designer lets you create campaigns, content selectors, placeholders, and user profile and other properties. The WebLogic Workshop Portal Extensions also provide a set of events for tracking user behavior in portals, and the designer lets you register any custom events you develop.

APIs - WebLogic Portal includes an extensive set of APIs you can use directly for custom application development. For example, the Expressions Package provides a set of expressions that let you construct complex content queries.

Creating a Portal

Creating a portal involves using the WebLogic Portal framework and tools to surface applications in a portal user interface. It also involves adding personalization, campaigns, and behavior tracking to your applications.

You can quickly and easily integrate your own applications into WebLogic Workshop and apply WebLogic Portal's framework, tools, and services to them, or you can create new portal applications in WebLogic Workshop.

The following sections guide you through the process of creating a portal:

Developing Portal Applications

Provides instructions on adding portal functionality to existing applications, developing new portal applications, and building portlets. This section includes information on integrating Web applications,

Page 83: webLogic

struts applications, and Web services; building Web, JSP, Java Page Flow, and commerce applications; and creating portlets.

Developing Personalized Applications

Provides instructions for adding personalization and campaigns to your portal applications.

Developing Portal User Interfaces

Describes the WebLogic Portal user interface framework and provides instructions for creating a portal user interface and developing user interface resources. This section also provides guidance on building user interfaces to address accessibility guidelines.

Assembling Portal Applications

Provides instructions for assembling portals with existing portal resources, such as creating a portal file, adding books and pages to desktops, changing page layouts, changing the look & feel, and changing the shell.

Creating a Portal Application and Portal Web Project

To create the necessary resources for portal development, you must do one of two things:

Option 1: Create a new portal application and add a Portal Web Project to it

or Option 2: Install Portal into an existing application and add a Portal Web Project to it

Following are the procedures for each option.

Option 1: To create new portal application and add a Portal Web project to it

Use this procedure to create a new portal application.

You do not need to perform these steps if you are developing on a shared domain and the portal application has already been created and stored in a version-control system. Simply synchronize to the current version of the domain to put the portal application on your machine.

1. If you have not yet created a portal domain on your development machine, create one with the Configuration Wizard. For instructions, see the Overview of Platform Configuration on the BEA's e-docs Web site.

Performing this step ensures you have a server (config.xml) for your portal application to use, as described later in this procedure.

2. Create a new portal application. In WebLogic Workshop Platform Edition, choose File -->New -->Application.

3. In the New Application window, select Portal Application in the right pane.4. In the Directory field, click Browse to set the location of the new application. The application

will be created in a subdirectory of the directory you select.5. Make sure the Name field contains the name of the application. This name will be the

application directory. 6. In the Server field, click Browse and select the config.xml file for the server (domain) you

want to use.

The config.xml file is in the portal domain directory you created.

Page 84: webLogic

7. Click Create. The application directory appears in the Application window. The application contains the WebLogic Administration Portal (contained in Modules/adminPortal.war), a datasync directory (data) for interaction management development, and application-level EJBs and APIs.

8. Create a portal Web project for your application. Right-click the directory in the Application window, and choose New -->Project.

9. In the New Project window, select Portal Web Project in the right pane. 10. In the Project name field, enter the name for the portal Web project. This will be the name of

a Web application directory. 11. Click Create. The project folder appears in the Application window. The portal Web project

contains WebLogic Portal JSP tags, Web-application-level APIs, and default portal framework files.

12. If you have any external projects or files you want to include in your portal application, perform any of the following steps:

o To import a project, right-click the directory in the Application window and choose Import Project. In the Import Project window, select the type of project to import, browse to select the project folder, and click Import.

o To import files, such as existing datasync files (User Segments, Campaigns, Placeholders, and so on) or the Workshop Portal Extensions sample portlets to use in your portals , right-click the appropriate directory in the Application window and choose Import. In the Import Files window, select the directory or files you want to import, and click Import.

The sample portlets are located in \\samples\portal\portalApp\sampleportal\portlets. There are other useful sample files throughout the \\samples directory. See the instructions in Portal Samples for more information.

You now have the resources and directories for developing personalized applications and creating portals to surface applications.

13. Start your development server. In WebLogic Workshop, choose Tools-->WebLogic Server-->Start WebLogic Server. The server you assigned to your application in the previous steps starts. All your work is deployed automatically on your machine as you develop.

Option 2: To install portal in an existing application and add a Portal Web project to it

Use this procedure to add portal services to an existing application.

You do not need to perform these steps if you are developing on a shared domain and the portal-enabled application has already been created and stored in a version-control system. Simply synchronize to the current version of the domain to put the portal application on your machine.

1. In WebLogic Workshop Platform Edition, open the application in which you want to install portal.

2. In the Application window, right-click the directory and choose Install-->Portal. WebLogic Workshop adds the WebLogic Administration Portal (contained in Modules/adminPortal.war), a datasync directory (data) for interaction management development, and application-level EJBs and APIs.

3. Create a portal Web project for your application. Right-click the directory in the Application window, and choose New-->Project.

4. In the New Project window, select Portal Web Project in the right pane. 5. In the Project name field, enter the name for the portal Web project. This will be the name of

a Web application directory. 6. Click Create. The project folder appears in the Application window. The portal Web project

contains WebLogic Portal JSP tags, Web-application-level APIs, and default portal framework files.

7. If you have any external projects or files you want to include in your application, perform any of the following steps:

Page 85: webLogic

o To import a project, right-click the directory in the Application window and choose Import Project. In the Import Project window, select the type of project to import, browse to select the project folder, and click Import.

o To import files, such as existing datasync files (User Segments, Campaigns, Placeholders, and so on) or the Workshop Portal Extensions sample portlets to use in your portals , right-click the appropriate directory in the Application window and choose Import. In the Import Files window, select the directory or files you want to import, and click Import.

The sample portlets are located in \\samples\portal\portalApp\sampleportal\portlets. There are other useful sample files throughout the \\samples directory. See the instructions in Portal Samples for more information.

You now have the resources and directories for developing personalized applications and creating portals to surface applications.

8. Start your development server if it is not already running. In WebLogic Workshop, choose Tools-->WebLogic Server-->Start WebLogic Server. All your work is deployed automatically on your machine as you develop.

Developing Enterprise JavaBeans

These topics show how to develop Enterprise JavaBeans. WebLogic Workshop provides you with the tools to make EJB development much easier, taking care of many implementation details for you and allowing you to focus on design.

Note. WebLogic Workshop 8.1 supports the development, importing, and building of EJB2.0 compliant Enterprise JavaBeans. In addition, the WebLogic Platform supports the deployment only of EJB1.1 compliant Enterprise JavaBeans.

Getting Started with EJB Project

When you are building WebLogic platform applications, EJB project is the development environment for Enterprise JavaBeans. EJB project provides a number of tools that facilitate the development of the EJBs which encompass the business logic for your enterprise application. This topic provides an overview of EJBs and EJB project in platform applications. It includes the following sections:

What is an Enterprise JavaBean? What is EJB Project? EJB Project and ejbgen Tags Building and Deploying EJBs What are EJB Controls?

What is an Enterprise JavaBean?

An EJB is a server-side component that encapsulates the business logic of an application. The business logic is the code that fulfills the purpose of the application, as opposed to code that provides infrastructure and plumbing for the application. In an inventory control application, for example, the EJBs might implement the business logic in methods called checkInventoryLevel and orderProduct. By invoking these methods, remote clients can access the inventory services provided by the application.

Page 86: webLogic

EJBs always execute within an EJB container, which provides system services to EJBs. These services include transaction management, persistence, pooling, clustering and other aspects of infrastructure. The J2EE and EJB architecture is built on a number of underlying technology standards, such as the JDBC API for database connectivity, JMS for messaging, and JNDI for naming and directory functionality. To learn more about these technology standards, see your favorite J2EE documentation and http://java.sun.com.

In J2EE 1.4 there are three types of EJBs: session, entity, and message-driven. Each of these types is described briefly in the following sections.

Session EJBs

A session EJB is used to execute business tasks for a client on the application server. The session EJB might execute only a single method for a client, in the case of stateless session beans, or it might execute several methods for that same client, in the case of stateful session beans. A session bean is never shared by clients. A session EJB is not persistent, so when the client terminates, its session EJB disconnects and is no longer associated with the client.

Entity EJBs

An entity EJB represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. The persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table. Unlike session beans, entity beans are persistent, allow shared access, have primary keys, and may participate in relationships with other entity beans.

Message-Driven EJBs

A message-driven EJB is an enterprise bean that is able to listen for Java Message Service (JMS) messages. The messages may be sent by any JMS-compliant component or application. Message-driven EJBs provide a mechanism for J2EE applications to participate in relationships with message-based legacy applications.

EJB Interfaces

EJB 2.0 exposes four types of interfaces for session and entity beans, called the local home interface, the local business interface (or simply, the local interface), the remote home interface, and the remote business interface (or simply, the remote interface). Client applications can obtain an instance of the EJB with which to communicate by using the remote home interface. The methods in the remote home interface are limited to those that create or find EJB instances. Once a client has an EJB instance, it can invoke methods of the EJB's remote business interface to do real work. The business interface directly accesses the business logic encapsulated in the EJB. Interactions between EJBs defined in the same WebLogic Workshop application, as well as interactions between EJBs and web services or page flows in the same WebLogic Workshop application, can use the local interfaces instead, which provides a performance advantage over remote interfaces. In other words, the local home and business interfaces define the methods that can be accessed by other beans, EJB controls, web services, and page flows in the same WebLogic Workshop application, while the remote home and business interfaces define the methods that can be accessed by other applications.

Message-driven beans do not have these interfaces, because these beans' methods do not get invoked directly by other beans or client applications. Instead they process messages from client applications or other EJBs that are delivered via the Java Message Service (JMS). When a message is delivered, the EJB container calls the message-driven bean's onMessage method to process the message. For more information on Java Message Service, see your favorite J2EE documentation. WebLogic Workshop also provides JMS controls to work with a Java Message Service. For more information, see JMS Controls.

Page 87: webLogic

Deployment Descriptor

During runtime, information about how EJBs should be managed by the EJB container is read from a deployment descriptor. The deployment descriptor describes the various beans packaged in an EJB JAR file, settings related to transaction management, and EJB QL for find methods, to name a few examples. Deployment descriptor settings can be changed without having to make changes to the actual beans, allowing for the fine-tuning of EJBs.

EJB JAR

The EJB JAR contains one or more EJBs, including their interface definitions, any related Java classes that are being used by the EJBs, and a deployment descriptor describing these EJBs.

What is EJB project?

EJB project is the development environment for session, entity, and message-driven beans in a WebLogic platform application. An EJB project contains one or more EJBs. A WebLogic platform application can have one or more EJB projects, as well as other types of projects such as web (service) projects, and Java control projects, thereby creating an integrated development environment.

EJB project provides a Design View, property editor, building and debugging windows, and various wizards to facilitate the design and development of EJBs. For instance, in Design View you can define business (component) methods, define CMP fields, and define methods for local and/or remote interfaces. A property editor is used to edit deployment descriptor settings and ejbgen tag settings (see below). Various wizards make it easy to import EJBs into EJB projects, create ejbCreate methods, and define entity relationships. Build and debugging windows are used to monitor the build process and to monitor the EJB when running/debugging the application. For more information on the visual environment, see Summary of IDE Windows for EJB Project. For step-by-step instructions on using the Design View and the various wizards, see the 'How Do I...?' section Enterprise JavaBeans.

A key advantage of developing EJBs in EJB project is that one file is used to store the definition of the EJB class, its interfaces, and deployment descriptor specific settings. Instead of managing the overhead of using several java files to store this information, one file with an ejb extension is used to represent an EJB. This is accomplished by using ejbGen, which is described next.

EJB Project and ejbgen Tags

During Enterprise JavaBean development, special Javadoc tags with the prefix ejbgen are inserted in the EJB source file. These ejbgen tags are used to mark methods to be exposed in remote and home interfaces, store deployment descriptor settings, and various other types of information. In many cases you will not have to add these ejbgen tags directly. Instead these tags are added when, for example, you define a business methods to be local, or create a primary key field for an entity bean. You can also use the property editor to edit ejbgen tag settings.

The use of a single EJB file is only for development purposes. When you build an EJB Project, the build process uses these tags to generate the various interfaces and deployment descriptor files as prescribed in the J2EE specification.

Building and Deploying EJBs

When you build an EJB project, the EJBs' source code is compiled and checked for errors. The build output of an EJB project is an EJB JAR, containing the various JAVA and CLASS files for the bean class, its interfaces, and any dependent value or primary key classes, as well as the deployment descriptor for these beans. After the build completes, the beans are (re)deployed on the server. You can also deploy, undeploy and redeploy EJBs separately from building.

Page 88: webLogic

What are EJB Controls?

When you want to use an EJB from a client application (such as a page flow), you must look up the EJB in the JNDI registry and obtain the EJB's home interface, before you can create an EJB instance and invoke the EJB's business methods. EJB controls provide an alternative approach to make locating and referencing the EJB easy. Once you have created the EJB control, the client application can define the EJB control and use its methods, which have the same method names as the EJB it controls, to execute the desired business logic without having to be involved with locating and referencing the EJB itself. In other words, EJB controls take care of the preparatory work necessary to use an EJB, allowing you to focus on the business logic instead. For more information, see EJB Controls.

What are CMP Entity Beans?

An entity bean represents a business object in a persistent storage mechanism. In other words, entity beans are used to model real-world objects with properties that need to be stored and remembered over time. Examples of business objects are customers, products, orders, credit cards, and addresses. Typically, each entity bean has an underlying table in a relational database, and each bean instance corresponds to a row in that table. An entity bean has one or more primary keys, or unique indices, to uniquely identify an object, that is, a particular record in the database.

Container-managed persistence (CMP) entity beans are entity beans for which the EJB container takes care of mapping property and relationship fields to the underlying database and knows how to insert, update, and delete data for an entity bean.

Home and Business Interfaces

An entity bean can have four different interfaces, called the local home interface, the local business interface (or simply, the local interface), the remote home interface, and the remote business interface (or simply, the remote interface). The local interfaces define the bean's methods that can be used by other EJBs, EJB controls, web services, and page flows defined within the same application. That is, if you define an entity bean and only plan to use it within that application, you can use local interfaces. In contrast, the remote interfaces define the bean's methods that be invoked by EJBs, EJB controls, web services, and page flows defined in other applications.

To determine what interfaces are defined for an entity bean, ensure you are in Design View and go to the Naming section in the Property Editor. The Remote EJB and Local EJB sections refer to the remote and local interfaces; within each section the Home class name refers to the home interface, and the Bean class name refers to the business interface. In Source View, the attributes are part of the @ejbgen:file-generation Annotation. When you define a new entity bean, by default only the local interfaces are defined, reflecting the design assumption that in your model entity beans are not accessed directly by other client applications but indirectly, with session or message-driven beans defined in the same application as intermediaries.

Client applications and other session or entity beans can obtain an instance of an entity bean with which to communicate by using methods in the (remote or local) home interface. Methods in the home interface include create methods, the findByPrimaryKey method, and other finder methods that return a single reference or a set of references to entity bean instances. In addition, Home methods are defined in the local interface. The (remote or local) business interface contains the methods that manipulate an entity bean instance. These methods include field accessor (getter and setter) methods and component methods.

CMP Fields

Container-managed persistence (CMP) fields contain the business object's properties. For example, a Customer bean might contain first name, last price, gender, and age fields. Because the EJB container takes care of the mapping of these properties to a database, CMP fields are virtual fields in an entity bean; that is, these fields are not defined in the entity bean itself but correspond to columns in the

Page 89: webLogic

database table. The entity bean only defines the accessor (getter and setter) methods. A CMP field can serve as a primary key field, meaning that this field uniquely identifies the entity bean instance or, if multiple primary keys are defined, in combination with the other primary keys uniquely identifies the entity bean instance. For more information, see How Do I: Define a Container-Managed Persistence (CMP) Field?

Create Methods

An ejbCreate method is used to create a new instance of an entity bean, that is, insert a new record in the underlying database. At least one ejbCreate method must be defined, but multiple ejbCreate methods are not uncommon. Each ejbCreate method defined for an entity bean has the signature public ejbCreate(parameters). The can be a primitive type, such as Integer, when a single primary key is defined, or it can be a separate primary key class. By default, WebLogic auto-generates a primary key class, with the name provided as an attribute in the @ejbgen:file-generation Annotation. To find out which primary key class is used for an entity bean, ensure you are in Design View and go to the General section in the Property Editor. In Source View, this attribute is part of the @ejbgen:entity Annotation.

Multiple ejbCreate methods can only be distinguished by their parameter composition. In the home interface, ejbCreate methods are exposed as create methods and can correspondingly be distinguished only by the unique set of parameters each one requires. For more information, see How Do I: Add a Create Method to an Entity Bean?

Component Methods

Component methods are the business methods that are invoked on an entity bean instance. A simple example of a business method is updateCustomer(firstName, lastName, age), which is used to update the customer's first name, last name and age. This method will in turn invoke the bean's setFirstName, setLastName and setAge methods to update the CMP fields holding this information. For more information, see How Do I: Add a Component Method to an Entity or Session Bean?

Home Methods

A home method is a business method that relates to the entity bean but is not specific to a single bean instance. For instance, a Customer bean might have a home method returning the total number of customers between 25 and 35 years of age. A home method is defined as a ejbHome method in the bean, and is exposed as a method on the bean's home interface. For example the method ejbHomeGetNCustomers defined in the bean class is exposed as getNCustomers in its home interface. For more information, see How Do I: Add a Home Method to an Entity or Session Bean? and the Home Methods Sample.

Finder and Select Methods

Finder and select methods are methods that execute queries on the database, using the EJB QL or WebLogic QL query languages. A finder method is defined in the bean's home interface and returns a reference to a single bean instance or to a set of references to bean instances. In contrast, a select method is not defined in any interface and can only be invoked internally, for instance by a bean's component method. A select method can return a reference to a single bean instance, a set of bean instances, or one or more individual CMP fields.

In addition to the finder and select methods defined for the bean, the method findByPrimaryKey() is automatically defined by WebLogic in the home interface(s) defined for the bean class. This method returns a reference to the bean instance that is uniquely defined by the method's parameter. As before, the can be a primitive type, such as Integer, when a single primary key is defined, or it can be a separate primary key class. To find out which primary key class is used for an entity bean, ensure you are in Design View and go to the General section in the Property Editor. In Source View, this attribute is part of the @ejbgen:entity Annotation.

Page 90: webLogic

For more information on how to define finder or select methods, see How Do I: Add a Finder Method to an Entity Bean? and How Do I: Add a Select Method to an Entity Bean? For more information on the EJB QL and WebLogic QL query languages, see Query Methods and EJB QL, the Finder Methods Sample, and the Select Methods Sample.

Relations

Entity relationships are used to model dependencies between business objects. For example, a customer can have one or more credit cards, and a product has a manufacturer. Relations between two entity beans can be defined such that for a customer, you can easily access its credit cards by using the accessor method getCreditCards. The entity relation accessor methods, also known as the CMR field accessor methods are defined in the bean's business interface. For more information, see Entity Relationships, How Do I: Add a Relation to an Entity Bean?, and Tutorial: Enterprise JavaBeans.

Other Methods

An entity bean has several predefined methods, as well as a number of callback methods, invoked by the EJB container during certain operations, that an entity bean must implement. In WebLogic these callback methods are by default automatically implemented. In many cases you will find it unnecessary to use these methods, with the possible exception of the remove methods used to remove an entity bean instance. To learn more about predefined methods and remove methods in particular, see Defining an Entity Bean. To learn more about callback methods, see the Callback Methods section of that same topic and The Life Cycle of an Entity Bean.

Creating an Entity Bean

To create an entity bean, you can choose one of the following methods:

Create an entity bean from scratch. If you are designing a new entity bean in EJB project, you can define a new entity bean. To find out exactly how to do this, see How Do I: Create an Enterprise JavaBean? When you create a new entity bean, by default the local interfaces and various other defaults are defined. For more details, see @ejbgen:file-generation Annotation.

Create an entity bean from a database table. If you have already designed a database table and want to create an entity bean with CMP fields mapped to the database columns, you can create an entity bean from a database table. To find out exactly how to do this, see How Do I: Generate an Entity Bean from a Database Table? In addition to mapping the CMP fields and defining an ejbCreate method with the (compound) primary key as the parameter, by default local interfaces and various other defaults are defined. For more details, see @ejbgen:file-generation Annotation. After you have created an entity bean from a database table, you can further expand its definition, including making changes that will require changes to the underlying database table.

Import an entity bean. If you have developed entity beans in another development environment, you can import these into WebLogic. To import an EJB, you need the EJB Jar file as well as the source files. You can import multiple EJBs at the same time. If you import multiple entity beans with defined entity relations, these relation definitions will be imported as well. For more information, see How Do I: Import an Enterprise JavaBean? After you have imported an entity bean, you can enhance its definition.

Note. If you have existing entity beans that you plan to invoke in the application, for instance via another EJB or an EJB control, but you do not intend to change their definitions, you can suffice by adding the EJB Jar to the application. For more information, see How Do I: Add an Existing Enterprise JavaBean to an Application?

Automatic Table Creation

Page 91: webLogic

When you are developing a new entity bean using any of the three methods specified above, you can make iterative development easier by enabling automatic table creation. You can have WebLogic create the table when it is not present, and you can allow WebLogic to drop an existing table and recreate it if the definition of the entity bean does not match the table specifications. You enable automatic table creation using the create-table property located in the JAR Settings section of the Property Editor. The default setting is CreateOnly. To recreate a table if the definition of the entity bean does not match the table specification, use DropAndCreate. For more information regarding the possible settings, see @ejbgen:jar-settings Annotation.

Note. Automatic table creation is meant to facilitate development, and is disabled in production mode.

Defining a Basic Entity Bean

The following figure shows the design view of a basic entity bean called ProductBean:

This bean was developed by defining it from scratch, adding the two CMP fields, labeling one of these as the primary key, and creating an ejbCreate method (for more details, see How Do I: Add a Create Method to an Entity Bean?). These steps were accomplished in design view. This entity bean allows you to add a new product, find a product using its primary key, and getting and setting its CMP field values. The source code of this bean is given below:

package myBeans;

import javax.ejb.*;import weblogic.ejb.*;

/** * @ejbgen:entity prim-key-class="java.lang.String" * ejb-name = "Product" * data-source-name="cgSampleDataSource" * table-name = "product" * abstract-schema-name = "Product" * * @ejbgen:jndi-name * local = "ejb.ProductLocalHome"

Page 92: webLogic

* * @ejbgen:file-generation local-class = "True" local-class-name = "Product" local-home = "True" * local-home-name = "ProductHome" remote-class = "False" remote-home = "False" remote-home-name = "ProductRemoteHome" * remote-class-name = "ProductRemote" value-class = "False" value-class-name = "ProductValue" pk-class = "True" * */abstract public class ProductBean extends GenericEntityBean implements EntityBean{

/** * @ejbgen:cmp-field primkey-field="true" column="Name" * @ejbgen:local-method */ public abstract String getName();

/** * @ejbgen:local-method */ public abstract void setName(String arg);

/** * @ejbgen:cmp-field column="Price" * @ejbgen:local-method */ public abstract double getPrice();

/** * @ejbgen:local-method */ public abstract void setPrice(double arg);

public java.lang.String ejbCreate(java.lang.String Name, double Price) { setName(Name); setPrice(Price);

return null; // FIXME return PK value }

public void ejbPostCreate(java.lang.String Name, double Price) { }}

In WebLogic, all the information needed to make an entity bean is stored in a single file, instead of separate JAVA files for the bean class, the local business interface, the local home interface, its primary key class, and so forth. When you build an EJB, these other classes are auto-generated. Various ejbgen annotations are used to hold the information required to make this generation possible. For example, the @ejbgen:file-generation annotation specifies the names of the local home and business interface for the ProductBean. The @ejbgen:local-method annotations on the accessor methods specify that these methods are defined in the local business interface. To verify that these JAVA and corresponding CLASS files are generated, expand the JAR file created during a build (located in the Modules folder in the Application pane), and locate and open the generated files in the folder reflecting the package name. For the ProductBean, the ProductBean.java (bean definition), Product.java (local interface definition), and ProductHome.java (local home interface definition) files are auto-generated.

If the ProductBean were to use multiple primary keys, the ProductBeanPK.java file containing the definition of the compound primary key class would also be auto-generated. For instance, the following figure shows a redefined ProductBean with an additional primary key manufacturer:

Page 93: webLogic

Notice in the above figure that the compound primary key is the return value of the ejbCreate method. Also, the auto-generated method findByPrimaryKey(myBeans.ProductBeanPK primaryKey) uses the compound primary key to obtain a bean instance reference.

Finally a value object class can also be auto-generated. For more information, see the Value Object Sample

Removing an Entity Bean Instance

Any entity bean must define at least one ejbCreate method to create a new instance. Also, the EJB container automatically defines the findByPrimaryKey method in the home interface(s), which return a bean instance using its primary key (class) as the method parameter. In addition, all the bean's interfaces will extend a particular interface which contains various useful methods. Specifically:

The local interface extends javax.ejb.EJBLocalObject The local home interface extends javax.ejb.EJBLocalHome The remote interface extends javax.ejb.EJBObject The remote home interface extends javax.ejb.EJBHome

Complete details about these interfaces and the methods they define can be found in your favorite J2EE documentation and the API reference at http://java.sun.com. One of the more frequently used methods provided by these 'extended' interfaces is a remove method, used to remove an entity bean instance. In other words, when you invoke the remove method on an entity bean, you remove the bean and the underlying record in the database. Remove methods are defined in all the interfaces. For instance, to remove a bean instance via the local home interface, you can invoke a remove method that takes instance's primary key as the parameter. To remove a bean instance via the local interface, you can invoked the remove method for the instance you want to remove. Both approaches are shown below; the session bean's method deleteViaHome deletes an instance of the Product bean via its local home interface, while deleteViaBusiness delete a Product bean instance via the local interface:

/**

Page 94: webLogic

* ... * * @ejbgen:ejb-local-ref link="Product" */public class SomeSession extends GenericSessionBean implements SessionBean{ ...

/** * @ejbgen:local-method */ public void deleteViaHome(myBeans.ProductBeanPK thePk) { try { javax.naming.Context ic = new InitialContext(); ProductHome productHome = (ProductHome)ic.lookup("java:comp/env/ejb/Product"); productHome.remove(thePk); } catch(NamingException ne) { ... } catch(RemoveException re) { ... } }

/** * @ejbgen:local-method */ public void deleteViaBusiness(myBeans.ProductBeanPK thePk) { try { javax.naming.Context ic = new InitialContext(); ProductHome productHome = (ProductHome)ic.lookup("java:comp/env/ejb/Product"); Product theProduct = productHome.findByPrimaryKey(thePk); theProduct.remove(); } catch(NamingException ne) { ... } catch(FinderException ne) { ... } catch(RemoveException re) { ... } }

...}

Callback Methods

Every entity bean must implement the javax.ejb.EntityBean interface. This interface defines callback methods that are called by the EJB container at specific times. The callback methods are setEntityContext, unsetEntityContext, ejbActivate, ejbPassivate, ejbLoad, ejbStore, and ejbRemove. When you define an entity bean from scratch or via a database table, it will extend weblogic.ejb.GenericEntityBean, which contains empty implementations of these callback methods. In other words, you will only need to define these methods if you need to override the empty

Page 95: webLogic

implementation. If you import an entity bean, these callback methods will probably be implemented directly in the bean's ejb file.

For more details about the callback methods and their role in the interaction between the entity bean and the EJB container, see The Life Cycle of an Entity Bean.

Automatic Primary Key Generation

In WebLogic it is possible to automatically generate a primary key to be used when creating a new CMP entity bean instead of providing primary key values. You can auto-generate primary keys in various vendor-specific ways - using Oracle, SQLServer, or SQLServer2000 - or you can use a vendor-neutral named sequence table. In all cases auto-generated primary keys are of type Integer or Long.

The topics in this section are:

Primary Key Generation Using Oracle's Sequence Primary Key Generation Using SQL Server's IDENTITY Primary Key Generation Using a Named Sequence Table Defining the CMP Entity Bean

Primary Key Generation Using Oracle's Sequence

Oracle provides the 'sequence' utility to automatically generate unique primary keys. To use this utility to auto-generate primary keys for a CMP entity bean, you must create a sequence table and use the ejbgen:automatic-key-generation tag to point to this table.

In your Oracle database, you must create a sequence table that will create the primary keys, like is shown in the following example:

create sequence myOracleSequencestart with 1 nomaxvalue;

This creates a sequences of primary key, starting with 1, followed by 2, 3, and so forth. The sequence table in the example uses the default increment 1, but you can change this by specifying the increment keyword, such as increment by 3. When you do the latter, you must specify the exact same value in the cache-size attribute of the ejbgen:automatic-key-generation tag:

@ejbgen:automatic-key-generation type="Oracle" name="myOracleSequence" cache-size="3"

If you have specified automatic table creation in the CMP bean's project settings, the sequence table will be created automatically when the entity bean is deployed. For more information, see @ejbgen:jar-settings Annotation. For more information on the definition of a CMP entity bean, see below.

Primary Key Generation Using SQL Server's IDENTITY

In SQL Server (2000) you can use the 'IDENTITY' keyword to indicate that a primary-key needs to be auto-generated. The following example shows a common scenario where the first primary key value is 1, and the increment is 1:

CREATE TABLE Customer (Customer_ID int IDENTITY(1,1), FirstName varchar(30) LastName varchar(30))

Page 96: webLogic

In the CMP entity bean definition you need to specify SQLServer(2000) as the type of automatic key generator you are using. You can also provide a cache size:

@ejbgen:automatic-key-generation type="SQLServer"

If you have specified automatic table creation in the CMP bean's project settings, the sequence table will be created automatically when the entity bean is deployed. For more information, see @ejbgen:jar-settings Annotation. For more information on the definition of a CMP entity bean, see below.

Note. The SQLServer2000 option is the same as SQLServer, except that SQLServer uses @@IDENTITY column to get the generated key value and SQLServer2000 uses the SCOPE_IDENTITY() function instead.

Primary Key Generation Using a Named Sequence Table

A named sequence table is similar to the Oracle sequence functionality in that a dedicated table is used to generate primary keys. However, the named sequence table approach is vendor-neutral. To auto-generate primary keys this way, create a named sequence table using the two SQL statements shown in the example:

CREATE Table MyNamedSequence (SEQUENCE number);INSERT into MyNamedSequence VALUES (0);

In the CMP entity bean definition you need to specify the named sequence table as the type of automatic key generator you are using. You can also provide a cache size:

@ejbgen:automatic-key-generation name="MySequence" type="MyNamedSequenceTable" cache-size="100"

If you have specified automatic table creation in the CMP bean's project settings, the sequence table will be created automatically when the entity bean is deployed. For more information, see @ejbgen:jar-settings Annotation. For more information on the definition of a CMP entity bean, see the next section.

Note. When you specify a cache-size for a named sequence table, a series of unique values are reserved for entity bean creation. When a new cache is necessary, a second series of unique values is reserved, under the assumption that the first series of unique values was entirely used. This guarantees that primary key values are always unique, although it leaves open the possibility that primary key values are not necessarily sequential. For instance, when the first series of values is 10...20, the second series of values is 21-30, even if not all values in the first series were actually used to create entity beans.

Defining the CMP Entity Bean

When defining a CMP entity bean that uses one of the primary key generators, you point to the name of the primary key generator table to obtain primary keys, using the ejbgen:automatic-key-generation tag. Also, you must define a primary key field of type Integer or Long, to set and get the auto-generated primary key. However, the ejbCreate method does not take a primary key value as an argument. Instead the EJB container adds the correct primary key to the entity bean record.

The following example shows what the entity bean might look like. Notice that the bean uses the named sequence option describe above, and that ejbCreate method does not take a primary key: /** * @ejbgen:automatic-key-generation name="MyNamedSequence" type="NamedSequenceTable" cache-size="100" * * @ejbgen:entity prim-key-class="java.lang.Integer" * ejb-name = "Customer"

Page 97: webLogic

* data-source-name = "MyCustomerDataSource" * table-name = "customer" * abstract-schema-name = "Customer" * * ... */abstract public class Customer extends GenericEntityBean implements EntityBean{ ...

/** * @ejbgen:cmp-field primkey-field="true" column="Customer_ID" * @ejbgen:local-method */ public abstract Integer getCustomer_ID();

/** * @ejbgen:local-method */ public abstract void setCustomer_ID(Integer arg);

public java.lang.Integer ejbCreate(java.lang.String LastName, java.lang.String FirstName) { setLastName(LastName); setFirstName(FirstName);

return null; // FIXME return PK value }}

Entity Relationships

Entity relationships are used to model real-world dependencies between business concepts with CMP entity beans. This topics gives an overview of the seven relationship types, and for each of these relationships describes implementation details in the EJBs and the underlying database tables. For more detailed information, see your favorite J2EE documentation.

The topics in this section are:

One-to-One, Unidirectional One-to-One, Bidirectional One-to-Many, Unidirectional One-to-Many, Bidirectional Many-to-One, Unidirectional Many-to-Many, Unidirectional Many-to-Many, Bidirectional

One-to-One, Unidirectional

In a one-to-one unidirectional relationship, object A relates to object B. In addition, given object A you can find a reference to object B, but not the other way around. An example of such a relationship is between a concertgoer and a ticket, assuming the perspective of the ticket counter. Each concertgoer requires exactly one ticket, and the concertgoer will have a reference to his/her ticket. However, given a ticket you don't know the concertgoer. That is, if a lost ticket is returned to the ticket counter, it is not possible to trace it back to the concertgoer.

The Concertgoer EJB will have a CMR field to set and get a reference to a Ticket object. In contrast, there is no reference from the Ticket to the Concertgoer, meaning that there is no direct way to find out if a particular ticket has been assigned to a concertgoer or not and if it has, who the concertgoer

Page 98: webLogic

is. (To find this out, you would have to run a query on the Concertgoer EJBs and check each referenced ticket .)

In this particular example, Ticket objects are probably created independently of Concertgoer objects, and the CMR set method is used to associate the Concertgoer with the Ticket. Also, when the concertgoer returns the ticket (and removes himself from the ticket counter database), the Ticket object may not be deleted because it can be resold. When the one-to-one unidirectional relationship is more dependent, as between a Customer and his/her Address, the Customer EJB may have an setAddress business method, which creates a new Address object first, and then uses the CMR set method to set the reference, as is shown in the following code snippet:

public void setAddress(String street, String apt, String city, String state, String zip) throws CreateException { Address currentAddress = this.getAddress( ); if (currentAddress == null) { // Customer's current address not known. newAddress = addressHome.create(street, apt, city, state, zip); setAddress(newAddress); } else { // Update customer's current address. currentAddress.setStreet(street); currentAddress.setApt(apt); currentAddress.setCity(city); currentAddress.setState(state); currentAddress.setZip(zip); } }

Notice that first the CMR get method is used to get the reference to the current address. if the address is not known, a new address object is created after which the reference is set. If there is already a reference to an address, the address object is updated to reflect the new address.

When a customer is removed from the database, the home address can likely be removed as well. To do so, you can specify a cascade delete for this entity relationship, which automatically removes the home address when the customer is removed. For more information, see the @ejbgen:relation Annotation.

With respect to persistent storage of this relationship, one table will have the foreign key column information, that is hold the a copy of the primary key of the other EJB. Typically the Concertgoer table will have an 'Ticket_Index' foreign-key column holding the primary key value of the address (assuming that the Ticket EJB defines only one primary key field; if there are multiple primary key columns, there are multiple foreign key columns holding these values). It is, however, also possible that the Ticket table holds the primary key value of the Concertgoer. Regardless of the implementation in the database table, the EJB container will ensure that the relationship is correctly represented.

One-to-One, Bidirectional

In a one-to-one bidirectional relationship, object A relates to object B and both reference each other. An example of such a relationship is between a concertgoer and a creditcard, again assuming the perspective of the ticket counter. Each concertgoer has only one credit card (to purchase a ticket), and if a credit card is inadvertently left behind at the ticket counter, it can be returned to the owner.

The Concertgoer EJB will have a CMR field to set and get a reference to a CreditCard object. In addition, the CreditCard object will have a CMR field to set and get a reference to a Concertgoer object. Also, the bidirectionality of this relationship is ensured by the EJB container. That is, when you use the Concertgoer's CMR set method to set a reference to a CreditCard object, the CMR field of the

Page 99: webLogic

CreditCard object is automatically updated to hold a reference to this Concertgoer. Similarly, when you change or remove a reference in one object, this change is automatically applied to the other object. As far as creating and deleting the object a CMR field references, similar design considerations apply as discussed above for one-to-one unidirectional relationships. With respect to creating a new creditcard for a concertgoer, it is possible that the Concertgoer EJB has a business method setCreditCard, which creates a new creditcard record and then sets the reference, similar to the setAddress method shown above. If on the other hand the CreditCard EJB defines a create method that creates the CreditCard object and sets the reference to the Concertgoer object, the reference must be set in the ejbPostCreate step. An example of this is shown below.

With respect to persistent storage of this relationship, there is again quite some flexibility how this is implemented in the database tables. One of the possibilities is that only the ConcertGoer table has a foreign key column holding the primary key value of a creditcard. There are other possibilities as well. Regardless of the implementation in the database table, the EJB container will ensure that the relationship is correctly represented.

One-to-Many, Unidirectional

In a one-to-many unidirectional relationship, object A relates to many objects B, there are references from object A to all objects B, but not the other way around. An example of such a relationship is between a concertgoer and CDs purchased after the concert. A concertgoer can purchase many CDs, but for a purchased CD, again inadvertently lost and found, it is not possible to trace it back to the concertgoer who made the purchase.

The Concertgoer EJB will have a CMR field to set and get a Collection/Set of references to CD objects. In contrast, there is no CMR field in the CD object. The choice of java.util.Collection versus java.util.Set depends on whether from a design perspective it makes sense to have a collection with potentially duplicate references to the same object, or to have a set without duplicate references.

In this particular example, Concertgoer objects are probably created independently of CD objects, and a new reference is added to the CMR field uses the Collection/Set's add method, while a reference is deleted without deleting the CD object using the Collection/Set's remove method. When the relationship is more dependent, as between a Band and its Recordings, the Band EJB may have an addRecording business method, which creates a new Recording object first, and then adds it to the collection, as is shown in the following code snippet:

public void addRecording(String recording) throws CreateException { Recording album = recordingHome.create(getBandName(), recording); Collection recordings = getRecordings(); if(album != null) { recordings.add(album); } }

Notice that this method first creates the album, then uses the CMR get method to obtain a collection of the current recordings of the band, and then adds the new recording to the collection. Without the last step the recording would be created, but would not be referenced by the band.

When the Band object is deleted from the database, it might or might not make sense to cascade delete its recordings, depending on the real-world scenario you are representing.

With respect to persistent storage of this relationship, the only possible implementation is for the CD table to have a foreign key column holding the primary value of the concertgoer. As you might notice, the model and the actual implementation are reversed; the EJB container again ensures that the relationship is correctly represented.

Page 100: webLogic

Note. WebLogic at present doesn't support the use of a join table to implement one-to-many relationships.

One-to-Many, Bidirectional

In a one-to-many bidirectional relationship, object A relates to many objects B, there are references from object A to all objects B, and each object B references object A. An example of such a relationship is between a concertgoer and a creditcard, assuming the perspective of the concertgoer. Each concertgoer can have many credit cards, and if a credit card is inadvertently lost, it can be returned to the owner. Notice that this is the second example of a relationship between a concertgoer and creditcard. Above a one-to-one bidirectional relationship was defined, assuming the perspective of the ticket counter instead of the concertgoer.

Note. Realize that one-to-many bidirectional relationships and many-to-one bidirectional relationships are conceptually identical and are therefore listed as one type of relationship.

The Concertgoer EJB will have a CMR field to set and get a Collection/Set of references to CreditCard objects. The CreditCard object will have a CMR field to set and get a reference to a ConcertGoer object. Again, the bidirectionality of this relationship is ensured by the EJB container. That is, when you set/add the reference to one of the EJBs, the reference is automatically updated for the other EJB. As far as creating and deleting the object a CMR field references, similar design considerations apply as discussed above.

With respect to persistent storage of this relationship, the only possible implementation is for the CreditCard table to have a foreign key column holding the primary value of the concertgoer.

Note. WebLogic at present doesn't support the use of a join table to implement one-to-many relationships.

Many-to-One, Unidirectional

In a many-to-one unidirectional relationship, many objects A relate to one object B, there is a reference from each object A to object B, but not the other way around. An example of such a relationship is between a concert and a venue, assuming the perspective of a concertgoer. There are many different concerts at the same venue but the concertgoer is probably less concerned to know the concerts given the venue. However, if the latter is a business requirement, you will model this as a one-to-many (venue-to-concerts) bidirectional relationship.

The Concert EJB will have a CMR field to set and get a reference to a Venue object. In contrast, the Venue object will not have a CMR field. When a new concert is scheduled, the venue likely needs to be known at this time. In other words, when you create a Concert object, the reference to the Venue object should be set as part of the create procedure, as is shown in the following example:

abstract public class ConcertBean extends GenericEntityBean implements EntityBean{ ...

public Integer ejbCreate(String bandName, Venue theVenue) { setBandName(bandName); return null; }

public void ejbPostCreate(String bandName, Venue theVenue) { setVenue(theVenue); }

...

Page 101: webLogic

Notice that ejbCreate sets the name of the performing band, while the reference to the Venue object is set in the corresponding ejbPostCreate method. References must by design always be set in the ejbPostCreate method, because the primary key(s) needed to set the reference may not be available yet until after creation of the object.

Cascade deletions will most likely not make sense for this relationship. That is, removing one concert should not lead to the destruction of the venue, as many other concerts are scheduled for this venue.

With respect to persistent storage of this relationship, the only possible implementation is for the Concert table to have a foreign key column holding the primary value of the venue.

Note. WebLogic at present doesn't support the use of a join table to implement one-to-many relationships.

Many-to-Many, Unidirectional

In a many-to-many unidirectional relationship, object A relates to many objects B, object B relates to many objects A, there are references from each object A to its objects B, but not the other way around. An example of such a relationship is between concertgoers and concerts. A concertgoer will attend many concerts, each concerts will attract many concertgoers, given a concertgoer you might want to know the concerts he/she attended, but given a concert you likely don't want to know the particular concertgoers that were attending it.

The Concertgoers EJB will have a CMR field to set and get a collection/set of references to Concert objects. In contrast, the Concert object will not have a CMR field. As far as manipulating the CMR field, and creating and deleting the objects the CMR field references, similar design considerations apply as discussed above. Cascade deletions typically do not make sense for many-to-many relationships.

With respect to persistent storage of this relationship, a join table is used. Each record in a join table has two foreign-key columns, one holding the primary key value of a concertgoer and the other holding the primary key value of the concert (again assuming that both EJBs are defined to have one unique primary key field).

Many-to-Many, Bidirectional

In a many-to-many bidirectional relationship, object A relates to many objects B, object B relates to many objects A, there are references from each object A to its objects B as well as references from each object B to its objects A. An example of such a relationship is between a passenger and a flight. A passenger can take multiple flights, a flight is typically booked by multiple passengers, given a passenger you want to know the flights, and for a flight you want to know exactly which passengers should be on the airplane.

The Passenger EJB will have a CMR field to set and get a collection/set of references to Flight objects. The Flight EJB will have a CMR field to set and get a collection/set of references to Passenger objects. As far as manipulating the CMR field, and creating and deleting the objects the CMR field references, similar design considerations apply as discussed above. In this particular example it is possible that a passenger books a flight for several passengers at the same time. You can use the Collection/Set's addAll method to add multiple references. Also notice that bidirectionality is again assured by the EJB container, and that cascade deletions typically do not make sense for many-to-many relationships.

With respect to persistent storage of this relationship, a join table is used. Each record in a join table has two foreign-key columns, one holding the primary key value of a concertgoer and the other holding the primary key value of the concert (again assuming that both EJBs are defined to have one unique primary key field).

The Life Cycle of an Entity Bean

Page 102: webLogic

The following figure shows the life cycle of an entity bean. An entity bean has the following three states:

Does Not Exist. In this state, the bean instance simply does not exist. Pooled. When WebLogic server is first started, several bean instances are created and placed

in the pool. A bean instance in the pooled state is not tied to particular data, that is, it does not correspond to a record in a database table. Additional bean instances can be added to the pool as needed, and a maximum number of instances can be set

Ready. A bean instance in the ready state is tied to particular data, that is, it represents an instance of an actual business object.

The various state transitions as well as the methods available during the various states are discussed below.

Moving from the Does Not Exist to the Pooled State

When WebLogic server creates a bean instance in the pool, it calls the callback method public void setEntityContext(EntityContext ctx). This method has the parameter javax.ejb.EntityContext, which contains a reference to the entity context, that is, the interface to the EJB container. The entity context contains a number of methods to self-reference the entity bean object, identify the caller of a method, and so forth. Complete details about the javax.ejb.EntityContext can be found in your favorite J2EE documentation and the API reference at http://java.sun.com.

If you want to use the EntityContext reference in the entity bean, you must implement this callback method and store the reference. In addition, this method is also frequently used to look up the home interface of other beans later invoked in one of the bean's methods. The following code sample shows both:

Page 103: webLogic

/** * @ejbgen:ejb-local-ref link="Recording" * * ... */abstract public class BandBean extends GenericEntityBean implements EntityBean{ private EntityContext ctx; private RecordingHome recordingHome;

public void setEntityContext(EntityContext c) { // store the reference to the EntityContext ctx = c;

// look up the home interface of the RecordingBean try { javax.naming.Context ic = new InitialContext(); recordingHome = (RecordingHome)ic.lookup("java:/comp/env/ejb/Recording"); } catch(Exception e) { System.out.println("Unable to obtain RecordingHome: " + e.getMessage()); } } 

...

The Pooled State

When a bean instance is in the pooled state, it is not tied to any particular business object. When in the pooled state, the methods defined in the home interface can be invoked, effectively transitioning it from the pooled to the ready state, with the exception of ejbHome methods. When a home method is invoked, a result that is not bean instance specific is returned to the caller, and the bean instance remains in the pooled state. Home methods in turn often invoke ejbSelect methods to query bean instances.

Moving from the Pooled to the Ready State

The following methods move a bean instance from the pooled to the ready state to represent a business object:

ejbCreate and ejbPostCreate. When the create method is invoked on the bean's home interface, the ejbCreate and ejbPostCreate methods are invoked. The bean instance moves to the ready state and represents this newly created business object. After creation, a (local or remote) reference to this object is returned to the caller, enabling the caller to invoke business methods on this instance. The ejbPostCreate method is used to set references to other entity beans as part of the creation of a new bean instance.

findByPrimaryKey. When this method is invoked on the bean's home interface with the (compound) primary key as the parameter, the bean instance moves to the ready state and represents the business object uniquely identified by the parameter. Also a (local or remote) reference to this object is returned to the caller, enabling the caller to invoke business methods on this instance.

Finder methods. When a Finder method is invoked on the bean's home interface, one or a set of references to objects matching the queries are returned to the caller. In many cases the corresponding bean instance(s) are not loaded with data and move to the ready state until at a later point when a business method is actually invoked on this object, a concept known as lazy loading. However, you can specify eager loading, that is, tell the EJB container to load (part of) the data and move the entity bean instance(s) to the ready state as a part of the finder method execution.

Page 104: webLogic

The Ready State

When a bean instance is in the ready state, it represent data for a business object. At this point any business method, that is any component method and accessor method, can be invoked on this object. (A component method may in turn call an ejbSelect method.) After a business method executes, the bean returns to the ready state to allow another business method invocation.

From the perspective of the EJB container, the execution of a component method is sandwiched between two synchronization steps:

1. Before a business method is executed, the EJB container updates the fields of the bean instance with the latest data from the database table to ensure that the bean instance has the latest data. Just after the data is updated, the EJB container invokes the callback method ejbLoad. If your entity bean needs to execute some custom logic as part of this synchronization step, you can use implement it using this callback method.

2. The business method executes and completes. 3. The EJB container now updates the database table to ensure that it contains the latest data

from the entity bean instance. In other words, if the business method changes data values, this synchronization step ensures these changes are stored. Just prior to updating the database table, the EJB container invokes the callback method ejbStore. If your entity bean needs to execute some custom logic as part of this synchronization step, you can implement it using this callback method.

Because a record in a database table can be accessed by multiple bean instances at the same time, these synchronization steps ensure that each bean instance always has the latest data. However, in some cases these synchronization steps might be overkill and unnecessarily slow down performance. For instance, an entity bean might be read-only, reading data that is changed rarely if at all. In these cases one can safely bypass the synchronization steps without risking violations to data integrity.

Moving from the Ready to the Pooled State

When a caller invokes a remove method to delete an entity bean instance and its underlying record in the database table, the EJB container will delete the bean instance. Just prior to deleting the instance, it will call the callback method ejbRemove. If your entity bean needs to execute some custom logic prior to deletion, you can implement it using this callback method. After the data is deleted, the bean instance returns to the pooled state. The bean instance is no longer tied to any particular business object, and can be used to execute a home method or one of the methods that will tie it to a new set of data and move it to the ready state.

Activation and Passivation

To more optimally manage resources, the EJB container might passivate a bean instance by moving it from the ready state to the pooled state. During passivation the entity bean instance is dissociated from the business object it represents, and become available to represent another set of data. Conversely, a passivated bean might be activated, meaning that it moves from the pooled to ready state to represent a business object.

It should be noted that the caller (a client application or another EJB) of the entity bean instance will be unaware of passivation having taken place. The caller's reference to the entity bean instance is still maintained and valid; that is, if the caller subsequently invokes a business method on this entity bean instance, an instance from the pooled state will be moved to the ready state to represent this business object.

A bean instance can be passivated when none of its business method are invoked. Passivation occurs after synchronization has completed, guaranteeing that the database has stored any changes to the

Page 105: webLogic

business object. Just prior to actual passivation, the callback method ejbPassivate is invoked. If your entity bean needs to execute some custom logic prior to passivation, you can implement it using this callback method.

When a previously passivated bean instance is activated to service business method invocation, the callback method ejbActivate is invoked. If your entity bean needs to execute some custom logic prior to activation, you can implement it using this callback method. For instance, you might use this callback method to reinitialize values of nonpersistent fields, that is, fields not stored in the database. After the callback method executes and completes, the synchronization - business method invocation - synchronization procedure described above follows as during any other business method invocation; that is, first synchronization happens during which the latest bean instance is updated with the latest data of the database, followed by the invocation of the ejbLoad callback method. After this completes the business method is invoked, and when this completes, the second synchronization happens during which the ejbStore callback method is invoked and the latest bean instance data is stored to the database.

Moving from the Pooled to the Does Not Exist State

To more optimally manage resources, or when WebLogic server shuts down, the EJB container might remove a bean instance from the pooled state to the does not exist state, allowing it to be garbage collected. Just prior to its destruction, the callback method unsetEntityContext is invoked. If your entity bean needs to execute some cleanup prior to garbage collection, you can implement it using this callback method.

Bean-Managed Persistence

When you use container-managed persistence (CMP) for entity beans, the EJB container handles the interaction with the underlying database. The EJB container ensures synchronization of data just prior and just after a business method executes , it deletes the underlying database record when the entity bean instance is deleted, for an ejbCreate method it inserts the data in the database, it automatically generates the findByPrimaryKey method and handles the database query to find a database record, and it interprets EJB QL and WebLogic QL queries on finder and select methods to generate the corresponding database queries. In most cases entity bean development is done using CMP.

In contrast, when you use bean-managed persistence (BMP) for entity beans, the EJB container will still provide a numbers of services (such as transaction management) but leaves the persistence management up to the bean class. Bean-managed persistence might be necessary when your bean represents an unusual set of data and/or interacts with a legacy system for data storage. The current topic introduces some of the main difference between CMP and BMP, and some of the main differences developing CMP entity beans in WebLogic. For detailed information on CMP bean development, see your favorite J2EE documentation.

Main Differences Between CMP and BMP

Compared to CMP, when you develop BMP entity beans you must take into account the following:

You are responsible for synchronizing the entity bean instance and the underlying database record before and after a business method invocation. To do so you must implement the callback methods ejbLoad and ejbStore. (The EJB container invokes the various callback methods for CMP and BMP entity beans alike.)

The ejbCreate method(s) must take care of storing the new data in the database. The findByPrimaryKey method must be explicitly defined and must take care of locating the

data corresponding to the (compound) primary key in the database. Removing the data from the database when a bean instance is removed must be handled by

the bean class. To do so you must implement the ejbRemove callback method. Query methods cannot be implemented using EJB QL or WebLogic QL. Instead the finder or

select method(s) must define the database queries.

Page 106: webLogic

BMP Implementation

When you define a CMP entity bean in WebLogic, you should take into account the following:

To create a new BMP entity bean file, the first step is creating it as you would a CMP entity bean. When the file is created and opened, go to source view and add persistence-type="bmp" to the @ejbgen:entity tag. When you close and re-open the file, you will notice that design view is no longer available and, correspondingly, that the various wizards to for instance add an entity relation or a create method are no longer available.

You need to add an @ejbgen:resource-ref tag to the datasource (the database). Because the EJB container doesn't handle persistence, you should remove the attributes data-source-name and table-name from the @ejbgen:entity tag.

The database table for the BMP entity bean is not created for you by WebLogic. You must define the table in the database.

You must define the property fields and accessor methods. You must define the findByPrimaryKey method and the various callback methods as mentioned

in the previous section. WebLogic will still generate the various interfaces for you. To that effect, you also still use the

appropriate @ejbgen tags to ensure that a particular method is added to the appropriate interface. The findByPrimaryKey method will automatically be added to the defined home interface(s).

What are Session Beans?

Session beans are used to execute business tasks for a client on the server. A session bean typically implements a certain kind of activity, such as ordering products or signing up for courses, and in executing the business rules typically invokes entity beans. For instance, ordering products is likely to involve stored information about products, customers, and credit cards, while signing up for courses is likely going to require invoking entity beans representing students and courses.

Stateful and Stateless

There are two types of session beans, stateful and stateless. A stateful session bean maintains conversational state. In other words, a stateful session bean remembers the calling client application from one method to the next. For a stateful session bean, the results produced by one method might be co-dependent on the results of its prior methods invoked by the same client. A stateful session bean maintains this conversation with the client until the conversation times out or the client explicitly ends the conversation by invoking the bean's remove method.

In contrast, a stateless session bean does not maintain any conversational state, that is, it does not remember which client invoked one of its methods, and does not maintain an internal state between methods. Each session bean method is independent, and the only client input is the data passed in its parameters.

Stateful session beans are tied to a particular client for the duration of the conversation, while stateless session beans are only tied to a particular client for the duration of a method execution. After method execution completes, a stateless session bean is ready to serve another client application. Consequently, a small number of stateless session beans can be used to serve a large number of client applications. Stateless session beans tend to be more commonly preferred over stateful session beans for this reason. When the client application is a page flow or a conversational web service, conversational state is remembered by the client application itself, making it possible to use a stateless session bean while maintaining a continuous session with the user of the client application. When you develop a new session bean in WebLogic, by default a stateless session bean is defined.

Home and Business Interfaces

Page 107: webLogic

Like an entity bean, a session bean can have four different interfaces, called the local home interface, the local business interface (or simply, the local interface), the remote home interface, and the remote business interface (or simply, the remote interface). The local interfaces define the bean's methods that can be used by other EJBs, EJB controls, web services and page flows defined within the same application. That is, if you define a session bean and only plan to use it within that application, you can use local interfaces. In contrast, the remote interfaces define the bean's methods that be invoked by EJBs, EJB controls, web services and page flows defined in other applications.

To determine what interfaces are defined for a session bean, ensure you are in Design View and go to the Naming section in the Property Editor. The Remote EJB and Local EJB sections refer to the remote and local interfaces; within each section the Home class name refers to the home interface, and the Bean class name refers to the business interface. In Source View, the attributes are part of the @ejbgen:file-generation Annotation. When you define a new session bean, by default only the remote interfaces are defined.

A session bean's (remote or local) home interface contains the create methods used to obtain a reference to the bean instance. Its (remote or local) business interface contains the component methods that are used to encapsulate a particular piece of business logic.

The Create Methods

For a stateless session bean, you must define exactly one ejbCreate() method with no parameters. This method must be invoked to obtain to a reference to a session bean instance. Once you have obtained a reference, you can invoke the session bean's component methods. If you call a stateless session bean via an EJB control, you do not need to call the create method explicitly; the EJB control will create a reference for you when you call a component method.

A stateful session bean must have at least one ejbCreate method and, like entity beans, can have multiple ejbCreate methods. One of these methods must be invoked to obtain a reference to the session bean instance before you can invoke the session bean's component methods. If you call a stateful session bean via an EJB control, you must first call (one of) its create methods to obtain a reference.

Unlike with stateless session beans, when you can call a stateful session bean's create method to obtain a reference and subsequently invoke several component methods, each method is guaranteed to be handled by the same bean instance on the server. For more information, see The Life Cycle of a Session Bean.

Component Methods

Component methods are the business methods that are invoked on a session bean instance. A simple example of a business method is reserveTickets(customer, movieName, date), which is used to reserve tickets for a movie. For more information, see How Do I: Add a Component Method to an Entity or Session Bean?

In principle there is no difference between component methods for a stateful and a stateless session bean. However, the component methods of a stateless session bean must be passed all the necessary data to execute business logic as parameters, while this is not necessary for the component methods of a stateful session bean. For instance, for a stateful session bean the component method reserveTickets() can be used to make ticket reservations for a movie, after the component method setCustomer(customer) is called to set the customer data, setMovie(name) is called to make the movie selection, and setDate(date) is called to set the movie time. For a stateless session bean, these parameters must be passed to the component method making the actual reservations, as in reserveTickets(customer, movieName, date).

Other Methods

Page 108: webLogic

A session bean has several predefined methods, as well as a number of callback methods, invoked by the EJB container during certain operations, that a session bean must implement. In WebLogic these callback methods are by default automatically implemented. In many cases you will find it unnecessary to use these methods. To learn more about these methods, see Defining a Session Bean and The Life Cycle of a Session Bean.

Creating a Session Bean

To create a session bean, you can choose one of the following methods:

Create a session bean from scratch. If you are designing a new session bean in EJB project, you can define a new session bean. To find out exactly how to do this, see How Do I: Create an Enterprise JavaBean? When you create a new session bean, by default the remote interfaces and various other defaults are defined. For more details, see @ejbgen:file-generation Annotation.

Import a session bean. If you have developed session beans in another development environment, you can import these into WebLogic. To import an EJB, you need the EJB Jar file as well as the source files. You can import multiple EJBs at the same time. For more information, see How Do I: Import an Enterprise JavaBean? After you have imported a session bean, you can enhance its definition.

Note. If you have existing session beans that you plan to invoke in the application, for instance via another EJB or an EJB control, but you do not intend to change their definitions, you can suffice by adding the EJB Jar to the application. For more information, see How Do I: Add an Existing Enterprise JavaBean to an Application?

Defining a Basic Session Bean The following figure shows the design view of a basic session bean called PriceCheckerBean:

This stateless session bean's component method receives the name of a product and returns the price when known, or a 'product unknown' message if the product cannot be found. It uses the ProductBean, shown in Defining an Entity Bean, to look up a product in the database and return its price. The source code of the PriceChecker bean is given below:

package myBeans;

import javax.ejb.*;import javax.naming.InitialContext;import javax.naming.NamingException;import weblogic.ejb.*;

/** * @ejbgen:session

Page 109: webLogic

* ejb-name = "PriceChecker" * * @ejbgen:jndi-name local="ejb.PriceCheckerLocalHome" * * @ejbgen:file-generation remote-class="false" remote-home="false" local-class="true" * local-class-name = "PriceCheckerLocal" local-home="true" local-home-name = "PriceCheckerLocalHome" * * @ejbgen:ejb-local-ref link="Product" */public class PriceCheckerBean extends GenericSessionBean implements SessionBean{ private ProductHome productHome; public void ejbCreate() { try { javax.naming.Context ic = new InitialContext(); productHome = (ProductHome)ic.lookup("java:comp/env/ejb/Product"); } catch (NamingException ne) { throw new EJBException(ne); } }

/** * @ejbgen:local-method */ public String returnPrice(String product) { Product theProduct; int visitNumber;

try { theProduct = productHome.findByPrimaryKey(product); } catch(FinderException fe) { return "Product not known"; } return "The price of this product is " + theProduct.getPrice(); }}

The @ejbgen:session annotation contains the actual name of the session bean. For stateful session beans this tag will contain the attribute type="Stateful". In the ejbCreate method a reference to the Product entity bean's local home interface is obtained. The JNDI reference Product used in the lookup method to look up the Product bean, is mapped to this bean's local interface using an @ejbgen:ejb-local-ref Annotation, which is defined at the top of the PriceChecker bean class definition. To learn more about JNDI naming, consult your favorite J2EE documentation or go to http://java.sun.com.

The method returnPrice implements the business logic for this class. It finds a particular product using the Product bean and returns its price. If the product cannot be found in the database, it returns a Product not known message instead.

In WebLogic, all the information needed to make a session bean are stored in a single file, instead of separate JAVA files for the bean class, the local business interface, the local home interface, and so forth. When you build a session bean, these classes are auto-generated. Various ejbgen annotations are used to hold the information required to make this generation possible. Specifically, the @ejbgen:file-generation annotation specifies the names of the local home and business interface for the PriceChecker bean, and the @ejbgen:local-method annotation on the component method specifies that the method should be defined in the local business interface. To verify that these JAVA and

Page 110: webLogic

corresponding CLASS files are generated, expand the JAR file created during a build (located in the Modules folder in the Application pane), and locate and open the generated files in the folder reflecting the package name. For the PriceCheckerBean, the PriceCheckerBean.java (bean definition), PriceCheckerLocal.java (local interface definition), and PriceCheckerLocalHome.java (local home interface definition) files are auto-generated.

Predefined and Callback Methods

The interfaces of session (and entity) beans extend a particular interface which contains various useful methods. Specifically:

The local interface extends javax.ejb.EJBLocalObject The local home interface extends javax.ejb.EJBLocalHome The remote interface extends javax.ejb.EJBObject The remote home interface extends javax.ejb.EJBHome

For example, the interfaces contain a remove method to remove a bean instance and, for a stateful session bean, end the conversation. Complete details about these interfaces and the methods they define can be found in your favorite J2EE documentation and the API reference at http://java.sun.com.

Every session bean must implement the javax.ejb.SessionBean interface. This interface defines callback methods that are called by the EJB container at specific times. The callback methods are setSessionContext, ejbActivate, ejbPassivate, and ejbRemove. When you define a session bean from scratch, it will extend weblogic.ejb.GenericSessionBean, which contains empty implementations of these callback methods. In other words, you will only need to define these methods if you need to override the empty implementation. If you import a session bean, these callback methods will probably be implemented directly in the bean's ejb file. For more details about the callback methods and their role in the interaction between the session bean and the EJB container, see The Life Cycle of a Session Bean.

The Life Cycle of a Stateless Session Bean

The following figure shows the life cycle of a stateless session bean. A stateless session bean has two states:

Does Not Exist. In this state, the bean instance simply does not exist. Ready. When WebLogic server is first started, several bean instances are created and placed

in the Ready pool. More instances might be created by the container as needed by the EJB container.

The various state transitions as well as the methods available during the various states are discussed below.

Page 111: webLogic

Moving from the Does Not Exist to the Ready State

When the EJB container creates a stateless session bean instance to be placed in the ready pool, it calls the callback method public void setSessionContext(SessionContext ctx). This method has the parameter javax.ejb.SessionContext, which contains a reference to the session context, that is, the interface to the EJB container, and can be used to self-reference the session bean object. Complete details about the javax.ejb.SessionContext can be found in your favorite J2EE documentation and the API reference at http://java.sun.com.

After the callback method setSessionContext is called, the EJB container calls the callback method ejbCreate. You can implement this callback method to for instance obtain the home interfaces of other EJBs invoked by the session bean, as shown in Defining a Session Bean. The ejbCreate method is only called once during the lifetime of a session bean, and is not tied to the calling of the create method by a client application. For a stateless session bean, calling the create method returns a reference to a bean instance already in the ready pool; it does not create a new bean instance. The management of stateless session bean instances is fully done by the EJB container.

The Ready State

When a bean instance is in the ready state, it can service client request, that is, execute component methods. When a client invokes a business method, the EJB container assign an available bean instance to execute the business method. Once executed, the session bean instance is ready to execute another business method.

Moving from the Ready to the Does Not Exist State

When the EJB container decides to reduce the number of session bean instances in the ready pool, it makes the bean instance ready for garbage collection. Just prior to doing this, it calls the callback method ejbRemove. If your session bean needs to execute some cleanup action prior to garbage collection, you can implement it using this callback method. The callback method is not tied to the remove method invoked by a client. For a stateless session bean, calling the remove method invalidates the reference to the bean instance already in the ready pool, but it does not move a bean instance from the ready to the does not exist state, as the management of stateless session bean instances is fully done by the EJB container.

The Life Cycle of a Stateful Session Bean

Page 112: webLogic

The following figure shows the life cycle of a stateful session bean. It has the following states:

Does Not Exist. In this state, the bean instance simply does not exist. Ready. A bean instance in the ready state is tied to particular client and engaged in a

conversation. Passive. A bean instance in the passive state is passivated to conserve resource.

The various state transitions as well as the methods available during the various states are discussed below.

Moving from the Does Not Exist to the Ready State

When a client invokes a create method on a stateful session bean, the EJB container creates a new instance and invokes the callback method public void setSessionContext(SessionContext ctx). This method has the parameter javax.ejb.SessionContext, which contains a reference to the session context, that is, the interface to the EJB container, and can be used to self-reference the session bean object. Complete details about the javax.ejb.SessionContext can be found in your favorite J2EE documentation and the API reference at http://java.sun.com. After the callback method setSessionContext is called, the EJB container calls the callback method ejbCreate that matches the signature of the create method.

The Ready State

A stateful bean instance in the ready state is tied to a particular client for the duration of their conversation. During this conversation the instance can the execute component methods invoked by the client.

Activation and Passivation

To more optimally manage resources, the EJB container might passivate an inactive stateful session bean instance by moving it from the ready state to the passive state. When a session bean instance is passivated, its (non-transient) data is serialized and written to disk, after which the the bean instance is purged from memory. Just prior to serialization, the callback method ejbPassivate is invoked. If your session bean needs to execute some custom logic prior to passivation, you can implement it using this callback method.

Page 113: webLogic

If after passivation a client application continues the conversation by invoking a business method, the passivated bean instance is reactivated; its data stored on disk is used to restore the bean instance state. Right after the state has been restored, the callback method ejbActivate is invoked. If your session bean needs to execute some custom logic after activation, you can implement it using this callback method.The caller (a client application or another EJB) of the session bean instance will be unaware of passivation (and reactivation) having taken place.

If a stateful session bean is set up to use the NRU (not recently used) cache-type algorithm, the session bean can time out while in passivated state. When this happens, it moves to the does not exist state, that is, it is removed. Prior to removal the EJB container will call the callback method ejbRemove. If a stateful session bean is set up to use the LRU (least recently used) algorithm, it cannot time out while in passivated state. Instead this session bean is always moved from the ready state to the passivated state when it times out.

The exact timeout can be set using the idle-timeout-seconds attribute on the @ejbgen:session annotation. The cache-type algorithm can be set using the cache-type attribute on the same annotation.

Moving from the Ready to the Does Not Exist State

When a client application invokes a remove method on the stateful session bean, it terminates the conversation and tells the EJB container to remove the instance. Just prior to deleting the instance, the EJB container will call the callback method ejbRemove. If your session bean needs to execute some custom logic prior to deletion, you can implement it using this callback method.

An inactive stateful session bean that is set up to use the NRU (not recently used) cache-type algorithm can time out, which moves it to the does not exist state, that is, it is removed. Prior to removal the EJB container will call the callback method ejbRemove. If a stateful session bean set up to use the LRU (least recently used) algorithm times out, it always moves to the passivated state, and is not removed.

The exact timeout can be set using the idle-timeout-seconds attribute on the @ejbgen:session annotation. The cache-type algorithm can be set using the cache-type attribute on the same annotation.

Developing Message-Driven Beans

An message-driven EJB is used to receive and process asynchronous messages using JMS. Message-driven EJBs are never directly invoked by other EJBs. However, they in turn can invoke methods of session and entity beans and send JMS messages to be processed by other message-driven EJBs. The topics listed below discuss development of message-driven beans.

What are Message-Driven Beans?

Message-driven beans are server-side objects used only to process JMS messages. These beans are stateless, in that each method invocation is independent from the next. Unlike session and entity beans, message-driven beans are not invoked by other beans or client applications. Instead a message-driven bean responds to a JMS message.

Because message-driven beans are not invoked by other EJBs or clients, these beans do not have interfaces. For each message-driven bean a single method, onMessage, is defined to process a JMS message. Although message-driven beans cannot be invoked by other EJBs, they can in turn invoke other EJBs. Also, message-driven beans can send JMS messages. As with the other types of EJBs, the EJB container is responsible for managing the beans environment, including making enough instances available for processing and message-acknowledgement.

Asynchronous and Concurrent Processing

Page 114: webLogic

A core feature of message-driven beans is the notion of asynchronous processing. A client application can send a JMS message to execute a certain business task. After the message has been sent, the client application can continue right away and does not have to wait for the JMS message to be received and processed. This is especially helpful when the business task is complex, requires the use of entity (and session) beans, and takes a long time to complete. In contrast, if the same client application were to use a session bean to execute a certain business task, it would have to wait until the session bean method completed and returned control to the client application. The message façade design pattern formalizes this use of message-driven beans as an intermediary between client applications and entity beans to achieve asynchrony. An example of this pattern is shown in the Message-Driven Bean Sample.

Another important feature of message-driven beans is that JMS messages are processed concurrently. That is, although each bean instance handles a message at a time, the EJB container takes care of creating enough bean instances to handle the message load at a given moment. In WebLogic you can set the initial number and max number of bean instances created by the container. For more information, see the @ejbgen:message-driven Annotation.

Because message-driven beans are stateless and processing of JMS messages occurs in an asynchronous message, there is no guarantee that messages are processed in the order they were sent. Therefore, sending multiple messages such that one message is dependent on the successful processing of another message might cause unexpected results. Instead, you should reconsider the granularity of your business task such that one message can initiate its execution, possibly by handling one piece of the task, and then sending a JMS message to be processed by another message-driven bean for the remainder of the business task.

Topics and Queues

A message-driven bean listens to a particular channel for JMS messages. There are two types of channels, namely topics and queues. Topics implement the publish-and-subscribe messaging model, in which a given message can be received by many different subscribers, that is, many different message-driven bean classes (not instances) listening to the same topic. In contrast, queues implement the point-to-point messaging model, in which a given message is received by exactly one message-driven bean class, even when multiple classes are listening to this queue.

The Life Cycle of a Message-Driven Bean

The EJB container is responsible for creating a pool of message-driven bean instances. When it creates an instance, it calls the setMessageDrivenContext() and the ejbCreate() methods. At this point the message-driven bean is ready to receive messages. When a bean instance is processing a JMS message, its onMessage method is being invoked. When the EJB container removes a bean instance, it first calls the ejbRemove method before the instance is ready for garbage collection. The life cycle of a message-driven bean is depicted in the following figure.

When defining a message-driven bean in WebLogic, in most cases you will implement the onMessage method to execute a particular business task, and use the ejbCreate method to implement actions that only need to be executed once, such as looking up the home interfaces of entity beans that are invoked by the message-driven bean's onMessage method. A typical example of simple message-driven bean is given below. Notice that the ejbCreate method is used to find the home interface of a Recording entity bean, while the onMessage method processes the message and invokes the Recording bean:

/** * @ejbgen:message-driven * ejb-name = Statistics * destination-jndi-name="jms.EJBTutorialSampleJmsQ" * destination-type = javax.jms.Queue * * @ejbgen:ejb-local-ref

Page 115: webLogic

* type="Entity" * name="ejb/recordLink" * local="bands.Recording" * link="Recording" * home="bands.RecordingHome" */public class StatisticsBean extends GenericMessageDrivenBean implements MessageDrivenBean, MessageListener{ private RecordingHome recordingHome;

public void ejbCreate() { try { javax.naming.Context ic = new InitialContext(); recordingHome = (RecordingHome)ic.lookup("java:/comp/env/ejb/recordLink"); } catch(NamingException ne) { System.out.println("Encountered the following naming exception: " + ne.getMessage()); } } public void onMessage(Message msg) { try { // read the message MapMessage recordingMsg = (MapMessage)msg; String bandName = recordingMsg.getString("bandName"); String recordingTitle = recordingMsg.getString("recordingTitle"); ... // save the rating with the recording Recording album = recordingHome.findByPrimaryKey(new RecordingBeanPK(bandName, recordingTitle)); album.setRating(rating); } catch(Exception e) { System.out.println("Encountered the following exception: " + e.getMessage()); } }}

You can implement the ejbRemove method if cleanup is required before the object is removed, and you can implement setMessageDrivenContext method if you need access to the javax.ejb.MessageDrivenContext provided by the EJB container. The MessageDrivenContext contains information about the container, in particular its transaction methods; for more information, see your favorite J2EE documentation. A message-driven bean defined in WebLogic by default extends weblogic.ejb.GenericMessageDrivenBean, which provides empty definitions for all these methods with the exception of the onMessage method; the definition of your bean must therefore implement the onMessage method.

 Using a JMS Control

In WebLogic you can use a JMS control to send JMS messages to a topic or queue. JMS controls can be used to send messages in page flows and web services; they cannot be used to send JMS messages in EJBs. You can use JMS controls to both send and receive messages. In this case you will only be using the JMS control to send messages, as a message-driven bean will be used to process received messages. For details on how to create JMS controls for topics and queues, see JMS Control.

The advantage of using a JMS control is that the details of the JMS messaging API are by and large taken care of by the JMS control. For example, the following code samples shows the definition of a JMS control to send messages to a queue:

Page 116: webLogic

/** * @jc:jms send-type="queue" send-jndi-name="jms.SamplesAppMDBQ" * connection-factory-jndi-name="weblogic.jws.jms.QueueConnectionFactory" */public interface sendToQueueControl extends JMSControl, com.bea.control.ControlExtension { /** * this method will send a javax.jms.Message to send-jndi-name */ public void sendJMSMessage(Message msg); static final long serialVersionUID = 1L;}

As the definition shows, you must still define the name of the queue to which to send the JMS message as well as the name of a QueueConnectionFactory. However, to send a message using this JMS control, you simply need to invoke the method sendJMSMessage and pass a message as the parameter. The JMS control handles the creation of a factory instance, a connection, session, and so forth.

When using a JMS control from a page flow or web service, you can use a built-in control to encapsulate all the message sending related logic, instead of defining this directly in the page flow or web service. For instance, the following built-in control code snippet uses the JMS control defined above to send 20 messages at one time to a queue.

...public class MessageSenderImpl implements MessageSender, ControlSource{ /** * @common:control */ private messageDriven.sendToQueueControl queueSend;

/** * @common:operation * @common:message-buffer enable="true" */ public void add20ViaQueue(int currentNum) throws JMSException { String name; for(int i = 0; i < 20; i++) { MapMessage msg = queueSend.getSession().createMapMessage(); msg.setStringProperty("Command", "Add"); name = Integer.toString(currentNum + i); msg.setString("tokenName", name); queueSend.sendJMSMessage(msg); } }}

For more information on built-in controls, see Building Custom Java Controls. The use of JMS controls and built-in controls in a page flow is demonstrated in the Message-Driven Bean Sample.

Sending Messages from EJBs

To send JMS message from an EJB, you cannot use JMS controls and must use the 'standard' JMS messaging API. (You can also use the standard messaging API in page flows and web services if you do not want to use a JMS control.) The following code sample shows a session bean sending a message to a queue. The queue and QueueConnectionFactory are defined using @ejbgen:resource-env-ref and @ejbgen:resource-ref annotations. In the bean's ejbCreate method the queue and QueueConnectionFactory are located (this only need to be done once), while the method executeTask

Page 117: webLogic

contains the correct procedure to create a connect, session, sender, and message before sending the JMS message.

/**

* @ejbgen:resource-ref * auth="Container" * jndi-name = "weblogic.jws.jms.QueueConnectionFactory" * name = "jms/QueueConnectionFactory" * type="javax.jms.QueueConnectionFactory" * * @ejbgen:resource-env-ref * jndi-name="jms.ASampleJmsQ" * name="jms/ASampleJmsQ" * type = "javax.jms.Queue" * * ... */public class ASessionBean extends GenericSessionBean implements SessionBean{ private QueueConnectionFactory factory; private Queue queue; public void ejbCreate() { try { javax.naming.Context ic = new InitialContext(); factory = (QueueConnectionFactory) ic.lookup("java:comp/env/jms/QueueConnectionFactory"); queue = (Queue) ic.lookup("java:comp/env/jms/ASampleJmsQ"); } catch (NamingException ne) { throw new EJBException(ne); } }

/** * @ejbgen:local-method */ public void executeTask(String prop1, String prop2) { try { //interpret the properties ... //send a message QueueConnection connect = factory.createQueueConnection(); QueueSession session = connect.createQueueSession(true,Session.AUTO_ACKNOWLEDGE); QueueSender sender = session.createSender(queue); MapMessage recordingMsg = session.createMapMessage(); recordingMsg.setString("Property1", prop1); recordingMsg.setString("Property2", prop2); sender.send(recordingMsg); connect.close(); } catch(JMSException ne) { throw new EJBException(ne); } }}

JMS Message Types

Page 118: webLogic

The JMS messaging API defines various message types, allowing for different types of information to be included in the body of a JMS message. Frequently used message types are TextMessage to send a text string, MapMessage to create sets of name-value pairs, and ObjectMessage to send a serializable object. For more details on the various message types, see your favorite J2EE documentation or the javax.jms.Message API documentation at http://java.sun.com.

Message Selectors

A JMS message can also contain message properties. There are different types of properties which can serve a number of functions. One common use of a message property is to set a message selector. A message selector is a property that is used by a message-driven bean to determine whether it should process this message or should leave its processing up to another message-driven bean listening to the same topic or queue.

The following example shows how to set a String property that will act as a message selector for a JMS MapMessage:

Message msg = session.createMapMessage();msg.setStringProperty("MyMessage", "Build 126"");

A message-driven bean that is defined to specifically process this type of message will include a message selector property:

* @ejbgen:message-driven * message-selector="MyMessage = 'Build126'" * ejb-name = MDBean * ... */public class MDBean extends GenericMessageDrivenBean implements MessageDrivenBean, MessageListener{ ...

In other words, this bean will respond specifically to this type of message and will leave the processing of other messages up to other beans listening to this topic or queue. By using a message selector you can send different types of messages to the same channel instead of having to create a separate queue/topic for every type of message. For more details on the various message properties, see your favorite J2EE documentation or the javax.jms.Message API documentation at http://java.sun.com.

 Processing JMS Messages

When a JMS message is sent to a topic or queue, a message-driven bean instance will interpret and process the message, as specified in its onMessage method. When a JMS message is sent to a topic, a publish-and-subscribe system, an instance of every message-driven bean class listening to this topic will in principle receive and process this message. However, if the message contains a message selector, only the message-driven bean(s) matching the message selector will process the message. When a JMS message is sent to a queue, a point-to-point system, only one message-driven bean will process the message, even when multiple bean classes are listening to the queue. Again, the use of a message selector might limit the bean processing the message. For more on message selectors, .

How the JMS message is processed fully depends on the business task that is being modeled. It might range from simply logging the message to executing a range of different tasks which include invoking methods on session and entity beans, or sending JMS messages to be processed by other message-driven beans. The following code sample shows one use of a message-driven bean. This bean responds only to JMS messages delivered via the jms/SamplesAppMDBQ queue and contain the message selector Command= 'Delete'. When processing a JMS message, an instance of this bean invokes the query method findAll of the entity bean SimpleToken, and subsequently deletes all SimpleToken records from the underlying database.

Page 119: webLogic

/**

* @ejbgen:message-driven * message-selector="Command = 'Delete'" * ejb-name = DeleteViaQMD * destination-jndi-name = jms/SamplesAppMDBQ * destination-type = javax.jms.Queue * * @ejbgen:ejb-local-ref link="SimpleToken" */public class DeleteViaQMDBean extends GenericMessageDrivenBean implements MessageDrivenBean, MessageListener{ private SimpleTokenHome tokenHome; public void ejbCreate() { try { javax.naming.Context ic = new InitialContext(); tokenHome = (SimpleTokenHome)ic.lookup("java:/comp/env/ejb/SimpleToken"); } catch(NamingException ne) { System.out.println("Encountered the following naming exception: " + ne.getMessage()); } }

public void onMessage(Message msg) { try { Iterator allIter = tokenHome.findAll().iterator(); while(allIter.hasNext()) { ((SimpleToken) allIter.next()).remove(); } } catch(Exception e) { System.out.println("Encountered the following exception: " + e.getMessage()); } }} 

Acknowledgement and Transactions

When a message-driven bean instance receives a message, and it is not part of a container-managed transaction, by default it immediately sends an acknowledgement to the JMS provider notifying that the message has been received. This will prevent the JMS provider from attempting to redeliver it. However, the acknowledgement only indicates that a message has been successfully received, but it does not guarantee that the message is successfully processed. For instance, a system exception might occur when attempting to locate an entity bean or update its records, causing the processing to fail.

If you want to ensure that a message is redelivered when processing fails, you can make the message-driven bean be part of a transaction. The easiest approach is to use container-managed transaction, where the EJB container is responsible for transaction management. To enable container-managed transaction for a message-driven bean, make sure that your cursor is placed inside the ejbgen:message-driven tag and use the Property Editor to set the transaction-type to Container and the default-transaction to Required. When JMS message processing executes successfully, any changes made during this business task, such as update to entity bean records, are committed and acknowledgement is sent to the JMS provider. However, when JMS message processing fails due to a system exception, any changes are rolled back and receipt is not acknowledged. In other words, after processing fails, the JMS provider will attempt to resend the JMS message until processing is

Page 120: webLogic

successfully or until the maximum number of redelivery attempts specified for this topic or queue has been reached.

Note. When a message-driven bean is part of a transaction, it executes as part of its own transaction. In other words, if the transaction fails, changes that were made as part of the onMessage method are rolled back, but the occurrence of an exception has no direct effect on the EJB or client application sending the JMS message, as the sender and the message-driven bean are decoupled.

To learn more about container-managed transactions, see EJBs and Transactions. To learn more about bean-managed transaction (that is, explicit transaction management), please refer to your favorite J2EE documentation.

WebLogic Workshop Security Overview

The following overview sets out the aims of security and the security technologies available in WebLogic Workshop.

Security Goals

All security technologies are designed to achieve three basic goals.

1. Authentication of participants

When a participant is authenticated it means that there is some assurance that the participant really is who they say they are. Different scenarios call for different levels of authentication. In some cases, only the web resource needs to be authenticated, while the client can remain anonymous. For example, if your web resource takes customer credit card numbers, you want your customers to have peace of mind that they are providing their card numbers to you, and not some malicious third party. But your customers may remain anonymous. In other cases, the web resource will want proof of identity from its clients. For example, if a bank provided online access to its customer's checking accounts, the bank should require some form of client authentication from those parties who want to access the online accounts.

2. Confidential communication

Data transmission is confidential when only the intended recipient can read the data. 3. Integrity of transmitted data

Data integrity means that the data has not been altered in the process of transmission. (When using transport security, there is generally no need to take special measures to ensure data integrity. This is because the encryption processes used by SSL ensures data integrity.)

The topics below provide detailed information to help you implement a security strategy for your WebLogic Workshop application.

WebLogic Workshop Security Technologies

WebLogic Workshop offers three main areas of security technology:

transport security web service security role-based security

Transport security refers to the mechanisms used to enable the http protocol to operate over a secure transport connection. Transport security lets you secure your web resources through SSL, username/password authentication, and client digital certificates.

Page 121: webLogic

An advantage of transport security is that is well known and relatively easy to implement. A disadvantage is that data is secured only while it is in transport over the wire. The transport security mechanisms no longer apply once the data has reached the recipient, so if the data is logged on the recipient's machine, its confidentiality may be at risk. This is not the case with Web service security, where the security mechanisms are applied to the data itself.

For detailed information on implementing SSL and client certificates see Transport Security. For detailed information on implementing username/password authentication see Username/Password Authentication.

Web service security provides message-level security for web services through an implementation of the Oasis Web Service Security standard. Web service security, often referred to as "WS-Security" or simply "WSSE", lets you secure the SOAP messages that pass between web services with security tokens (username and password), digital signatures, and encryption.

An advantage of WS-Security is that the security mechanisms are applied to the SOAP messages that pass between web services. So WS-Security security mechanisms apply both while the SOAP message is in transit and once the message has arrived at the recipient's machine.The disadvantages of WS-Security are that it is not a widely used form of security and it is relatively more difficult to implement than the analogous transport security technologies. For example, users must be familiar with some of the inner workings of the Public Key Infrastructure (PKI) to effectively use WS-Security's encryption and digital signature technologies.

For detailed information on implementing see Web Service Security.

Role-based security lets you secure a web resource by restricting access to only those users who have been granted a particular security role. For detailed information on see Role-Based Security.

Transport Security

Transport security refers to a group of security technologies that ensure the authenticity of both clients and servers and the integrity and confidentiality of data passed between web servers and their clients.

In most cases, transport security alone is sufficient to secure a web resource such as a web application or web service; but there is another security option available specifically for web services. For detailed information see Web Service Security.

Transport Security Strategies

Transport security offers three basic strategies for achieving the three main security goals: authentication of participants, confidential communication and data integrity. See WebLogic Workshop Security Overview for a description of these security goals.

One-way SSL

One-way SSL offers two primary benefits. First it authenticates the identity of the web server. Second, it ensures confidential communication by encrypting the messages between the client and the server. The "one-way" in one-way SSL refers to the fact that only the identity of the server is authenticated, not the client. You should use one-way SSL when you want to ensure private communication, but where the identity of the client is not a critical factor.

One-way SSL with Basic Authentication

Basic authentication ensures the identity of clients by requiring a username and password. Basic authentication should always be used together with one-way SSL, otherwise the username and

Page 122: webLogic

password could be intercepted by a malicious third party. You should use one-way SSL when you want to ensure the identities of both the client and server. For details on implementing a basic authentication process, see Basic Authentication.

Two-way SSL

Two-way SSL combines server authentication, encryption of data, and client authentication through client digital certificates.

Web Service Security (WS-Security)

WebLogic Workshop provides message-level security for web services through an implementation of the WS-Security Oasis web service security standard. WS-Security lets you secure the SOAP messages passed between web services using (1) security tokens, (2) digital signatures, and (3) encryption.

Although WebLogic Workshop supports both transport and message-level security, it is generally not necessary to use both sorts of security to secure a web service. In most cases, developers should choose one or the other type of security to secure their web services.

Security Tokens

Security tokens are credentials used for authentication, authorization, or both. The WebLogic Workshop implementation supports two types of tokens. (1) Username and password tokens, and (2) X509 Binary Security Tokens.

When a X509 Binary Security Token accompanies an inbound SOAP message, the token is passed to the WebLogic Server security framework for authentication.

To include a Binary Security Token in an outbound SOAP message, you specify that you want to sign the outbound message. Signing the SOAP message will automatically include a X.509 BinarySecurityToken in the message. Note that sending a X509/Binary Security Token without signing the outbound SOAP message is not supported.

Digital Signatures

Digital signatures are used for two purposes: (1) to authenticate the identity of the sender and (2) to ensure the integrity of SOAP messages. If any part of an incoming SOAP message has been changed in transport, the signature validation performed by the recipient will fail. In WebLogic Workshop, if you require XML signatures for incoming SOAP messages, the SOAP body must be digitally signed to be processed by the web service.

By default, digital signatures are applied only to the body of outgoing SOAP messages. You must specifically provide for the signing of elements in the header. For details see in the WS-Security reference documentation.

Encryption

Encryption is used to encrypt either the body of the SOAP message, the header, or both. If your web service requires encryption for incoming messages, then, at a minimum, the body of incoming SOAP messages must be encrypted.

For outgoing SOAP messages, encryption is applied only to the SOAP body by default. You must specifically provide for the encryption of elements in the header. For details see in the WS-Security reference documentation.

Note that keys used in WebLogic Workshop's implementation of WS-Security must be RSA keys.

Page 123: webLogic

WSSE Policy Files

Web service security is controlled through WSSE policy files. WSSE policy files are XML files with a .WSSE file extension.

To secure a web service with web service security, you create a WSSE policy file and associate that file with your web service. All outbound and inbound SOAP messages are processed according to the policy called for in the WSSE file. Inbound messages are first checked for the necessary security measures called for in the policy file. If the inbound message is found to be appropriately secured, then the SOAP message, cleaned of its security enhancements, is passed to the web service for normal processing. Outbound messages go through the reverse process: they are enhanced with the security measures called for in the policy file before they sent out over the wire.

To access a web service secured with WS-Security, you create a policy file and associate that file with the web service control. The policy file you associate with a web service's control should match the policy file of the target web service. If the target web service requires encrypted incoming messages, then a control file targeting that web service should encrypt messages before they are sent to the web service.

For detailed information see Using WSSE Policy Files.

An Overview of Role-Based Security

The topics in this section explain how role-based security can be used to restrict access to resources (web services, page flows, Java controls, EJBs) to only those users who have been granted a particular security role. It also explains the relationship between EJB-scoped, application-scoped, web-application scoped, and global security roles.

To restrict access you set up two kinds of tests that candidate users must pass to access some resources: an authentication process, which determines the user's identity and group membership, and an authorization process, which decides whether a user has the role membership necessary to access a particular resource. Once a user has access to a method and the method executes, it can run under the security role of the user or under a different security role.

The Authentication Process

A candidate user is first tested against the authentication process. The authentication process is generally a login process, where the candidate user is asked to provide a username and password. If the candidate succeeds in passing this challenge, the user is granted a set of identities: one identity is his username identity, the other identities are the set of groups that user has membership in. The user's username identity and group identities are called the user's principals: think of these principals as a set of credentials that the user presents when he/she wants to access some resource protected by an authorization process. For more information, see Authentication.

The Authorization Process

In the authorization process, users are tested to see if they have been granted the required role to access the protected resource. If they have been granted the required role, they can access the resource; if they haven't, they are denied access. A user has been granted a particular role if one of his/her principals has been granted a particular role. Principals are granted roles by a set of role-principal mappings.

Note. A user can be a person or another software component. For instance, a web service can invoke an EJB's method with security restrictions; if the web service does not pass the authorization process, it is prevented from invoking the EJB method.

Page 124: webLogic

Global Roles

Global roles are available to all resources within a server's security realm, that is, a server's domain. These roles can be used by any application and any resource using this domain. WebLogic Server predefines a set of global roles but you can define additional global roles as needed. For more information, see the WebLogic Server help topic Securing WebLogic Resources.

Scoped Roles

Scoped roles apply to a particular resource. WebLogic Workshop applications can have three different scopings:

1. Application scoped (defined in the application's application.xml / weblogic-application.xml files) 2. Web application scoped (defined in a project's web.xml / weblogic.xml files) 3. EJB scoped (defined in an EJB's ejb-jar.xml / weblogic-ejb-jar.xml files)

Application scoped roles can be used in an authorization process to protect any of the resources within the application, whereas web application scoped roles apply only to the resources within an individual web project and EJB scoped roles apply only to the resources within an individual EJB. For instance, if you want a security role to be defined just for a particular EJB, you make it EJB-scoped.

Note that EJB scoped roles do not exclusively protect WebLogic Workshop's EJB projects: they also can be used to protect Web Services, Java control extensions (JCX files), and JPD files. This is because all these files are compiled into EJBs at compile time.

The following diagram shows the three kinds of scoped roles, and corresponding deployment descriptors, that you can define with WebLogic Workshop.

Page 125: webLogic

Note. You can also define scoped security roles for other resources such as JDBC resources. For more information, see the WebLogic Server help topic Securing WebLogic Resources.

Role-Principal Mapping

Role-principal mappings define how principals map to security roles. A particular user can be mapped to one or more security roles or a group can be mapped to one or more security roles. Role-principal mappings for a scoped role are defined in the appropriate deployment descriptor configuration file (see the fragments in the above picture; this is discussed in more detail in Implementing Role-Based Security).

For scoped roles, you can alternatively use the element to indicate that the role and role-principal mapping are defined elsewhere in the security realm. Specifically, when you use this element for EJB-scoped or web application scoped roles, WebLogic Server first examines the application-scoped roles for a role with the same name and with a role-principal mapping definition. If no appropriate application-scoped roles are found, global roles are examined. For application-scoped roles with the element, global roles are examined for role-principal mappings.

Note. When you map a scoped role to a principal, the principal is assumed to exist in the security realm. Role-principal mapping does not have the side effect of defining the principal if it doesn't exist. For more inforrmation, see Creating Principals and Role-Principal Mappings.

Running Under Another Security Role

Page 126: webLogic

An EJB, Java control, or web service method can run under the security role of the invoking user, or it can run under a different security role and principal. This might for instance be necessary when the EJB or web service in turn use resources that have strict security requirements.

Authentication

Authentication establishes the identity of a user by challenging the user to provide a valid username/password pair: something only the intended user knows.

Authentication can be used to protect any web-accessible resource, including web applications, web services, page flow applications, and individual JSP pages.

If the protected web resource is intended for human clients, the application can be configured to redirect users to a login page, where they must enter a valid username and password before they can access the resource. If the web resource is intended for machine clients, the machine client can provided the required username and password through methods on the resource's control file. For detailed information on authenticating machine clients see Using Controls to Access Transport Secured Resources.

The username/password pair can be checked against a variety of authentication provider services. A default authentication provider is provided by WebLogic Server, but other providers can be supplied as needed. For details on changing the default authentication provider or adding addition providers, see Configuring Security Providers in the WebLogic Server 8.1 documentation.

If you want to restrict access to sensitive information, username/password authentication should always be used in conjunction with SSL. Without SSL the username and password to are transported over the HTTP protocol, which uses only 64-bit encryption to hide the username and password, making it relatively easy for a malicious party to intercept and decode the message. For this reason you should always use basic authentication in conjunction with SSL, which uses 128-bit encryption.

However, if the primary purpose of username/password authentication is tracking user behavior in an application, and there is no especially sensitive information at stake, you do not need to use SSL.

Below are three basic strategies for setting up a username/password challenge in a WebLogic Workshop application:

Basic Authentication: uses a standard login screen provided by the web browser. Form Authentication: uses a custom login screen provided by the developer. Page flow authentication: uses a page flow to authenticate a user.

Basic Authentication

Basic authentication has the advantage of being easy to implement, but, since the login page is provided by the browser software, the developer does not have control over the look and feel of the login page. For detailed information see Basic Authentication. (Also see Developing BASIC Authentication Web Applications in the WebLogic Server 8.1 documentation.)

Form Authentication

Form authentication is easy to implement and gives the developer control over the look and feel of the login screen, but it should not be used in all situations. In particular it should not be used to secure (1) web services which have machine clients and (2) individual pages and methods within a page flow.

Web services with machine clients will encounter a problem interpreting the HTTP login page; instead use basic authentication for resources with machine clients.

Page 127: webLogic

Form authentication should not be used to secure individual pages and methods within a page flow. This is because form based authentication relies on redirecting the user from and back to the protected resource, but page flows do not support redirection from and back to the same location within a page flow. For this reason, you should only use form authentication to establish the identity of a user before he enters a page flow, not once he is within the page flow. If you want to allow a user to navigate within a page flow unauthenticated, but require authentication for other pages within the page flow use Page Flow Authentication.

For details on developing Form Authentication see Form Authentication. (Also see Developing FORM Authentication Web Applications in the WebLogic Server 8.1 documentation.)

Page Flow Authentication

Page Flow authentication uses a page flow to authenticate a user. The page flow can be a nested page flow, so it is appropriate to use this authentication technique when a user is already navigating within another page flow. For detailed information see Page Flow Authentication.

Portal Security Scenario

The following scenario describes the portal implementation needs of a fictitious company called Avitek, many of which involve security considerations. The topic that follows, Implementing the Portal Security Scenario, describes the security touch points in the scenario and provides links to implementation information.

Avitek needs two types of portal-based Web presence: an internal site for its employees and partners called "Inweb," and a public portal for its customers called "Outweb." It needs authentication for both sites. Inweb must live behind a firewall.

Outweb is set up on a server cluster for load balancing and failover.

For Inweb, Avitek needs to cater to three different types of users: managers, regular employees, and partners.

For the three types of users, Avitek wants to create only two portals: one for managers and employees and one for partners. Since there are five different partners, each partner must have a separate view of Inweb.

Some of the partners also perform contract work for Avitek, so they must also be able to access the employee portal desktop.

Avitek wants all Inweb users to authenticate before seeing any view of the portals.

For Outweb, Avitek provides information and services on a subscription basis, so it wants to provide a portal that lets all users see unsecured company information and log in to see secure information.

Avitek has a staff of two to administer all portals, and it wants to grant limited administrative access to certain partners to let them maintain their partner portal.

There are two JSP-based administration portlets that can never be seen by anyone other than Avitek's in-house administrators.

Avitek also wants to use its existing content management system for delivering content to its portals. The content management system vendor has created an interface to connect to BEA's Virtual Content Repository.

Page 128: webLogic

Avitek will use two user databases: The Intranet site will use an existing user database, and the public site will use the default WebLogic Server LDAP user database and is gradually adding users to it.

Deploying an Application to a Production Server

The following topic explains the basic concepts of deploying WebLogic Workshop applications to WebLogic Server running in production mode.

For step-by-step instructions on deploying a WebLogic Workshop application to a production server see How Do I: Deploy a WebLogic Workshop Application to a Production Server?.

Development Mode and Production Mode

Weblogic Server can be started in one of two modes: development or production mode. Development mode is the default. When you are developing, deploying and testing an application with WebLogic Workshop, the instance of Weblogic Server you are running is in development mode. In development mode, WebLogic Server behaves in ways that make it easier to iteratively develop and test an application: it automatically deploys the current application in an exploded format, server resources such as databases and JMS queues necessary for the application to run are automatically created, etc.

When the development cycle is complete, and the application is ready for use, you deploy it to an instance (or instances) of WebLogic Server running in production mode. In production mode applications are not automatically deployed. The server resources necessary for running an application are not automatically generated, you must generate them manually.

To set the server to start in production mode, you specify the Java property mode in the startup script as:

-Dweblogic.ProductionModeEnabled=true

For detailed information on starting WebLogic Server in production or development mode see startWebLogic Command.

EAR Files

WebLogic Workshop produces J2EE enterprise applications for deployment to a production server. You cannot deploy a web application project alone as a Web Application Archive (WAR) file; it must be deployed as a part of an entire application. There are two ways to deploy an application on the production server: in an exploded directory, or in an archive.

In an archived format, use EAR files if you are deploying an entire application; or use a JAR file if you are deploying a specific project within an application, (provided that specific project is a custom Java control or a Schema project).

You can generate an EAR file for a WebLogic Workshop application either (1) from the menu bar by selecting Build-->Build EAR or (2) by using the wlwBuild.cmd command line tool. The wlwBuild.cmd line tool is somewhat more flexible in that you can set flags to build a JAR file for a specific project, instead of building an EAR file for the entire application.

For information generating an ANT build.xml file that calls wlwBuild.cmd, see How Do I: Call wlwBuild.cmd from an ANT build.xml file?

EAR files can be deployed to WebLogic Server using either (1) the WebLogic Server console, or (2) the weblogic.Deployer utility.

Page 129: webLogic

To use the WebLogic Server console to deploy an EAR file, start the console, expand the Deployments node in the left-hand pane, right-click the Applications node, and select Deploy a new Application.

To use the weblogic.Deployer utility see the Deployment Tools Reference in the WebLogic Server 8.1 documentation.

When you compile an EAR file using Build EAR, a wlw-manifest.xml file is produced and placed in the application's META-INF directory. This wlw-manifiest.xml file lists the server resources that must be created on the production server for the application EAR to run successfully. See the next section for information relating to the wlw-manifest.xml file.

Note: Values specified in a project's WEB-INF/wlw-config.xml file, such as hostname, http-port, and https-port, will be hard-coded into the EAR file. The result will be an EAR file that can be run only on the machine named in the wlw-config.xml file. For this reason, it is recommended that you do not write to the wlw-config.xml file before producing an EAR file. If you need to override the hostname and ports dynamically determined by the server at runtime, use the wlw-runtime-config.xml file instead of wlw-config.xml.

Manual Creation of Server Resources

When deploying EAR files to a production server, a certain amount of manual resource creation is necessary. When an application is built in an EAR file, a wlw-manifest.xml file is produced and placed in the application's META-INF directory. This file lists the JMS queues and database tables that need to be manually created on the target WebLogic Server for the application to run properly.

Note: When you use iterative builds, the builds do not include a clean step. To ensure an accurate wlw-manifest.xml file, make sure your final build includes a clean step. Otherwise, the contents of the wlw-manifest.xml may not be correct.

Note: When you are developing and testing an application with WebLogic Workshop, the creation of the necessary JMS queues and datatables on WebLogic Server takes places automatically on demand.

Required database tables are indicated by a tag. These tables are used by web services to store conversational state. For each occurrence of the tag in the wlw-manifest.xml file, you must create a corresponding datatable on WebLogic Server. For detailed information about the schema required for these tables, see How Do I: Deploy a WebLogic Workshop Application to a Production Server?

Required JMS queues are indicated by pairs of and tags. For each occurrence of these tags in the wlw-manifest.xml file, you must create a corresponding JMS queue on WebLogic Server and you must associate the members of the pair by referencing the in the ErrorDestination attribute of the . For detailed information about how to create these queues, see How Do I: Deploy a WebLogic Workshop Application to a Production Server?

Optionally, you may want to enforce role restrictions on any controls that receive external callbacks. Controls that can receive external callbacks are indicated within a tag in the wlw-manifest.xml file. Since the compilation process turns control files into individual methods on an EJB, you enforce the role restrictions on these post-compilation EJB methods.

Overview: Clustering

A WebLogic Server cluster is a deployment in which multiple copies, or instances, of an application work together to provide increased performance, especially in high traffic contexts. In cases where an application receives a high volume of requests, the different instances of WebLogic Server in the cluster share the work of processing the requests. From the client’s point of view, there appears to be only one instance of WebLogic Server servicing the requests.

Page 130: webLogic

Clusters also provide failover support. Should one instance of the application fail for some reason--for example, because of a hardware outage--another copy of the application in the cluster can pick up and complete the tasks left incomplete by the failed server.

The server instances that make up the cluster can run on a single machine, or they can run on different machines. Each server instance in a cluster must run the same version of WebLogic Server.

To learn more about deploying applications to WebLogic Server clusters see WebLogic Server Clusters in the WebLogic Server 8.1 Documentation.

Clustering Workshop Applications

Clusters provide scalability and support failover for web resources. The basic clustering model consists of the following elements:

1. One administration server that manages state and configures the other servers in the cluster 2. One HTTP proxy server—either a hardware or a software proxy server—which receives

requests from clients and distributes jobs to the other servers in the cluster 3. Any number of managed servers that actually do the work of servicing requests from clients

All configuration of the cluster takes place on the administration server: all other servers in the cluster use the copy of config.xml on the administration server. (There may be local copies of config.xml on the managed servers in the cluster, but, these copies of config.xml are ignored in favor of the copy on the administration server.)

The following three required WebLogic Workshop resources must also be deployed homogeneously across all servers in a cluster:

JDBCConnectionPool JDBCTxDatasource JMSQueueConnectionFactory.

A JMS Server is also a required Workshop resource, however, it can only be deployed to one server in the cluster.

Configuring Clusters in config.xml

Complete syntax for the config.xml file can be found at WebLogic Server Configuration Reference in the WebLogic Server 8.1 documentation.

The following sections highlight some of the most important elements within a cluster-defining config.xml file (located on the administration server), including the element, resource deployment, and database support.

The Element

The ClusterAddress attribute specifies a DNS name that maps to the list of IPs of the servers. ClusterAddress does not give the DNS name of the multicast address, which does not require a DNS name. The cluster as a whole can be used as a deployment target. To deploy a J2EE resource to the entire cluster, use the value of the Name attribute as the target of the deployment. To learn more, see the -targets parameter of the deployment tool, Deployment Tools Reference, in the WebLogic Server 8.1 documentation.

Resource Deployment

Page 131: webLogic

Resources in the cluster—such as database connection pools, data sources, and JMS servers—are defined in the administration server's config.xml file. Resources are not by default universally available across the cluster. The servers they are deployed to are specified by their Targets attributes.

The connection pool, conversational datasource, and queue connection factory that Workshop relies on is defined on each managed server in the cluster. For example, the Targets attribute on the JDBConnectionPool and JDBCDataSource elements specifies each managed server, and each managed server has its own pool of connections.

However, the JMSServers can only be targeted at one server in the cluster. Currently Workshop only uses one JMSServer that is targeted, by convention, at the first managed server in the cluster.

Proxy Server Setup

Clusters can use a software proxy server to distribute HTTP requests across the cluster. The proxy server is also called the sprayer or load balancer. This software proxy is implemented as a web application deployed to the proxy server. You configure the proxy by editing the web.xml descriptor in the proxy application’s WAR file. There are entries in the descriptor for specifying what IP addresses and ports the proxy should distribute requests to. For more information about configuring the proxy server see Configure Proxy Plug-Ins in the WebLogic Server 8.1 documentation.

When using a proxy, it is necessary to set the hostname, HTTP, and HTTPS ports on the target cluster, otherwise the target cluster will not know how to interpret the requested URLs coming from the proxy. You set the hostname and ports by (1) setting the FrontEnd information through the WebLogic Server console and (2) in the target cluster's the wlw-runtime-config.xml file.

Editing the application's wlw-config.xml file is not recommended, because these values are fixed at compile-time. It is generally best to configure the hostname and ports through the wlw-runtime-config.xml file, which overrides the values in the wlw-config.xml.

To set the FrontEnd host and port information using the WebLogic Server console, open the console, and navigate to

[your_domain]-->Servers-->[your_server]-->Protocols tab-->HTTP tab-->Advanced Options

Then edit the Frontend Host, Frontend HTTP port, and Frontend HTTPS port fields. Note that the Frontend host must be set on each managed server in the cluster, but should not be set on the administration server. All servers in the cluster must be restarted for this change to take effect. Configuring Web Server Functionality for WebLogic Server

To set the host and port information in the wlw-runtime-config.xml file see wlw-runtime-config.xml in the WebLogic Workshop reference documentation.