sap net weaver composition environment

87
Understanding the Project Management and Employee Services Application SAP NetWeaver Composition Environment Document Version 1.00 – March 2007

Upload: valentini400

Post on 18-Apr-2015

78 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: SAP Net Weaver Composition Environment

Understanding the Project Management and Employee Services Application

SAP NetWeaver Composition Environment

Document Version 1.00 – March 2007

Page 2: SAP Net Weaver Composition Environment

SAP AG Neurottstraße 16 69190 Walldorf Germany T +49/18 05/34 34 24 F +49/18 05/34 34 20 www.sap.com

© Copyright 2005 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, and Informix are trademarks or registered trademarks of IBM Corporation in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc. JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. MaxDB is a trademark of MySQL AB, Sweden.

SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary. These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty. Disclaimer Some components of this product are based on Java™. Any code change in these components may cause unpredictable and severe malfunctions and is therefore expressively prohibited, as is any decompilation of these components. Any Java™ Source Code delivered with this product is only to be used by SAP’s Support Services and may not be modified or altered in any way. Documentation on SAP Service Marketplace You can find this documentation at service.sap.com/instguidesNW04

Page 3: SAP Net Weaver Composition Environment

T yp o g r a p h i c C o n v e n t i o n s I c o n s

Type Style Represents

Example Text Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options.

Cross-references to other documentation.

Example text Emphasized words or phrases in body text, graphic titles, and table titles.

EXAMPLE TEXT Technical names of system objects. These include report names, program names, transaction codes, table names, and key concepts of a programming language when they are surrounded by body text, for example, SELECT and INCLUDE.

Example text Output on the screen. This includes file and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools.

Example text Exact user entry. These are words or characters that you enter in the system exactly as they appear in the documentation.

<Example text> Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system.

EXAMPLE TEXT Keys on the keyboard, for example, F2 or ENTER.

Icon Meaning

Caution

Example

Note

Recommendation

Syntax

Page 4: SAP Net Weaver Composition Environment

Contents

1 PROJECT MANAGEMENT AND EMPLOYEE SERVICES APPLICATION .................... 1 2 RUNNING THE APPLICATION......................................................................................... 1

2.1 Setting Up Application Users .................................................................................... 2 2.2 Running the Predeployed Application....................................................................... 3 2.3 Deploying and Running the Application from NWDS................................................ 3 2.4 Scenario Walkthrough............................................................................................... 6

2.4.1 Managing Projects.......................................................................................... 7 2.4.2 anaging Employees........................................................................................ 7

3 SCENARIO OVERVIEW.................................................................................................... 8 3.1 Application Data Model ............................................................................................. 8 3.2 Application Layers................................................................................................... 11

4 APPLICATION DESIGN .................................................................................................. 12 4.1 Persistence Layer ................................................................................................... 12 4.2 Business Logic Layer .............................................................................................. 13 4.3 Presentation Layer .................................................................................................. 13

5 REBUILDING THE PROJECT MANAGEMENT AND EMPLOYEE SERVICES APPLICATION ................................................................................................................. 14 5.1 Developing the Persistence Entities ....................................................................... 15

5.1.1 Creating the EDMProjectEJBDemo ............................................................. 15 5.1.2 Defining a Connection to the Database Schema ......................................... 17

5.2 Generating the Project Entities ............................................................................... 18 5.2.1 Implementing the Employee Entity............................................................... 23 5.2.2 Registering a Data Source Alias .................................................................. 29

5.3 Developing the Session Beans ............................................................................... 31 5.3.1 Creating the ProjectManagementService Session Bean ............................. 31 5.3.2 Implementing the ProjectManagementService Session Bean ..................... 33

5.4 Developing the Message Driven Beans.................................................................. 36 5.4.1 Creating the ProjectChangeReceiver Bean ................................................. 37 5.4.2 Defining the Message Destination for the Bean........................................... 38 5.4.3 Implementing the ProjectChangeReceiver Bean ......................................... 39

5.5 Reference................................................................................................................ 40 5.5.1 CeraDepartment Source Code..................................................................... 40 5.5.2 CeraEmployee Source Code........................................................................ 42 5.5.3 CeraNavigation Source Code....................................................................... 46 5.5.4 CeraProject Source Code ............................................................................ 48 5.5.5 CeraPrjHistory Source Code ........................................................................ 51 5.5.6 CeraSkill Source Code ................................................................................. 54 5.5.7 CeraUsergroup Source Code....................................................................... 55 5.5.8 ApplicationResetReceiver Source Code ...................................................... 57 5.5.9 DataResetService Source Code .................................................................. 60 5.5.10 EmployeeManagementService Source Code .............................................. 66

Page 5: SAP Net Weaver Composition Environment

5.5.11 ProjectChangeReceiver Source Code ......................................................... 73 5.5.12 ProjectChangeSender Source Code............................................................ 76 5.5.13 ProjectManagementService Source Code ................................................... 78 5.5.14 Application Users and User Groups ............................................................. 81

Page 6: SAP Net Weaver Composition Environment

Project Management and Employee Services Application March 2007

Setting Up Application Users

1 Project Management and Employee Services Application

This documentation provides information about the architecture and the implementation of the Project Management and Employee Services application. See:

● Scenario Overview [Page 8]

● Application Design [Page 12]

● Rebuilding the Application [Page 14]

2 Running the Application Use This procedure describes how to set up application users, how to run the application, and how to review the current business scenarios.

The application is predeployed on your server during installation. There are two options to run the application as described below. For both cases you need to perform the user set up first.

Procedure ...

1. Set up application users.

See: Setting Up Application Users [Page 2]

2. Access and run the application.

○ Run the application that is predeployed during the SAP NetWeaver Composition Environment 1.0 installation

See: Running the Predeployed Application [Page 3]

○ Undeploy existing application (if any) and deploy and run the application from the SAP NetWeaver Developer Studio

See: Deploying and Running the Application from NWDS [Page 3]

3. Review the business scenarios.

See: Scenario Walkthrough [Page 6]

Project Management and Employee Services Application 1

Page 7: SAP Net Weaver Composition Environment

Running the Application March 2007

Setting Up Application Users

2.1 Setting Up Application Users

Use This documentation describes how to set up initial users for the Project Management and Employee Services application.

Procedure ...

1. Import the application code from the Welcome page of the SAP NetWeaver Developer Studio. To do this:

a. Launch your SAP NetWeaver Developer Studio

b. Specify the workspace

c. From the Welcome page, select Samples → Project Management and Employee Services

The application source code is imported in your workspace. Along with the code you can see the UME scripts under ra_edm_prjmgmt_dict\resource\ume.

2. From your browser, start the SAP NetWeaver Administrator: http://<server>:<port>/nwa.

For example, http://localhost:50100/nwa.

When prompted for a log on, use the following credentials:

○ User ID: administrator

○ Password: the password set during SAP NetWeaver Composition Environment installation

3. Choose Identity Management.

4. Go to Batch Import → Browse.

Make sure you enable the option Overwrite Existing Data before proceeding with the import of the files.

5. In your file system, browse to the correct location <NWDS_workspace>\ra_edm_prjmgmt_dict\ressource\ume and choose Upload for each of the files. Use Return to Batch Import to upload the next file.

For example, C:\workspace\ra_edm_prjmgmt_dict\ressource\ume\group_employee_itelo.dat.

Make sure you upload them in the following order: group_employee_itelo.dat role_employee_itelo.da user_employee_telo.dat

a. user_employee_itelo.dat

b. group_employee_itelo.dat

c. role_employee_itelo.dat

Project Management and Employee Services Application 2

Page 8: SAP Net Weaver Composition Environment

Running the Application March 2007

Running the Predeployed Application

2.2 Running the Predeployed Application

Prerequisites Make sure you have completed the step Setting Up Application Users [Page 2] before proceeding with the following procedure.

Procedure ...

1. Open the Servers view, by choosing Window → Show View → Servers from the main menu.

Make sure the server status is Started and that the server host and server port are set correctly. To do this, go to Window → Preferences → SAP AS JAVA.

For example, for a local SAP NetWeaver Composition Environment installation the settings are:

○ Message Server Port: 3600

○ Message Server Host: localhost

If you use a remote SAP NetWeaver Composition Environment installation, enter the corresponding IP address.

2. To start the application, you can type the following address in your Web browser http://<host>:<port>/EDMProjectWEB . Alternatively, you can run the application from SAP MMC. To do this:

a. In the SAP MMC, browse the tree structure in the left-hand pane to locate the J2EE Aliases node. The result pane on the right-hand side displays the deployed applications, their aliases, and further details.

b. To launch the application from the MMC, select EDMProjectWEB and from the context menu choose Launch Application.

3. To log on to the application, use the credentials listed in the Reference section under: Application Users and User Groups [Page 81]

After you have set up the users and attempt to log on to the application you need to reset the password. The default one is welcome123.

...

2.3 Deploying and Running the Application from NWDS

Use If you use this option you need to undeploy the existing (predeployed) application and deploy the one from the SAP NetWeaver Developer Studio.

Project Management and Employee Services Application 3

Page 9: SAP Net Weaver Composition Environment

Running the Application March 2007

Deploying and Running the Application from NWDS

Prerequisites Make sure you have completed the step Setting Up Application Users [Page 2] before proceeding with the following procedure.

You have opened the SAP NetWeaver Developer Studio, and imported the application from Welcome page → Samples → Project Management and Employee Services

Procedure

1. Undeploy the Predeployed Application ...

1. From the Developer Studio main menu, select Window → Show View → Other → Deploy View → Undeploy View.

2. Select the component xapps~ra.edm.prjmgmt.jee.app(sap.com) and choose Add Items to undeploy list. Using the same steps, add to the undeploy list the following two components:

○ xapps~ra.edm.prjmgmt.content(sap.com)

○ xapps~ra.edm.prjmgmt.dict(sap.com)

3. After you have added the components to the undeploy list, choose Undeploy all items in the list.

4. Choose OK to confirm.

Project Management and Employee Services Application 4

Page 10: SAP Net Weaver Composition Environment

Running the Application March 2007

Deploying and Running the Application from NWDS

2. Deploy the Java Dictionary Tables from the SAP NetWeaver Developer Studio

5. Deploy the Java Dictionary tables. To do this:

a. Open the Dictionary perspective.

b. In the Dictionary Explorer, select the project node ra_edm_prgmgmt_dict.

c. From the context menu of the project node, choose Create Archive.

d. From the same context menu, choose Deploy.

6. Deploy the content of the tables. To do this:

a. Open the Navigator view for the same dictionary project.

b. Expand the ressource/content folder. Here you find the archive file

sap.com~ra.edm.prjmgmt.content.sda.

c. To deploy the archive, choose Deploy from its context menu.

3. Deploy and Run the Application 7. Deploy the application. To do this:

a. To open the Servers view, choose Window → Show View → Servers from the main menu.

b. To add the project to the deployment list, choose Add and Remove Projects from the SAP Server context menu.

c. Select the ra.edm.prjmgmt.jee.app from the Available projects list and choose Add to add it to the Configured projects list.

Project Management and Employee Services Application 5

Page 11: SAP Net Weaver Composition Environment

Running the Application March 2007

Scenario Walkthrough

d. Choose Finish.

8. Run the application.

You can use the instructions as for the predeployed application.

See: Running the Predeployed Application [Page 3]

2.4 Scenario Walkthrough This section provides basic information for the business case implemented in the application. It describes how to actually manage projects and employees using the application functionality.

To log on to the application, use the credentials listed in the Reference section: Application Users and User Groups [Page 81]

See also:

● Managing Projects [Page 7]

● Managing Employees [Page 7]

Project Management and Employee Services Application 6

Page 12: SAP Net Weaver Composition Environment

Running the Application March 2007

Scenario Walkthrough

2.4.1 Managing Projects

Procedure

1. Creating New Projects ...

1. In the main application menu, choose Create New Project.

2. Type the required data:

○ Project Name

○ Project Description

○ Start date

○ End date

○ Project lead’s name

3. Choose Continue.

4. Review the summary information and choose Save.

2. Assigning Employees to a Project

5. For the corresponding project, choose (Edit).

The project details appear in a separate window.

6. Choose Edit Details.

7. Choose Assign Employees.

8. Select the needed employees and by using the arrow button (->), move them to the right window.

9. Choose Save.

3.Assigning Skills to Project

10. For the corresponding project, choose (Edit).

The project details appear in a separate window.

11. Choose Edit Details .

The Assign Project Skills field appears.

12. Select the needed skills and by using the arrow button (->), move them to the right window.

13. Choose Save.

2.4.2 Managing Employees

Procedure

1.Creating New Employees ...

Project Management and Employee Services Application 7

Page 13: SAP Net Weaver Composition Environment

Scenario Overview March 2007

Application Data Model

1. In the main application menu, choose Create New Employee.

2. Enter the required data:

○ Salutation

○ Firstname

○ Lastname

○ Login

○ Email

○ Salary

○ Currency

○ Department

3. Choose Continue.

2. Creating New Skills ... ...

1. In the main application menu, choose Create New Skill.

2. Type the required data:

○ skill description

○ skill language

○ version

3. Choose Continue.

3 Scenario Overview The Project Management and Employee Services application is explanatory software showing the possibilities for developing applications with the SAP NetWeaver Composition Environment.

This section provides an introduction to the architecture and technologies used for the creation of the application. For more information, see:

● Application Data Model [Page 8]

● Application Layers [Page 11]

3.1 Application Data Model A data model is the database concept representing the application entities, entity attributes, and entity relations persisted in the database schema.

The entities (components) specified for the application are:

● Educational Data Model (EDM) entities:

○ Department

Project Management and Employee Services Application 8

Page 14: SAP Net Weaver Composition Environment

Scenario Overview March 2007

Application Data Model

This entity represents a department. The attributes are ID, name, manager, version, list of employees.

○ Employee

This entity manages the records for the employee instances. The attributes for this entity are employeeId, firstName, lastName, email, skills, emoloyeeDepartment, deptMnager, and so on.

○ Project

This entity is responsible for the records of the project instances. Its attributes are projectId, title, description, startDate, endDate, employess, leader, skills, and so on.

○ Skill

This entity manages the database entries for the skill instances. The attributes are skill Id, description, language, version.

● Entities related to the application features:

○ Navigation

This entity keeps the navigation sets defined for user groups. The available attributes are navigation key, label, href, position, and so on.

○ UserGroup

This entity organizes the employees in user groups by connecting a single user to the set of navigation provided for its kind. The attributes are groupKey, groupName, version, and navigations.

○ ProjectChanges

This entity keeps a record of the changes performed on the projects. For example, change of the corresponding dates, change of the list of employees, and so on. The entity attributes are id, project id, title, description, startDate, endDate, employee leader, version, change date, and so on.

Figure: Application data model describing entities, relations, and attributes

Project Management and Employee Services Application 9

Page 15: SAP Net Weaver Composition Environment

Scenario Overview March 2007

Application Data Model

For the model presented in application, we have the following relations between the entities:

○ Department – Employee

Bidirectional one-to-many relationship for regular employees, and bidirectional one-to-one relationship for employees designated as department managers.

○ Project – Employees

Bidirectional many-to-many relationship for regular employees, and bidirectional one-to-one relationship for employees designated as project leads.

○ Project – Skill

Unidirectional many-to-many relationship.

○ Employee – Skill

Unidirectional many-to-many relationship.

○ Employees – UserGroup

Unidirectional many-to-many relationship.

○ UserGroup – Navigation

Unidirectional many-to-many relationship.

Project Management and Employee Services Application 10

Page 16: SAP Net Weaver Composition Environment

Scenario Overview March 2007

Application Layers

○ Project-Projectchanges

Unidirectional one-to-many relationship.

3.2 Application Layers As a business application based on Java EE 5 technology, the application consists of the following application layers:

• Presentation (UI) layer

• Business layer

• Persistence layer

See the figure below to become familiar with the model of structuring our application.

Persistence Layer Technologies This layer implements the data model of the application. The components we introduced in the Data Model section are implemented as entity beans using Enterprise JavaBeans (EJB) 3.0 technology. EJB version 3.0 presents a new Java Persistency API. It simplifies and standardizes the object-relational mapping. The new Java Persistence API makes the application independent from the specific vendor’s mapping requirements. The developer can either use annotations or XML descriptors to specify object-relational mapping information.

The entity beans are POJOs (Plain Old Java Objects) annotated with metadata. So they can be serialized and distributed across the network even in a persistence-unaware environment. As a consequence of this change, the data transfer objects (DTOs) become obsolete.

Business Layer Technologies This layer performs the session operation between the components and implements the actual entity management. Generally, the layer implements the following business tasks:

● Employee management: finding objects (employees, skills, departments) by different attributes; creating employee and skill instances.

Project Management and Employee Services Application 11

Page 17: SAP Net Weaver Composition Environment

Application Design March 2007

Persistence Layer

● Project management: finding projects by different attributes; creating and updating a project (for example, changing the employees assigned to the project, changing the start and end dates, and so on).

When creating or updating a project, the session bean that implements project management capabilities sends a JMS message to a configured JMS destination (a JMS queue). Message-driven beans enable the asynchronous consumption of JMS messages. A concurrent consumption of messages is possible with the EJB container architecture. The typical message driven bean comprises two parts:

● A “sender” part that sends the message to the queue (the session bean calls this part of the bean)

● A “receiver” part that processes the received messages in the queue (the EJB container calls this part automatically upon a message receipt in the queue). In the application, the MDB just converts the message into a text message and stores it in the Projectchanges entity as a history of the project change.

Presentation (UI) Layer Technologies The presentation layer has the required elements to visualize the controller logic presented in the application business layer. For the implementation of this layer we use JavaServer Faces (JSF) 1.2 and JavaServer Pages (JSP) 2.1 technologies.

Unlike pure servlets and JSP technologies that mix the HTML presentation (VIEW) logic with the programming MODEL and CONTROLLER logic in the application, user interface (UI) designers work with XML-like tags and programmers writes the logic using Java beans. Then designers use these beans properties for the application UI.

4 Application Design This part of the documentation shows common perspectives of the design and implementation of the Project Management and Employee Services application. You can use the hints when creating your own Java EE 5 applications with SAP NetWeaver Composition Environment.

We separate the information in the following subsections:

● Persistence Layer [Page 12]

● Business Logic Layer [Page 13]

● Presentation Layer [Page 13]

4.1 Persistence Layer In this section you can find general guidance for using the SAP NetWeaver Composition Environment to implement a persistence layer of Java EE 5 applications:

● The deployment descriptors are not necessary anymore. The declaration and configuration of Enterprise JavaBeans (EJBs) in the deployment descriptor can be

Project Management and Employee Services Application 12

Page 18: SAP Net Weaver Composition Environment

Application Design March 2007

Business Logic Layer

defined directly within the Java code, using the annotations metadata facility (a set of intelligent defaults for the most common cases or configuration by exception)

● You can replace DAOs (Data Access Objects) with the EJB 3.0 Java Persistence API.

In EJB 3.0, the Persistence API uses metadata annotations to define persistence and relationship criteria on the lines of object-relational mapping concepts.

● The business/domain model is implemented using entity beans and you can rely on the direct usage of entity beans to transport values and objects. The entities can be detached (decoupled) with the underlying persistence layer. This advantage makes Data Transfer Objects (DTOs) obsolete.

● Do not exaggerate the connections of entities by defined relationships.

● Decide carefully when to use lazy fetching (specification does not require a server to provide it).

Lazy fetching can improve the application performance dramatically, but unfortunately detached entities do not support lazy fetching. Detaching means that an entity can be passed to a separate application tier (for example, from EJB to Web tier). However, an entity that is outside the persistence context does not have valid references to entity sets (collections, single entities) of lazy relations. To get lazy related entities or collections of a relation tree you have to go back and request the entity that owns the relation and fetch the related entities again in the context of the persistence unit. That feature can influence your application design and has to be considered in an early stage of the design and development.

● To improve performance, loosely-connected entities with relationships that are not expected to be used so regularly can be loaded by queries.

4.2 Business Logic Layer The business logic layer of the Project Management and Employee Services application is implemented via session beans, which are part of the Enterprise JavaBeans 3.0 technology. You can find our guidance below:

● Create only the interfaces that are really necessary. In most cases, the local interface fulfils the requirements and it is the recommended approach if all parts of your application run in the same Java Virtual Machine (JVM).

● The EJB 3.0 specification introduces an important change in the way enterprise beans are accessed and called. You can replace the earlier service locator pattern that utilized Java Naming and Directory Interface (JNDI) lookups with the Dependency Injection pattern. Thus, the complexity around JNDI API usage is removed from the bean developer's and client’s viewpoint.

4.3 Presentation Layer The presentation layer of the Project Management and Employee Services application uses JSF 1.2 and JSP 2.1 technologies. Below, you can find our hints related to this layer:

● Create beans to wrap EJBs (used as JSF-managed beans to combine the dual layers of Web actions and EJBs).

● We do not recommend you mix Frames technology in JSF pages as it is difficult to handle JSF navigation.

Project Management and Employee Services Application 13

Page 19: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Presentation Layer

● Use backing beans and attributes defined therein in the smallest scope that fits the requirement.

● Avoid using properties of global (session/application) scope at different pages, especially for different meanings.

● Clear separation of concerns to reduce possible side-effects.

● Standardize similar UIs and use fitting beans that can be configured in the faces-config to serve in each of the cases.

● Cached entities (or lists of them) in higher layers may worsen the memory consumption and performance.

● Avoid huge lists and objects to be cached.

● Think about maintaining the most recent state of cached entities.

● Restrict access to Create, Read, Update, Delete (CRUD) operations for these entities to a small, well-maintained API. When caching, strive for a consistent manner to avoid side effects or locking exceptions.

● Usage of multiple forms on one page could lead to inconsistency.

● Only use multiple forms on one page if both forms are distinct semantically and lead to independent navigation paths.

● Consider where to store JSF View state information.

The specification and implementation provide client-side saving and server-side saving.

In case of views with a huge number of UI components, server-side state saving should be considered. In this way, the communication traffic is reduced as the view state is not propagated back to the client. For more information, see JSF 1.2 Specification section 7.6.2 State Saving Alternatives and Implications.

5 Rebuilding the Project Management and Employee Services Application

Use In this tutorial you learn how to implement the Project Management and Employee Services persistence and business logic.

Procedure The implementation comprises the following steps: ...

1. Developing the Persistence Entities [Page 15]

As a first step, you implement the application data model using persistence entities. Using the Dali object-relational (O/R) mapping tools, you can easily generate the entities from the database tables that already exist in your DB.

2. Developing the Session Beans [Page 31]

Next you implement the business logic for project and employee management using session beans.

Project Management and Employee Services Application 14

Page 20: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

TDeveloping the Persistence Entities

3. Developing the Message Driven Bean [Page 36]

Using a message-driven bean, you enable the application to use Java Messaging Service (JMS) and to record each change that is made to projects in a project history.

5.1 Developing the Persistence Entities Use This tutorial shows you how to implement the data model of the Project Management and Employee Services application using persistent entities. It uses the Employee entity as an example.

Using the Dali Object-relational (O/R) mapping tools integrated in the SAP NetWeaver Developer Studio, you can develop persistent entities that comply with the Java Pesistence API (JPA) standard.

Procedure To create the Employee entity, you complete the following steps:

4. Creating the EDMProjectEJBDemo [Page 15]

Persistent entities are not developed in a specific project. As they are usually packaged in an Enterprise JavaBeans (EJB) module, they are therefore developed in an EJB 3.0 project.

5. Defining a Connection to the Database Schema [Page 17]

This makes it possible to list all tables that are created for the application. You can generate entities used by the application, based on the table definitions.

6. Generating the Project Entities [Page 18]

In this step you select the tables that you want to generate persistent entities from. The tools do that automatically for you and generate the Plain Old Java Objects (POJOs) that are mapped to the respective database table.

7. Implementing the Employee Entity [Page 23]

In this step you define relationships between your entities to reflect the relations defined by the data model of the application.

8. Registering a Data Source Alias [Page 29]

When you rebuild the application a new logical name (data source alias) is necessary that is mapped to a real data source. Every application uses a separate (own) data source alias.

5.1.1 Creating the EDMProjectEJBDemo

Prerequisites In the SAP NetWeaver Developer Studio, you have opened the J2EE perspective.

Procedure ...

1. Choose File →New → Project from the main menu.

Project Management and Employee Services Application 15

Page 21: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

TDeveloping the Persistence Entities

2. On the New Project screen, choose EJB → EJB Project 3.0.

3. On the next screen, do the following:

○ Enter EDMProjectEJBDemo in the Project name field

○ Select Add project to an EAR

○ Enter EDMProjectEARDemo in the EAR Project Name field

4. Choose Finish to complete the wizard.

Result The Developer Studio generates the EDMProjectEJBDemo and EDMProjectEARDemo projects. The EAR project references the EJB one (the referred project is included in the list of modules that is packaged in the EAR file).

Project Management and Employee Services Application 16

Page 22: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

TDeveloping the Persistence Entities

5.1.2 Defining a Connection to the Database Schema

Procedure To define a connection to the database schema where the application tables are created, follow the procedure described in Creating Database Connections [External].

Connect to the database schema with the following credentials:

● User ID: SAP<SID>DB

For example, the default SID is CE1 and the user ID is SAPCE1DB

● Password: The master password entered during SAP NetWeaver Composition Environment 1.0 installation

Project Management and Employee Services Application 17

Page 23: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

5.2 Generating the Project Entities

Procedure 5. To enable your project to use persistence features, choose Java Persistence → Add

Java Persistence from the context menu.

Project Management and Employee Services Application 18

Page 24: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

6. Specify the database to which your persistent entities should be mapped by providing the following details:

a. In the Database Explorer view, select the name of the database from the Connection dropdown list.

b. Select CE1 schema from the Schema dropdown list.

7. To create persistence.xml, packaged with your EJB 3.0 module, provide the following information in the Packaging Settings:

a. Leave the Persistence provider field empty.

b. Enter ems/EJB3_EDM_DEMO_PU in the Persistence unit name field. You use this name later on in your session EJBs code to inject the persistence unit.

c. Choose Finish.

Project Management and Employee Services Application 19

Page 25: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

8. Choose Java Persistence → Generate Entities from the context menu of the EDMProjectEJBDemo.

Project Management and Employee Services Application 20

Page 26: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

9. On the Create Entities screen do the following:

a. Enter com.sap.nwce.ra.edm.ejb.entity in the Package field.

b. Select the DB tables that should be used to generate entities from. Change the default names of the entities in the Entity Name column as follows:

Table Entity Name

CERA_DEPARTMENT CeraDepartment

CERA_EMPLOYEE CeraEmployee

CERA_NAVIGATION CeraNavigation

CERA_PROJECT CeraProject

CERA_SKILL CeraSkill

CERA_USERGROUP CeraUsergroup

CERA_PRJ_HISTORY CeraPrjHistory

Project Management and Employee Services Application 21

Page 27: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

10. To complete the procedure, choose Finish.

Result The entities are generated and added to the EDMProjectEJBDemo:

Project Management and Employee Services Application 22

Page 28: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

5.2.1 Implementing the Employee Entity

Use This procedure shows you how to implement the entities you generated in the previous step of the tutorial.

The automatic generation detects all columns of the tables and generates persistent fields in the entity accordingly. In this case, the CERA_EMPLOYEE table contains a column DEPARTMENT_ID, which is a foreign key in a one-to-many relationship between the Department and Employee entities. This means that the Employee entity should not contain a persistent entity mapped to this column.

For each relationship the Employee entity participates in, you must define new variables that hold the foreign keys of the inverse side of the relationships.

Procedure

1. Adjusting the Persistent Fields ...

1. Open the entity for editing.

The Persistence Outline view displays all persistent fields this entity has.

Project Management and Employee Services Application 23

Page 29: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

2. Delete the departmentId field and the corresponding getter and setter methods using

the source code editor.

3. Add the following new variables: private List<CeraProject> projectsLeadByEmployee = new ArrayList<CeraProject>(); private List<CeraProject> projectsByParticipant = new ArrayList<CeraProject>(); private List<CeraSkill> skills = new ArrayList<CeraSkill>(); private List<CeraUsergroup> groups = new ArrayList<CeraUsergroup>(); private CeraDepartment employeeDepartment; private CeraDepartment deptManager;

4. Import the necessary classes by choosing Source → Organize Imports from the context menu.

Make sure you select the java.util.List from the proposed options.

At this point you can ignore the errors that you get for the employeeDepartment and the deptManager entries. They are handled later on when you set relationships between the entities.

5. To generate getter and setter methods for the new fields, choosing Source → Generate Getters and Setter.

Select all variables in the list except serialVersionUID, and choose OK.

6. Add the following two methods that are used to manage an employee’s set of skills: public void addSkill(CeraSkill s) { this.getSkills().add(s); } public void removeSkill(CeraSkill s) { this.getSkills().remove(s); }

Project Management and Employee Services Application 24

Page 30: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

2. Defining ID Generation 7. Select the employeeId field from the Persistence Outline view.

This field is already marked as one that holds the primary key of the Employee entity based on the settings of the CERA_EMPLOYEE table.

8. Open the Persistence Properties view by choosing Window → Show View → Other → Java Persistence → Persistence Properties.

9. To define the primary key generation strategy, open the PK Generation tab and proceed as follows:

a. Choose Primary Key Generation.

b. Select Table from the Strategy dropdown list.

c. Enter IdGenerator in the Generator Name field.

d. Expand the Table Generator list and select the Table Generator checkbox.

e. Select CERA_GENERATOR from the Table dropdown list.

f. Select BEAN_NAME from the Primary Key Column.

g. Select MAX_ID from the Value column.

3. Defining Relationships ...

1. Define a one-to-one relationship between the Employee and Department entities, in which Employee is the owning side of the relationship:

a. Select the deptManager field from the Persistence Outline view.

b. Provide the following information in the Persistence Properties view

Property Value

Map As One to One

Fetch Type Lazy

Mapped By Manager

This generates the following annotation for the deptManager field:

@OneToOne(mappedBy="manager")

2. Define a many-to-one relationship between the Employee and the Department entities for the employeeDepartment variable. Complete the following steps:

a. Select the employeeDepartment field from the Persistence Outline view.

Project Management and Employee Services Application 25

Page 31: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

b. On the General tab page of the Persistence Properties view, enter the following data:

Property Value

Map As Many to one

Fetch Type Lazy

c. On the Join Columns tab page, enable the Override Default indicator, and choose Add. Select DEPARTMENT_ID from the Name dropdown list, leave Referenced Column Name empty, and choose OK.

d. Remove the default entry.

This generates the following code for the employeeDepartment field:

@ManyToOne(fetch=FetchType.LAZY)

@JoinColumn(name="DEPARTMENT_ID")

private CeraDepartment employeeDepartment;

3. Using the same procedure you can define the other relationships that Employee participates in. To input in the respective fields in the Persistence Properties view, use the tables below for the corresponding fields:

○ Persistent field groups

Property Value

Tab Page: General

Map As Many to many

Fetch Type Lazy

Tab Page: Join Table

Name CERA_EMP_UGR

Join Columns Name: EMPLOYEE_ID

Referenced Column Name: EMPLOYEE_ID

Inverse Join Columns Name: GROUP_ID

Referenced Column Name: GROUP_ID

Generated Code @ManyToMany(fetch=FetchType.LAZY) @JoinTable(name="CERA_EMP_UGR", joinColumns = @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name = "GROUP_ID", referencedColumnName = "GROUP_ID")) private List<CeraUsergroup> groups = new ArrayList<CeraUsergroup>();

○ Persistent field skills

Property Value

Tab Page: General

Map As Many to many

Fetch Type Eager

Tab Page: Join Table

Project Management and Employee Services Application 26

Page 32: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

Name CERA_EMP_SKILL

Join Columns Name: EMPLOYEE_ID

Referenced Column Name: EMPLOYEE_ID

Inverse Join Columns Name: SKILL_ID

Referenced Column Name: SKILL_ID

Generated Code @ManyToMany(fetch=FetchType.EAGER) @JoinTable(name="CERA_EMP_SKILL", joinColumns = @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name = "SKILL_ID", referencedColumnName = "SKILL_ID")) private List<CeraSkill> skills = new ArrayList<CeraSkill>();

○ Persistent field projectsLeadByEmployee

Property Value

Tab Page: General

Map As One to many

Fetch Type Lazy

Mapped By Leader

Generated Code @OneToMany(mappedBy="leader", fetch = FetchType.LAZY) private List<CeraProject> projectsLeadByEmployee = new ArrayList<CeraProject>();

○ Persistent field projectsByParticipant

Property Value

Tab Page: General

Map As Many to many

Fetch Type Lazy

Mapped By Employees

Generated Code @ManyToMany(mappedBy="employees", fetch = FetchType.LAZY) private List<CeraProject> projectsByParticipant = new ArrayList<CeraProject>();

While creating the relationships in which Employee is the owning side, you can get error messages issued by the Developer Studio. The error messages disappear when you create the entity that is the inverse side of the relationship. To implement the other entities, copy the source codes from Reference [Page 40].

Project Management and Employee Services Application 27

Page 33: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

4. Defining Named Queries 4. Open the Outline view (Window → Show view → Outline from the main menu) and

select Employee.

5. Choose Java EE Annotations → Entity → NamedQueries from the context menu for Employee.

This generates the @NamedQueries annotation for the Employee class.

6. Copy and paste the following code in the place where the NamedQueries annotation displays.

Project Management and Employee Services Application 28

Page 34: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

@NamedQueries({ @NamedQuery(name="Employee.getAll", query="SELECT e FROM Employee e"), // @NamedQuery(name="Employee.findByNamePart", query="SELECT e FROM Employee e WHERE lower(e.lastName) LIKE :namepart OR lower(e.firstName) LIKE :namepart1"), // requires native datasource @NamedQuery(name="Employee.findByNamePart", query="SELECT e FROM Employee e WHERE e.lastName LIKE :namepart OR e.firstName LIKE :namepart1"), @NamedQuery(name="Employee.findByLogin", query="SELECT e FROM Employee e WHERE e.login = :login") })

This implements the names and the queries shown in the table bellow:

Name Query

Employee.findByNamePart SELECT e FROM Employee e WHERE lower(e.lastName) LIKE :namepart OR lower(e.firstName) LIKE :namepart1

Employee.findByLogin SELECT e FROM Employee e WHERE e.login = :login

Employee.getAll SELECT e FROM Employee e

5.2.2 Registering a Data Source Alias

Use You use this procedure to define DataSource aliases and deploy them with your applications.

A DataSource alias is a logical name mapped to the name of a real DataSource available in the system. You use the DataSource alias in your application code to connect to the underlying DataSource

Procedure ...

1. From the project navigation pane, select the folder META-INF under EDMProjectEARDemo.

2. Select File → New → Other → XML → XML and choose Next.

3. Select Create the XML file from an XML schema file and choose Next.

4. Select EDMProjectEARDemo → META-INF for parent folder.

5. In the File name field, enter data-source-aliases.xml.

6. Select the option Select XML Catalog entry.

7. From the XML catalog list, select data-source-aliases.xsd and choose Next.

Project Management and Employee Services Application 29

Page 35: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Generating the Project Entities

8. In the Root element drop-down list, select data-sourse-aliases and choose Finish.

The data-source-aliases.xml is created and added to the project. The xml file opens for editing automatically.

9. In the Design tab of the data-source-aliases.xml, browse to the data-source-name and alias and enter the following names:

○ data source name: ${com.sap.datasource.default}

○ alias: CE_RA_DS

10. Open for editing the persistence.xml under EDMProjectEJBDemo/ejbModule/META-INF.

11. To enter CE_RA_DS for jta-data-source, paste the following code in the persistence.xml. <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"> <persistence-unit name="ems/EJB3_EDM_DEMO_PU">

Project Management and Employee Services Application 30

Page 36: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Session Beans

<description>EDM EJB3 Demo Application Persistence Unit</description> <jta-data-source>CE_RA_DS</jta-data-source> </persistence-unit> </persistence>

5.3 Developing the Session Beans

Use This tutorial shows you how to implement the business logic layer of the Project Management and Employee Services application. It uses the ProjectManagement Session bean as an example. Using the the same procedure, you can implement the rest of the session beans copying the source codes from Reference [Page 40].

Procedure To develop the ProjectManagementService bean, you need to go through the following steps: ...

1. Creating the ProjectManagementService Session Bean [Page 31]

Using the session EJB wizard, you create the bean with its main requisites, such as session type and access type of the business interface.

2. Implementing the ProjectManagementService Session Bean [Page 33]

a. Inject resources into the environment.

You inject the persistence context to provide access to the EntityManager (EM) and use the EM’s API to work with queries in the bean’s business methods. You also inject a reference to another session bean, as well as make a session context available to the ProjectManagementService bean.

b. Write queries to the database.

You use the EM APIs to implement the bean’s business methods that send queries to the database.

c. Expose the business methods to the business interface.

You use the Developer Studio tools to add the bean’s methods to its local business interface.

5.3.1 Creating the ProjectManagementService Session Bean

Prerequisites You have opened the J2EE perspective in the SAP NetWeaver Developer Studio.

Procedure ...

1. Choose File → New → Other from the main menu.

Project Management and Employee Services Application 31

Page 37: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Session Beans

2. Choose EJB → EJB Session Bean 3.0 on the Select a wizard screen

3. On the New EJB Session Bean 3.0 screen, proceed as follows:

a. Enter ProjectManagementService in the EJB Name field.

b. Enter com.sap.nwce.ra.edm.ejb.services in Default EJBPackage.

c. Select Stateless for Session Type.

d. Deselect Remote from Create Interface.

4. Choose Finish to complete the wizard.

Result This creates the ProjectManagementService and the associated local business interface ProjectManagementServiceLocal. In addition, the bean is with container-managed transaction demarcation, which is the default demarcation for session beans. Therefore, you do not need to set the @Local and @TransactionManagement annotations explicitly.

Project Management and Employee Services Application 32

Page 38: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Session Beans

5.3.2 Implementing the ProjectManagementService Session Bean

Procedure

1. Injecting Resources to Bean’s Environment ...

1. Open the ProjectManagementService bean in the source code editor and define the following variables that hold the injected resources:

private EntityManager em; private SessionContext sessionCtx; private ProjectChangeSenderLocal jmsSender;

2. To inject the persistence context, select the em variable in the Outline view and choose Java EE Annotations → General → PersistenceContext from the context menu.

This generates the @PersistenceContext annotation.

3. Enter ems/EJB3_EDM_DEMO_PU as a value of the unitName attribute of the

annotation.

4. Inject the remaining two resources using the same procedure.

Variable Context Menu Path Attribute Values

sessionCtx Java EE Annotations → References → Resource

Project Management and Employee Services Application 33

Page 39: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Session Beans

jmsSender Java EE Annotations → References → EJB

name="JMSSenderSessionLocal"

5. From the secondary mouse button (within the code content), select Source → Organize Imports → javax.persistence and chooose Finish.

2. Querying the Database Using the simplified EntityManager API, as well as the new named queries available in EJB3.0 query language, it is easy to implement business methods that query the database. For example, to find a project by its ID, you do not have to write your own query. EntityManager’s find() method does that for you. You can also use EntityManager’s createNameQuery() method to execute any of the named queries you defined in the Employee entity.

Use the following code to define and implement all methods of the ProjectManagementService bean: /** * Get a project by its id. * @return project entity */ public roject getProjectById ng pId){ CeraP (Stri return em.find(CeraProject.class, Integer.valueOf(pId)); } /** * Get all projects in a single list. * @return list of all projects */ @SuppressWarnings("unchecked") public List<CeraProject> getAllProjects(){ Query query = em.createNamedQuery("Project.getAll"); List<CeraProject> result = query.getResultList(); return result; } /** * Get all assigned projects. * @return list of all assigned projects */ @SuppressWarnings("unchecked") public List<CeraProject> getAssignedProjects(int pEmployeeId){ Query query = em.createNamedQuery("Project.getAllForEmployee"); query.setParameter("employeeId", pEmployeeId); List<CeraProject> result = query.getResultList(); return result; } /** * s a project. Remove * @param pProject */ public void removeProject(CeraProject pProject){ em.remove(pProject);

Project Management and Employee Services Application 34

Page 40: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Session Beans

} /** * Persists a project (create or update) and sends a message to * the projectchangequeue to notify the system that the project * was changed */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public CeraProject createProject(CeraProject pProject){ CeraProject result = em.merge(pProject); String caller = sessionCtx.getCallerPrincipal().getName(); jmsSender.sendMessage(result, caller); return result; } /** * list of projects by its name or description. Get a * @param Name or description fragment * @return List of projects */ @SuppressWarnings("unchecked") public List<CeraProject> findProjectByNameOrDescription(String pNameFragment){ Query query = em.createNamedQuery("Project.findByNameOrDescPart"); String parameter = pNameFragment.toLowerCase(); query.setParameter("namepart", "%"+parameter+"%"); query.setParameter("namepart1", "%"+parameter+"%"); eraProject> result = query.getResultList(); List<C return result; }

3. Exposing Methods to the Local Business Interface ...

1. Select, for example, the getProjectById() method of the bean in the Outline view.

2. To add it to the local business interface, choose EJB Methods → Add to Local Interfaces.

This adds the method’s definition to the business interface of the bean, thereby making it visible to other enterprise beans in the application

Project Management and Employee Services Application 35

Page 41: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Message Driven Beans

3. Repeat the same steps to expose all other methods of the ProjectManagementService

bean to its business interface.

Result The implementation of the bean should now look like the one shown in ProjectManagementService Source Code [Page 78].

5.4 Developing the Message Driven Beans

Use In this part of the tutorial you learn how to implement the ProjectChangeReceiver message-driven bean that is used for consuming Java Messaging Service (JMS) messages and updating the project management history asynchronously. The application contains an additional message-driven bean – the ApplicationResetReceiver, which you can implement by copying its source code from the Reference [Page 40].

Procedure To develop the bean, you go through the following steps: ...

Project Management and Employee Services Application 36

Page 42: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Message Driven Beans

1. Creating the ProjectChangeReceiver Bean [Page 37]

Using the SAP NetWeaver Developer Studio tools, you create a message-driven bean in the EJB 3.0 project that you created.

2. Defining the Message Destination for the Bean [Page 38]

You register the bean to a destination where the JMS messages are posted.

3. Implementing the ProjectChangeReceiver Bean [Page 39]

a. You enable the bean to consume messages by making it implement the javax.jms.MessageListener interface.

b. You inject the required context variables.

c. You implement the bean’s onMessage method.

5.4.1 Creating the ProjectChangeReceiver Bean

Procedure ...

1. Choose File → New → Other from the main menu.

2. Choose EJB → Message Driven Bean 3.0 on the Select a wizard screen

3. On the New Message Driven Bean 3.0 screen, proceed as follows:

a. Enter ProjectChangeReceiver in EJB Name.

b. Enter EDMProjectEJBDemo in EJB Project.

c. Enter com.sap.nwce.ra.edm.ejb.services in Default EJBPackage.

Project Management and Employee Services Application 37

Page 43: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Message Driven Beans

4. Choose Finish to create the bean.

5.4.2 Defining the Message Destination for the Bean

Procedure ...

1. Open the ProjectChangeReceiver bean in the Java editor.

2. To define the message driven bean properties that refer to configuring its environment, add the respective configuration properties to the activationConfig element of the @MessageDriven annotation:

@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "prjChangeQueue"), })

You complete the definition of the JMS destination used by the ProjectChangeReceiver bean later on using the jms-resource.xml file in the Enterprise Application project for the Project Management and Employee Services application.

Project Management and Employee Services Application 38

Page 44: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Developing the Message Driven Beans

5.4.3 Implementing the ProjectChangeReceiver Bean

Procedure ...

1. Specify that ProjectChangeReceiver implements the javax.jms.MessageListener interface:

public class ProjectChangeReceiver implements MessageListener {

2. Inject a MessageDrivenContext and a PersistenceContext: @Resource public MessageDrivenContext mdc; @PersistenceContext(unitName = "ems/EJB3_EDM_DEMO_PU")

3. Implement the bean’s onMessage method as follows: public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; CeraPrjHistory chPrj = new CeraPrjHistory(); chPrj.setProjectId(msg.getIntProperty("ProjectId")); chPrj.setEndDate(java.sql.Date.valueOf(msg.getStringProperty("EndDate"))); chPrj.setStartDate(java.sql.Date.valueOf(msg.getStringProperty("StartDate"))); chPrj.setTitle(msg.getStringProperty("Title")); chPrj.setDescription(msg.getStringProperty("Description")); chPrj.setLeader(msg.getIntProperty("LeadId")); chPrj.setChangeDate(new java.sql.Timestamp(msg.getLongProperty("ChangeDate"))); chPrj.setStatus(msg.getIntProperty("Status")); chPrj.setChangerId(msg.getStringProperty("Changer")); em.merge(chPrj); logger.info("MESSAGE BEAN: Message received: " + chPrj.getProjectId()); } else { logger.warning( "Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { logger.severe( "MessageBean.onMessage: JMSException: " + e.toString()); e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { logger.severe("MessageBean.onMessage: Exception: " + te.toString()); te.printStackTrace(); } }

Project Management and Employee Services Application 39

Page 45: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

Result The implementation of the bean should now look like the one shown in ProjectChangeReceiver Source Code [Page 73].

5.5 Reference In this section you can find the source codes of all EJB 3.0 session beans, entity beans, and the tables with the user credentials and the relevent user groups of the Project Management and Employee Services application:

● Entity beans: ...

○ Department [Page 40]

○ Employee [Page 42]

○ Navigation [Page 46]

○ Project [Page 48]

○ ProjectChanges [Page 51]

○ Skill [Page 54]

○ UserGroup [Page 55]

● Session beans:

○ DataResetService [Page 60]

○ EmployeeManagementService [Page 66]

○ ProjectChangeSender [Page 76]

○ ProjectManagementService [Page 78]

● Message-driven beans:

○ ProjectChangeReceiver [Page 73]

○ ApplicationResetReceiver [Page 57]

● Application user credentials and user groups:

○ Application Users and User Groups [Page 81]

5.5.1 CeraDepartment Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.entity; import java.io.Serializable; import java.util.ArrayList;

Project Management and Employee Services Application 40

Page 46: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Version; @NamedQueries({ @NamedQuery(name="Department.getAll", query="SELECT d FROM CeraDepartment d") }) @Entity @Table name= ") ( "CERA_DEPARTMENTpublic class CeraDepartment implements Serializable { @Id (name="DEPARTMENT_ID") @Column private String departmentId; private String name; @Version private int version; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="MANAGER_ID", updatable = false) private CeraEmployee manager; @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "employeeDepartment") private List<CeraEmployee> employees = new ArrayList<CeraEmployee>(); private static final long serialVersionUID = 1L; public CeraDepartment() { super(); } public String getDepartmentId() { return this.departmentId; } public void setDepartmentId(String departmentId) { this.departmentId = departmentId; } public g Name() { Strin get return this.name; }

Project Management and Employee Services Application 41

Page 47: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public void setName(String name) { this.name = name; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public CeraEmployee getManager() { return manager; } public void setManager(CeraEmployee manager) { this.manager = manager; } public List<CeraEmployee> getEmployees() { return employees; } public void setEmployees(List<CeraEmployee> employees) { this.employees = employees; } public void addEmployee(CeraEmployee e) { employees.add(e); e.setEmployeeDepartment(this); } public void removeEmployee(CeraEmployee e) { if (employees.remove(e)) { e.setEmployeeDepartment(null); } } }

5.5.2 CeraEmployee Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List;

Project Management and Employee Services Application 42

Page 48: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Version; @NamedQueries({ @NamedQuery(name="Employee.getAll", query="SELECT e FROM Employee e"), // @NamedQuery(name="Employee.findByNamePart", query="SELECT e FROM Employee e WHERE lower(e.lastName) LIKE :namepart OR lower(e.firstName) LIKE :namepart1"), // requires native datasource @NamedQuery(name="Employee.findByNamePart", query="SELECT e FROM Employee e WHERE e.lastName LIKE :namepart OR e.firstName LIKE :namepart1"), @NamedQuery(name="Employee.findByLogin", query="SELECT e FROM Employee e WHERE e.login = :login") }) @Entity @Table(name="CERA_EMPLOYEE") public class CeraEmployee implements Serializable { @Id @Column(name="EMPLOYEE_ID") @GeneratedValue(strategy=GenerationType.TABLE, generator = "IdGenerator") @TableGenerator(name="IdGenerator", table = "CERA_GENERATOR", pkColu = EAN_NAME", valueColumnName = "MAX_ID") mnName "B private int employeeId; private String email; private String currency; private BigDecimal salary; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="DEPARTMENT_ID") private CeraDepartment employeeDepartment; @O (mappedBy="manager") neToOne private CeraDepartment deptManager; private String salutation; @Version private int version;

Project Management and Employee Services Application 43

Page 49: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

@Column(name="LAST_NAME") private String lastName; private String login; @Column(name="FIRST_NAME") private String firstName; @OneToMany(mappedBy="leader", fetch = FetchType.LAZY) private List<CeraProject> projectsLeadByEmployee = new ArrayList<CeraProject>(); @ManyToMany(mappedBy="employees", fetch = FetchType.LAZY) private List<CeraProject> projectsByParticipant = new ArrayList<CeraProject>(); @ManyToMany(fetch=FetchType.EAGER) @JoinTable(joinColumns = @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name = "SKILL_ID", referencedColumnName = "SKILL_ID"), name = "CERA_EMP_SKILL") private List<CeraSkill> skills = new ArrayList<CeraSkill>(); @ManyToMany(fetch=FetchType.LAZY) @JoinTable(joinColumns = @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name = "GROUP_ID", referencedColumnName = "GROUP_ID"), name = "CERA_EMP_UGR") private List<CeraUsergroup> groups = new ArrayList<CeraUsergroup>(); private static final long serialVersionUID = 1L; public CeraEmployee() { super(); } public int getEmployeeId() { return this.employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public g Currency() { Strin get return this.currency; }

Project Management and Employee Services Application 44

Page 50: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public void setCurrency(String currency) { this.currency = currency; } public BigDecimal getSalary() { return this.salary; } public void setSalary(BigDecimal salary) { this.salary = salary; } public String getSalutation() { return this.salutation; } public void setSalutation(String salutation) { this.salutation = salutation; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public CeraDepartment getDeptManager() { return deptManager; } public void setDeptManager(CeraDepartment deptManager) { this.deptManager = deptManager;

Project Management and Employee Services Application 45

Page 51: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

} public epartment getEmployeeDepartment() { CeraD return employeeDepartment; } public void setEmployeeDepartment(CeraDepartment employeeDepartment) { this.employeeDepartment = employeeDepartment; } public List<CeraUsergroup> getGroups() { return groups; } public void setGroups(List<CeraUsergroup> groups) { this.groups = groups; } public List<CeraProject> getProjectsByParticipant() { return projectsByParticipant; } public void setProjectsByParticipant(List<CeraProject> projectsByParticipant) { this.projectsByParticipant = projectsByParticipant; } public List<CeraProject> getProjectsLeadByEmployee() { return projectsLeadByEmployee; } public void setProjectsLeadByEmployee(List<CeraProject> projectsLeadByEmployee) { this.projectsLeadByEmployee = projectsLeadByEmployee; } public List<CeraSkill> getSkills() { return skills; } public void setSkills(List<CeraSkill> skills) { this.skills = skills; } }

5.5.3 CeraNavigation Source Code /* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.entity;

Project Management and Employee Services Application 46

Page 52: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; @Entity @Table(name="CERA_NAVIGATION") public class CeraNavigation implements Serializable { @Id @Column(name="NAVIGATION_ID") private String navigationId; @Column(name="POS") private int position; @Version private int version; private String label; private String href; private static final long serialVersionUID = 1L; public CeraNavigation() { super(); } public String getNavigationId() { return this.navigationId; } public void setNavigationId(String navigationId) { this.navigationId = navigationId; } public int getPosition() { return this.position; } public void setPosition(int position) { this.position = position; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public String getLabel() { return this.label; }

Project Management and Employee Services Application 47

Page 53: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public void setLabel(String label) { this.label = label; } public String getHref() { return this.href; } public void setHref(String href) { this.href = href; } }

5.5.4 CeraProject Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; @NamedQueries({ @NamedQuery(name="Project.getAll", query="SELECT p FROM Project p"), @NamedQuery(name="Project.getAllForEmployee", query="SELECT p FROM Project p where p.leader.employeeId = :employeeId"), @NamedQuery(name="Project.findByNameOrDescPart", query="SELECT p FROM Project p WHERE p.title LIKE :namepart OR p.description LIKE

Project Management and Employee Services Application 48

Page 54: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

:namepart1") // @NamedQuery(name="Project.findByNameOrDescPart", query="SELECT p FROM Project p WHERE lower(p.title) LIKE :namepart OR lower(p.description) LIKE :namepart1") //requires native datasource }) @Entity @Table(name="CERA_PROJECT") public class CeraProject implements Serializable { @Id @Column(name="PROJECT_ID") @GeneratedValue(strategy=GenerationType.TABLE, generator = "IdGenerator") @TableGenerator(name="IdGenerator", table = "CERA_GENERATOR", pkColumnName = "BEAN_NAME", valueColumnName = "MAX_ID") private int projectId; @ManyToOne lumn(name="LEAD_ID") @JoinCo private CeraEmployee leader; private int status; private String description; @Column(name="START_DATE") @Temporal (TemporalType.DATE) private java.util.Date startDate; private String title; @ManyToMany(fetch=FetchType.EAGER) @JoinTable(joinColumns = @JoinColumn(name = "PROJECT_ID", referencedColumnName = "PROJECT_ID"), inverseJoinColumns = @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMPLOYEE_ID"), name = "CERA_EMP_PRJ") private List<CeraEmployee> employees = new ArrayList<CeraEmployee>(); @ManyToMany(fetch=FetchType.EAGER) @JoinTable(joinColumns = @JoinColumn(name = "PROJECT_ID", referencedColumnName = "PROJECT_ID"), inverseJoinColumns = @JoinColumn(name = "SKILL_ID", referencedColumnName = "SKILL_ID"), name = "CERA_PRJ_SKILL") private List<CeraSkill> skills = new ArrayList<CeraSkill>(); @Version private int version; @Column(name="END_DATE") @Temporal(TemporalType.DATE) private java.util.Date endDate; private static final long serialVersionUID = 1L; public Project() { Cera super(); }

Project Management and Employee Services Application 49

Page 55: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public int getProjectId() { return this.projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public int e tus() { g tSta return this.status; } public void setStatus(int status) { this.status = status; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public Date getEndDate() { return this.endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public List<CeraEmployee> getEmployees() { return employees;

Project Management and Employee Services Application 50

Page 56: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

} public void setEmployees(List<CeraEmployee> employees) { this.employees = employees; } public CeraEmployee getLeader() { return leader; } public void setLeader(CeraEmployee leader) { this.leader = leader; } public List<CeraSkill> getSkills() { return skills; } public void setSkills(List<CeraSkill> skills) { this.skills = skills; } }

5.5.5 CeraPrjHistory Source Code package com.sap.nwce.ra.edm.ejb.entity; import java.io.Serializable; import java.util.Date; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; @Entity @Table name= Y") ( "CERA_PRJ_HISTORpublic class CeraPrjHistory implements Serializable { @Id @TableGenerator(name="IdGenerator", table="CERA_GENERATOR", pkColumnName="BEAN_NAME", valueColumnName="MAX_ID") @GeneratedValue(strategy=GenerationType.TABLE, genera G rator") tor="Id ene private int id; @Column(name="END_DATE")

Project Management and Employee Services Application 51

Page 57: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

@Temporal(TemporalType.DATE) private java.util.Date endDate; @Version private int version; private String description; private String title; private Timestamp changeDate; private int status; (name="LEAD_ID") @Column private int leader; (name="PROJECT_ID") @Column private int projectId; (name="CHANGER_ID") @Column private String changerId; @Column(name="START_DATE") @Temporal (TemporalType.DATE) private java.util.Date startDate; private static final long serialVersionUID = 1L; public CeraPrjHistory() { super(); } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public Date getEndDate() { return this.endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public String getDescription() {

Project Management and Employee Services Application 52

Page 58: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

return this.description; } public void setDescription(String description) { this.description = description; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public Timestamp getChangeDate() { return this.changeDate; } public void setChangeDate(Timestamp changeDate) { this.changeDate = changeDate; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public int getProjectId() { return this.projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public String getChangerId() { return this.changerId; } public void setChangerId(String changerId) { this.changerId = changerId; } public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public int getLeader() { return leader; }

Project Management and Employee Services Application 53

Page 59: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public void setLeader(int leader) { this.leader = leader; } }

5.5.6 CeraSkill Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Version; @NamedQueries({ @NamedQuery(name="Skill.getAll", query="SELECT s FROM Skill s"), @NamedQuery(name="Skill.findByNamePart", query="SELECT b FROM Skill b WHERE b.name LIKE :namepart") // @NamedQuery(name="Skill.findByNamePart", query="SELECT b FROM Skill b WHERE lower(b.name) LIKE :namepart") // requires native datasource }) @Entity @Table(name="CERA_SKILL") public class CeraSkill implements Serializable { @Id @Column(name="SKILL_ID") @GeneratedValue(strategy=GenerationType.TABLE, generator = "IdGenerator") @TableGenerator(name="IdGenerator", table = "CERA_GENERATOR", pkColu = EAN_NAME", valueColumnName = "MAX_ID") mnName "B private int skillId; n@Versio private int version; (name="LANGUAGE_ID") @Column private String language;

Project Management and Employee Services Application 54

Page 60: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

private String name; private static final long serialVersionUID = 1L; public CeraSkill() { super(); } public int e llId() { g tSki return this.skillId; } public void setSkillId(int skillId) { this.skillId = skillId; } public int getVersion() { return this.version; } public void setVersion(int version) { this.version = version; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }

5.5.7 CeraUsergroup Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List;

Project Management and Employee Services Application 55

Page 61: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.ManyToMany; import javax.persistence.FetchType; import javax.persistence.JoinTable; import javax.persistence.JoinColumn; import javax.persistence.Version; @Entity @Table(name="CERA_USERGROUP") public class CeraUsergroup implements Serializable { @Id @Column(name="GROUP_ID") private String groupId; @Version private int version; private String groupname; @ManyToMany(fetch=FetchType.EAGER) @JoinTable(joinColumns = @JoinColumn(name = "GROUP_ID", referencedColumnName = "GROUP_ID"), inverseJoinColumns = @JoinColumn(name = "NAVIGATION_ID", referencedColumnName = "NAVIGATION_ID"), name = "CERA_UGR_NAV") private List<CeraNavigation> navigations = new ArrayList<CeraNavigation>(); private static final long serialVersionUID = 1L; public CeraUsergroup() { super(); } public String getGroupId() { return this.groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public int e sion() { g tVer return this.version; } public void setVersion(int version) { this.version = version; } public String getGroupname() { return this.groupname; } public void setGroupname(String groupname) {

Project Management and Employee Services Application 56

Page 62: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

this.groupname = groupname; } public List<CeraNavigation> getNavigations() { return navigations; } public void setNavigations(List<CeraNavigation> navigations) { this.navigations = navigations; } }

5.5.8 ApplicationResetReceiver Source Code

package com.sap.nwce.ra.edm.ejb.services;

import javax.annotation.Resource;

import javax.ejb.ActivationConfigProperty;

import javax.ejb.EJB;

import javax.ejb.EJBException;

import javax.ejb.MessageDriven;

import javax.ejb.MessageDrivenContext;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;

import javax.jms.JMSException;

import javax.jms.Message;

import javax.jms.MessageListener;

import javax.jms.MessageProducer;

import javax.jms.ObjectMessage;

import javax.jms.Session;

import javax.jms.TemporaryQueue;

import javax.jms.TextMessage;

import com.sap.nwce.ra.edm.util.DataResetResult;

import com.sap.nwce.ra.edm.util.ReferenceApplicationEJBLogger;

/**

* The MessageBean class is a message-driven bean. It implements

Project Management and Employee Services Application 57

Page 63: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

* the javax.jms.MessageListener interface. It is defined as public

* (but not final or abstract).

*/

@MessageDriven(

activationConfig = {

@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),

@ActivationConfigProperty(propertyName = "destination", propertyValue = "appResetQueue"),

@ActivationConfigProperty(propertyName = "connectionFactoryName", propertyValue = "EDMQueueConnectionFactory")

})

public class ApplicationResetReceiverBean implements MessageListener {

@Resource

public MessageDrivenContext mdc;

@EJB private DataResetServiceLocal dataServiceFacade;

@Resource(name="EDMQueueConnectionFactory")

private ConnectionFactory queueConnectionFactory;

/**

* Constructor, which is public and takes no arguments.

*/

public ApplicationResetReceiverBean() {

}

public void setMessageDrivenContext(MessageDrivenContext ctx) throws EJBException{

this.mdc = ctx;

}

/**

* onMessage method, declared as public (but not final or

* static), with a return type of void, and with one argument

* of type javax.jms.Message.

Project Management and Employee Services Application 58

Page 64: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

*

* Casts the incoming Message to a TextMessage and displays

* the text.

*

* @param inMessage the incoming message

*/

public void onMessage(Message inMessage) {

TextMessage msg = null;

DataResetResult dataResetResult;

try {

if (inMessage instanceof TextMessage) {

msg = (TextMessage) inMessage;

ReferenceApplicationEJBLogger.logInfo("MESSAGE BEAN: Message received: " + msg.getText());

if (msg.getText().equals("reset")){

dataResetResult = dataServiceFacade.resetContent();

processNotification((TemporaryQueue) msg.getJMSReplyTo(), dataResetResult);

}else{

ReferenceApplicationEJBLogger.logInfo("MESSAGE BEAN: Message received: " + msg.getText() + " but nothing to do!");

}

} else {

ReferenceApplicationEJBLogger.logInfo("Message of wrong type: " + inMessage.getClass().getName());

}

} catch (JMSException jmsExc) {

ReferenceApplicationEJBLogger.logException(jmsExc);

mdc.setRollbackOnly();

} catch (Throwable te) {

ReferenceApplicationEJBLogger.logThrowable(te);

}

}

private void processNotification(TemporaryQueue queue, DataResetResult result) throws JMSException{

Session jmsSession = null;

MessageProducer queueSender = null;

Project Management and Employee Services Application 59

Page 65: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

Connection connection = null;

try {

connection = queueConnectionFactory.createConnection();

jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

queueSender = jmsSession.createProducer(queue);

ObjectMessage msg = jmsSession.createObjectMessage();

msg.setObject(result);

queueSender.send(msg);

} finally {

if (connection != null) {

connection.close();

}

}

}

}

5.5.9 DataResetService Source Code

/**

*

*/

package com.sap.nwce.ra.edm.ejb.services;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.sql.Connection;

import java.sql.Date;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

Project Management and Employee Services Application 60

Page 66: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

import java.util.Calendar;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import javax.annotation.Resource;

import javax.ejb.EJBException;

import javax.ejb.SessionContext;

import javax.ejb.Stateless;

import javax.ejb.TransactionAttribute;

import javax.ejb.TransactionAttributeType;

import javax.ejb.TransactionManagement;

import javax.ejb.TransactionManagementType;

import javax.sql.DataSource;

import com.sap.nwce.ra.edm.util.DataResetResult;

import com.sap.nwce.ra.edm.util.PackageResolver;

import com.sap.nwce.ra.edm.util.ReferenceApplicationEJBLogger;

@Stateless

@TransactionManagement(value=TransactionManagementType.CONTAINER)

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

public class DataResetServiceBean implements DataResetServiceLocal {

@Resource

public SessionContext sc;

@Resource(name="CE_RA_DS")

private DataSource _dataSource;

private static final String INSERT_SQLFILE = "update_application_data.sql";

private static final String DELETE_SQLFILE = "delete_application_data.sql";

private static final String DATEDETECTPATTERN = "^.*'[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'.*$";

private static final String DATEPATTERN = "'[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'";

private static final int BASEYEAR = 2007;

Project Management and Employee Services Application 61

Page 67: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

private Connection getConnection() throws SQLException {

return _dataSource.getConnection();

}

public void setSessionContext(SessionContext ctx) throws EJBException{

this.sc = ctx;

}

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

@SuppressWarnings("finally")

public DataResetResult resetContent() {

Connection connection = null;

DataResetResult dataresult = new DataResetResult();

try {

connection = this.getConnection();

deleteAllContent(connection);

importContent(connection);

dataresult.setResultStatus(true);

} catch (SQLException sqlExc){

ReferenceApplicationEJBLogger.logException(sqlExc);

dataresult.setResultStatus(false);

dataresult.setErrorMessage(prepearErrorStatement(sqlExc.getMessage()));

sc.setRollbackOnly();

} catch (IOException ioExc) {

ReferenceApplicationEJBLogger.logException(ioExc);

dataresult.setResultStatus(false);

dataresult.setErrorMessage(prepearErrorStatement(ioExc.getMessage()));

sc.setRollbackOnly();

} finally {

try{

connection.close();

}catch (SQLException ioExc){

ReferenceApplicationEJBLogger.logException(ioExc);

Project Management and Employee Services Application 62

Page 68: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

}

return dataresult;

}

}

private void deleteAllContent(Connection connection) throws SQLException, IOException {

Statement statement = connection.createStatement();

final InputStream in = this.getClass().getClassLoader().getResourceAsStream(PackageResolver.resolvePackage(this, DELETE_SQLFILE));

if(in != null) {

BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ));

String line;

while(((line=reader.readLine()) != null)) {

String readedString = line.toString();

if(readedString.toUpperCase().indexOf("DELETE") == 0){

statement.execute(readedString);

}

}

reader.close();

}else{

throw new IOException("The requested delete file is not avaible. Please check name and location");

}

statement.close();

in.close();

}

private void importContent(Connection connection) throws SQLException, IOException {

Calendar c = Calendar.getInstance();

int yearOffset = c.get(Calendar.YEAR)-BASEYEAR;

Statement statement = connection.createStatement();

final InputStream in = this.getClass().getClassLoader().getResourceAsStream(PackageResolver.resolvePackage(this, INSERT_SQLFILE));

Project Management and Employee Services Application 63

Page 69: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

if(in != null) {

BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ));

String line;

while(((line=reader.readLine()) != null)) {

String readedString = line.toString();

if(readedString.toUpperCase().indexOf("INSERT") == 0 || readedString.toUpperCase().indexOf("UPDATE") == 0){

if(Pattern.matches(DATEDETECTPATTERN, readedString)) { // with dates

Object[] parsedStatement = parseForDates(readedString, yearOffset);

PreparedStatement ps = connection.prepareStatement((String)parsedStatement[0]);

for(int i=1; i<parsedStatement.length; i++){

ps.setDate(i, (Date)parsedStatement[i]);

}

ps.execute();

ps.close();

} else { // without dates

statement.execute(readedString);

}

}

}

reader.close();

}else{

throw new IOException("The requested insert/update file is not available. Please check name and location");

}

statement.close();

in.close();

}

private Object[] parseForDates(String readedString, int yearOffset) {

Pattern p = Pattern.compile(DATEPATTERN);

Matcher m = p.matcher(readedString);

StringBuffer sb = new StringBuffer();

Project Management and Employee Services Application 64

Page 70: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

ArrayList<Date> list = new ArrayList<Date>();

while(m.find()){

list.add(parseDate(m.group().replaceAll("'", ""), yearOffset));

m.appendReplacement(sb, "?");

}

m.appendTail(sb);

Object[] result = new Object[list.size()+1];

result[0] = sb.toString();

for(int i=1;i<result.length;i++) {

result[i] = list.get(i-1);

}

return result;

}

private Date parseDate(String pDate, int yearOffset) {

String[] parsed = pDate.split("-");

Calendar c = Calendar.getInstance();

c.set(Calendar.YEAR, Integer.parseInt(parsed[0]) + yearOffset);

c.set(Calendar.MONTH, Integer.parseInt(parsed[1])-1); //month start with 0 for January

c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(parsed[2]));

c.set(Calendar.HOUR_OF_DAY, 0);

c.set(Calendar.MINUTE, 0);

c.set(Calendar.SECOND, 0);

c.set(Calendar.MILLISECOND, 0);

java.sql.Date d = new java.sql.Date(c.getTimeInMillis());

return d;

}

private String prepearErrorStatement(String exceptionMessage){

final StringBuffer errorMessage = new StringBuffer();

errorMessage.append("Error during data reset. Contact your administrator to handle the exception. Error detail message is: \n\r " );

errorMessage.append(exceptionMessage);

return errorMessage.toString();

}

}

Project Management and Employee Services Application 65

Page 71: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

To combine the data, you need to create additional utility class DataResetResult and copy the code from the table bellow. package com.sap.nwce.ra.edm.util; import java.io.Serializable; public class DataResetResult implements Serializable{ /** * added for compiler only */ private static final long serialVersionUID = 1L; private boolean resultStatus; private String errorMessage; public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public boolean isResultStatus() { return resultStatus; } public void setResultStatus(boolean resultStatus) { this.resultStatus = resultStatus; } }

5.5.10 EmployeeManagementService Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.services; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.annotation.Resource; import javax.ejb.Local; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute;

Project Management and Employee Services Application 66

Page 72: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.sap.nwce.ra.edm.ejb.entity.CeraDepartment; import com.sap.nwce.ra.edm.ejb.entity.CeraEmployee; import com.sap.nwce.ra.edm.ejb.entity.CeraNavigation; import com.sap.nwce.ra.edm.ejb.entity.CeraSkill; import com.sap.nwce.ra.edm.ejb.entity.CeraUsergroup; /** * Employee management session facade. provides operations on employees and related objects. */ @Stateless @Local ({EmployeeManagementServiceLocal.class}) @SuppressWarnings("boxing") @TransactionManagement(value=TransactionManagementType.CONTAINER) public class EmployeeManagementServiceBean implements EmployeeManagementServiceLocal { ce @Resour private SessionContext sessionCtx; istenceContext(unitName = "ems/EJB3_EDM_DEMO_PU") @Pers private EntityManager em; /** * Get all employees in a single list. * @return list of all employees */ @SuppressWarnings("unchecked") public List<CeraEmployee> getAllEmployees(){ Query query = em.createNamedQuery("Employee.getAll"); List<CeraEmployee> result = query.getResultList(); return result; } /** * employee by its primary key. Get an * @return employee entity */ public CeraEmployee getEmployeeByID(String pId){ ReferenceApplicationEJBLogger.logInfo("search for employee by Id: " + pId); return em.find(CeraEmployee.class, Integer.valueOf(pId)); } /** * ist of employees with matching lastname. Get a l * @return list of employees */ @SuppressWarnings("unchecked")

Project Management and Employee Services Application 67

Page 73: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public List<CeraEmployee> findEmployeeByNamePart(String pNameFragment) { Query query = em.createNamedQuery("Employee.findByNamePart"); //String parameter = pNameFragment.toLowerCase(); // native datasource variant String parameter = pNameFragment; query.setParameter("namepart", "%"+parameter+"%"); query.setParameter("namepart1", "%"+parameter+"%"); List<CeraEmployee> result = query.getResultList(); return result; } /** * skills. Get all * @return */ essWarnings("unchecked") @Suppr public List<CeraSkill> getAllSkills() { Query query = em.createNamedQuery("Skill.getAll"); st<CeraSkill> result = query.getResultList(); Li return result; } /** * Persist the state of an Employee. * @param pEmployee */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public CeraEmployee saveEmployee(CeraEmployee pEmployee){ ReferenceApplicationEJBLogger.logInfo("persist employee: " + pEmployee.getEmployeeId()); return em.merge(pEmployee); } /** * Persist the state of an Skill. * @param pEmployee */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public CeraSkill saveSkill(CeraSkill pSkill){ ReferenceApplicationEJBLogger.logInfo("persist skill: " + pSkill.getSkillId()); return em.merge(pSkill); } public void removeSkill(CeraSkill pSkill){ em.remove(pSkill); } /** * employee by its login. Get an * @param login of employee * @return Employee or null if no employee was found */ essWarnings("unchecked") @Suppr public CeraEmployee findEmployeeByLogin(String pLogin) { ReferenceApplicationEJBLogger.logInfo("find employee for login name: " + pLogin);

Project Management and Employee Services Application 68

Page 74: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

CeraEmployee result = null; Query query = em.createNamedQuery("Employee.findByLogin"); query.setParameter("login", pLogin); try { result = (CeraEmployee)query.getSingleResult(); } catch (NoResultException e) { ReferenceApplicationEJBLogger.logInfo("No Employee found for login name: " + pLogin); return null; } return result; } /** * Get employee associated with the current user by its login. */ @SuppressWarnings("unchecked") public CeraEmployee findEmployeeByCurrentUserId() { return findEmployeeByLogin(sessionCtx.getCallerPrincipal().getName()); } public CeraSkill getSkillById(String sklId){ return em.find(CeraSkill.class, Integer.parseInt(sklId)); } essWarnings("unchecked") @Suppr public List<CeraSkill> findSkillByName(String pNameFragment){ Query query = em.createNamedQuery("Skill.findByNamePart"); //query.setParameter("namepart", "%"+pNameFragment.toLowerCase()+"%"); query.setParameter("namepart", "%"+pNameFragment+"%"); eraSkill> result = query.getResultList(); List<C return result; } /** * Get all departments. * @return list of departments */ @SuppressWarnings("unchecked") public List<CeraDepartment> getAllDepartments(){ Query query = em.createNamedQuery("Department.getAll"); List<CeraDepartment> result = query.getResultList(); return result; } /** * Get a department by its id. * @param depId * @return */ public CeraDepartment getDepartmentById(String departmentId) { return em.find(CeraDepartment.class, departmentId); } /** * Get the list of all navigations for the employee.

Project Management and Employee Services Application 69

Page 75: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

* @param employee login name to get the allowed navigations for * @return ordered list of navigations, empty if login was unknown */ public List<CeraNavigation> getOrderedNavigations(String pLogin) { CeraEmployee emp = this.findEmployeeByLogin(pLogin); List<CeraNavigation> result = new ArrayList<CeraNavigation>(); if(emp != null) { //if login was found return lsit, otherwise return empty list try { for(CeraUsergroup ug: emp.getGroups()){ for(CeraNavigation nav: ug.getNavigations()){ if(!result.contains(nav)){ result.add(nav); } } } } catch (Exception e) { // unexpected results? ReferenceApplicationEJBLogger.logInfo("getOrderedNavigations unexpected: " + e.getMessage()); } Collections.sort(result, new NavigationComparator()); } return result; } /** * This utility class allows for comparing Navigation entities by their p attributes. osition * @author D042764 */ private class NavigationComparator implements Comparator<CeraNavigation>{ public int compare(CeraNavigation o1, CeraNavigation o2) { return o1.getPosition() - o2.getPosition(); } } /** * e list of UserGroups of an employee. Get th * @param employee id * @return list of UserGroup */ public List<CeraUsergroup> getUserGroupsForEmployee(String pId){ ReferenceApplicationEJBLogger.logInfo("get usergroups for employee id: + pId); " try { CeraEmployee e = em.find(CeraEmployee.class, Integer.valueOf(pId)); if(e!=null) { return e.getGroups(); }

Project Management and Employee Services Application 70

Page 76: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

} catch (Exception e) { // unexpected problems ReferenceApplicationEJBLogger.logInfo("getUserGroupsForEmployee unexpected exception: " + e.getMessage()); ReferenceApplicationEJBLogger.logException(e); } return new ArrayList<CeraUsergroup>(); } }

To combine the code you need to create additinal utility class ReferenceApplicationEJBLogger and copy and paste the code:

/*

* Copyright (c) 2006 SAP AG, Germany. All rights reserved.

* SAP C42 Reference Application. Use is subject to license terms.

*/

package com.sap.nwce.ra.edm.util;

import com.sap.tc.logging.Category;

import com.sap.tc.logging.FileLog;

import com.sap.tc.logging.Location;

import com.sap.tc.logging.Severity;

/**

* Allow logging on the session bean side of the application.

* @author D042764

*/

public class ReferenceApplicationEJBLogger {

private static final Location LOCATION = Location.getLocation("com.sap.nwce.ra.edm");

private static final Category CATEGORY = Category.getCategory(Category.APPLICATIONS, "Reference Application");

static{

LOCATION.setMinimumSeverity(CATEGORY, Severity.INFO);

LOCATION.setMaximumSeverity(CATEGORY, Severity.ALL);

CATEGORY.addLog(new FileLog("./log/application/edmProject.%g.trc"));

}

Project Management and Employee Services Application 71

Page 77: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

/**

* log a caught exception.

* @param eMessage

*/

public static void logException (Exception eMessage){

logThrowable(eMessage);

}

/**

* log a caught throwable.

* @param eMessage

*/

public static void logThrowable (Throwable eMessage){

CATEGORY.logThrowableT(Severity.WARNING, LOCATION, eMessage.getMessage(), eMessage);

}

/**

* trace an exception when application remains operable.

* @param logWarning

* @param eMessage

*/

public static void logWarning (String logWarning, Exception eMessage) {

CATEGORY.warningT(LOCATION, logWarning, new Object[]{eMessage});

}

/**

* trace an information.

* @param logString

*/

public static void logInfo (String logString){

CATEGORY.infoT(LOCATION, logString);

}

/**

* trace an information.

* @param logString

*/

Project Management and Employee Services Application 72

Page 78: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public static void logWarn (String logString){

CATEGORY.warningT(LOCATION, logString);

}

}

5.5.11 ProjectChangeReceiver Source Code package com.sap.nwce.ra.edm.ejb.services; import javax.annotation.Resource; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.sap.nwce.ra.edm.ejb.entity.CeraPrjHistory; /** * The MessageBean class is a message-driven bean. It implements * the javax.jms.MessageListener interface. It is defined as public * (but not final or abstract). * */ @MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "prjChangeQueue"), @ActivationConfigProperty(propertyName = "connectionFactoryName", propertyValue = "EDMQueueConnectionFactory") })

Project Management and Employee Services Application 73

Page 79: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

public class ProjectChangeReceiverBean implements MessageListener { @Resource public MessageDrivenContext mdc; @PersistenceContext(unitName = "ems/EJB3_EDM_DEMO_PU") private EntityManager em; /** * Constructor, which is public and takes no arguments. */ public ProjectChangeReceiverBean() { } /** * onMessage method, declared as public (but not final or * static), with a return type of void, and with one argument * of type javax.jms.Message. * * Casts the incoming Message to a TextMessage and displays * the text. * * @param inMessage the incoming message */ public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) {

Project Management and Employee Services Application 74

Page 80: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

msg = (TextMessage) inMessage; CeraPrjHistory chPrj = new CeraPrjHistory(); chPrj.setProjectId(msg.getIntProperty("ProjectId")); chPrj.setEndDate(java.sql.Date.valueOf(msg.getStringProperty("EndDate"))); chPrj.setStartDate(java.sql.Date.valueOf(msg.getStringProperty("StartDate"))); chPrj.setTitle(msg.getStringProperty("Title")); chPrj.setDescription(msg.getStringProperty("Description")); chPrj.setLeader(msg.getIntProperty("LeadId")); chPrj.setChangeDate(new java.sql.Timestamp(msg.getLongProperty("ChangeDate"))); chPrj.setStatus(msg.getIntProperty("Status")); chPrj.setChangerId(msg.getStringProperty("Changer")); em.merge(chPrj); ReferenceApplicationEJBLogger.logInfo("MESSAGE BEAN: Message received: " + chPrj.getProjectId()); } else { ReferenceApplicationEJBLogger.logWarn("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { ReferenceApplicationEJBLogger.logException( e); mdc.setRollbackOnly(); } catch (Throwable te) { ReferenceApplicationEJBLogger.logThrowable( te); } } }

Project Management and Employee Services Application 75

Page 81: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

5.5.12 ProjectChangeSender Source Code

/* * Copyright (c) 2006 SAP AG, Germany. All rights reserved. * SAP C42 Reference Implementation. Use is subject to license terms. */ package com.sap.nwce.ra.edm.ejb.services; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.Local; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import com.sap.nwce.ra.edm.ejb.entity.CeraProject; /** * JMS SenderSession. */ @Stateless @Local ({ProjectChangeSenderLocal.class}) @SuppressWarnings("boxing") @Trans ctiona Management(value = TransactionManagementType.CONTAINER) public class ProjectChangeSenderBean implements ProjectChangeSenderLocal { @Resource(name="EDMQueueConnectionFactory") private ConnectionFactory queueConnectionFactory; @Resource(name="prjChangeQueue") private Queue queue; private Connection queueConnection; public ProjectChangeSenderBean() { } o uct @PostC nstr public void initialize() { try {

Project Management and Employee Services Application 76

Page 82: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

queueConnection = queueConnectionFactory.createConnection(); ueueConnection.start(); q } catch (JMSException jmse) { ReferenceApplicationEJBLogger.logException(jmse); throw new RuntimeException(jmse); } } /** * Creates session, sender, message and send created message */ public void sendMessage(CeraProject pProject, String pCaller) { Session queueSession = null; MessageProducer queueSender = null; try { queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createProducer(queue); TextMessage textMsg = queueSession.createTextMessage(); textMsg.setIntProperty("ProjectId", pProject.getProjectId()); textMsg.setLongProperty("StartDate", pProject.getStartDate().getTime()); textMsg.setLongProperty("EndDate", pProject.getEndDate().getTime()); textMsg.setStringProperty("Title", pProject.getTitle()); textMsg.setStringProperty("Description", pProject.getDescription()); if(pProject.getLeader() != null) { textMsg.setIntProperty("LeadId", pProject.getLeader().getEmployeeId()); } else { textMsg.setIntProperty("LeadId", -1); } textMsg.setLongProperty("ChangeDate", System.currentTimeMillis()); textMsg.setIntProperty("Status", pProject.getStatus()); textMsg.setStringProperty("Changer", pCaller); queueSender.send(textMsg); } catch (JMSException jmse) { ReferenceApplicationEJBLogger.logException(jmse); throw new RuntimeException(jmse); } finally { if (queueSession != null) { try { queueSession.close(); } catch (JMSException jmse) { ReferenceApplicationEJBLogger.logException(jmse); } } } }

Project Management and Employee Services Application 77

Page 83: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

@PreDestroy public void stopSession() { if (queueConnection != null) { try { ueueConnection.close(); q } catch (JMSException jmse) { ReferenceApplicationEJBLogger.logException(jmse); throw new RuntimeException(jmse); } } } }

5.5.13 ProjectManagementService Source Code /** * */ package com.sap.nwce.ra.edm.ejb.services; import java.util.List; import javax.annotation.Resource; import javax.annotation.Resource.AuthenticationType; import javax.ejb.EJB; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.Query; import com.sap.nwce.ra.edm.ejb.entity.CeraProject; /** * @author I039454 * */ @Stateless public class ProjectManagementServiceBean implements ProjectManagementServiceLocal { @PersistenceContext(unitName="ems/EJB3_EDM_DEMO_PU", type=PersistenceContextType.TRANSACTION) private EntityManager em; @Resource(name="resource1", authenticationType=AuthenticationType.CONTAINER, type=Object.class) private SessionContext sessionCtx;

Project Management and Employee Services Application 78

Page 84: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

@EJB(name="JMSSenderSessionLocal", beanName="DefaultBeanName", beanInterface=Object.class) private ProjectChangeSenderLocal jmsSender; /** * Get a project by its id. * @return project entity */ public CeraProject getProjectById(String pId){ return em.find(CeraProject.class, Integer.valueOf(pId)); } /** * Get all projects in a single list. * @return list of all projects */ @SuppressWarnings("unchecked") public List<CeraProject> getAllProjects(){ Query query = em.createNamedQuery("Project.getAll"); List<CeraProject> result = query.getResultList(); return result; } /** * Get all assigned projects. * @return list of all assigned projects */ @SuppressWarnings("unchecked") public List<CeraProject> getAssignedProjects(int pEmployeeId){ Query query = em.createNamedQuery("Project.getAllForEmployee");

Project Management and Employee Services Application 79

Page 85: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

query.setParameter("employeeId", pEmployeeId); List<CeraProject> result = query.getResultList(); return result; } /** * Removes a project. * @param pProject */ public void removeProject(CeraProject pProject){ em.remove(pProject); } /** * Persists a project (create or update) and sends a message to * the projectchangequeue to notify the system that the project * was changed */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public CeraProject createProject(CeraProject pProject){ CeraProject result = em.merge(pProject); String caller = sessionCtx.getCallerPrincipal().getName(); jmsSender.sendMessage(result, caller); return result; } /** * Get a list of projects by its name or description. * @param Name or description fragment

Project Management and Employee Services Application 80

Page 86: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

* @return List of projects */ @SuppressWarnings("unchecked") public List<CeraProject> findProjectByNameOrDescription(String pNameFragment){ Query query = em.createNamedQuery("Project.findByNameOrDescPart"); String parameter = pNameFragment.toLowerCase(); query.setParameter("namepart", "%"+parameter+"%"); query.setParameter("namepart1", "%"+parameter+"%"); List<CeraProject> result = query.getResultList(); return result; } }

5.5.14 Application Users and User Groups The following table shows the list of application users, their log on credentials, and the user group they belong to.

Logon Name User Name User Group

springs Sally Spring Employee

summers Susan Summer Employee

Fallf Franco Fall Project Manager

winterw Walter Winter Employee

hicksm Maria Hicks Employee

dashj John Dash Project Manager

gainsv Viola Gains Department Manager

gordonr Randy Gordon Project Manager

burkep Paul Burke Department Manager

nicolsj John Nicols Employee

millerm Michael Miller Employee

rushj Joanne Rush Employee

bays Sue Bay Project Manager

Project Management and Employee Services Application 81

Page 87: SAP Net Weaver Composition Environment

Rebuilding the Project Management and Employee Services Application March 2007

Reference

fieldj James Field Employee

heckerh Hermann Hecker Employee

platter Rudolf Platte Project Manager

darwind Douglas Darwin Employee

westj Jonathan West Project Manager

smithjo John Smith Project Manager

smithj James Smith Employee

The initial password for all users is welcome123.

The option Reset Application Data resets the application to the state it is, before you deploy it on your server. All users can reset the application data.

The next table shows specific activities for user group member.

User Group Allowed Actions

Department Manager • list projects • list employees • list skills • create projects • create employees • create skills

Project Manager • list projects • list employees • list skills

Employee • list projects

Project Management and Employee Services Application 82