Build a taskagent on WebSphere Sensor Events 6.2

来源:互联网 发布:我的淘宝免费下载安装 编辑:程序博客网 时间:2024/05/04 10:43

LEARN IBM WebSphere Sensor Events Toolkit (1)

Building an example for handling sensor events with custom payloads

This tutorial describes how to extend the WebSphere® Sensor Events event model to create and handle events with custom payload types using the WebSphere Sensor Events Toolkit in Rational® Application Developer for WebSphere Software.

The example in this tutorial simulates temperature events sent to WebSphere Sensor Events. A custom event payload type is used to transport the temperature data.

This example assumes the following prerequisites have been met:

· WebSphere Sensor Events Toolkit is installed

· WebSphere Sensor Events projects are in the Rational Application Developer for WebSphere Software workspace

· The WebSphere Application Server profile has been created and configured

The tasks in this tutorial include:

· Creating a custom payload

· Creating a WebSphere Sensor Events task agent MDB

· Configuring WebSphere Application Server to handle an event with the custom payload

· Testing the custom payload


I Creating a custom payload

(1)Create an enterprise application project. 

1 In Rational Application Developer for WebSphere Software select File > New > Other > J2EE > Enterprise Application Project and click Next.

o Complete the following tasks in the Enterprise Application Project window.For the project name, enter TemperatureEvent_EAR.

o For the target runtime, select WebSphere Application Server v6.1.

2 Click Finish. Ignore any errors in the project. They are corrected in a later step.

(2)Copy the required JAR files. 

1    In Rational® Application Developer for WebSphere Software select File > New > Other > General > Folder and click Next.

o Complete the following tasks in the Folder windowFor the parent folder, select TemperatureEvent_EAR.

o For the folder name, enter lib.

2 Click Finish.

3 In the Project Explorer view, expand IBM > RFID > premises > api > lib.

o While pressing and holding the Ctrl key, select the following JAR files in the lib folder:Amit3.0Common.jar

o com.ibm.rfid.epcg.core.jar

o com.ibm.rfid.epcg.tds.jar

o ibmrfid_common_utils.jar

o ibmrfid_event_profilerClient.jar

o ibmse_common_util.jar

o ibmse_event_model.jar

o ibmse_event_model_ale_converter.jar

o ibmse_event_model_converter.jar

o ibmse_event_model_uuid.jar

o ibmse_taskagent_runtime.jar

o org.apache.regexp.jar

4 With the JAR files selected, select Edit > Copy.

5 Expand TemperatureEvent_EAR and select the lib folder.

6 With the lib folder selected, select Edit > Paste.

7 Expand the lib folder to verify that the JAR files have been copied.

(3)Create a Java utility project. 

1   In Rational® Application Developer for WebSphere® Software select File > New > Other > J2EE > Utility Project and click Next.

o Complete the following tasks in the Utility Module window.For the project name, enter TemperatureEvent_Java.

o For the EAR project name, select TemperatureEvent_EAR.

2 Click Finish.

(4)Modify the Java utility project's J2EE module dependencies. 

1   In the Project Explorer view, select TemperatureEvent_Java.

2 Select File > Properties > J2EE Module Dependencies.

Select all JAR files.Note: To add a JAR file to the classpath, check the box in front of the JAR file name.

3 Click OK.

(5)Create the custom payload in the Java utility project.

1     In Rational® Application Developer for WebSphere® Software select File > New > Other > Java > Class and click Next.

o Complete the following tasks in the Java Class window.For the source folder, enter TemperatureEvent_Java/src.

o For the package, enter com.temperature.event.payload.

o For the name, enter TemperatureEventPayload.

o For the modifiers, select Public.

o For the superclass, enter com.ibm.sensorevent.model.payload.IBMSensorEventPayload.

2 Click Finish. The source editor for TemperatureEventPayload.java file opens.

package com.temperature.event.payload;

import com.ibm.sensorevent.model.IPayload;

import com.ibm.sensorevent.model.generic.IGenericGroup;

import com.ibm.sensorevent.model.generic.SensorEventException;

import com.ibm.sensorevent.model.payload.IBMSensorEventPayload;

public class TemperatureEventPayload extends IBMSensorEventPayload {

    private static final long serialVersionUID = 1L;

    // Constructor 1

    protected TemperatureEventPayload() throws SensorEventException {

    }

    // Constructor 2

    protected TemperatureEventPayload(String eventType) throws SensorEventException {

        super(eventType);

}

    // Factory method 1

    public static IGenericGroup getInstance() throws SensorEventException {

        return new TemperatureEventPayload();

    }

    

    // Factory method 2

    public static IGenericGroup getInstance(String eventType) throws SensorEventException {

        return new TemperatureEventPayload(eventType);

    }

   // Factory method 3

    public static IGenericGroup getInstance(IPayload sourcePayload) throws SensorEventException {

        TemperatureEventPayload payload = (TemperatureEventPayload) getInstance();

        payload.copyFields(sourcePayload);      

        copyGroup(sourcePayload, payload);

        return payload;

    }

      // Method 1

    public int getTemperature() throws SensorEventException {

        return this.eventGroup.getIntAttributeValue("temperature");

    }

    // Method 2

    public void setTemperature(int t) throws SensorEventException {

        this.eventGroup.addIntAttribute("temperature", t);

    }

    // Method 3

    public long getTime() throws SensorEventException {

        return this.eventGroup.getDateAttributeValueAsLong("time");

    }

    

    // Method 4

    public void setTime(long t) throws SensorEventException {

        this.eventGroup.addDateAttributeAsLong("time", t);

       }   

}

3 Select File > Save All.

4 Select File > Close All.

In this custom payload example:

· Constructor 1 - Creates an empty payload. This constructor is protected to prevent direct access.

· Constructor 2 - Creates a payload with the specified event type

· Factory method 1 - Creates an empty payload

· Factory method 2 - Creates a payload with the specified event type

· Factory method 3 - Creates a payload from the given payload

· Method 1 - Returns the temperature payload attribute

· Method 2 - Sets the temperature payload attribute

· Method 3 - Returns the time payload attribute

· Method 4 - Sets the time payload attribute

Every custom payload must contain the following:

· The same set of constructors

· The same set of factory methods

· Methods to manage the payload's attributes


【NOTE】

1.about the EAR lib contain jars

The required JAR files vary depending upon the type of application you want to create. All JAR files are available in the WebSphere Sensor Events Toolkit in the IBM > RFID > premises > api > lib folder.

To create an application that creates or processes events, the following JAR files are required:

· Amit3.0Common.jar

· com.ibm.rfid.epcg.core.jar

· com.ibm.rfid.epcg.tds.jar

· ibmrfid_common_utils.jar

· ibmrfid_event_profilerClient.jar

· ibmse_common_util.jar

· ibmse_event_model.jar

· ibmse_event_model_ale_converter.jar

· ibmse_event_model_converter.jar

· ibmse_event_model_uuid.jar

· ibmse_taskagent_runtime.jar

· org.apache.regexp.jar

To call a reusable component, the following JAR files are required in addition to the JAR files required for processing events:

· ibmruc_rucimpl_ejbClient.jar

· ibmruc_backendimpl_ejbClient.jar

· ibmruc_common_utils.jar

To create a reusable component, the following JAR files are required in addition to the JAR files required for processing events:

· ibmrfid_epc_commissioningClient.jar

ibmruc_backendimpl_ejbClient.jarNote: This file is optional. It is only required if your Reusable Component will call a back-end implementation.

· ibmruc_common_parent.jar

To create an application that uses the WebSphere Sensor Events API, the following JAR files are required:

· com.ibm.rfid.epcg.core.jar

· com.ibm.rfid.epcg.tds.jar

· ibmrfid_common_utils.jar

· ibmrfid_epc_commissioningClient.jar

· ibmrfid_event_profilerClient.jar

· ibmrfid_premises_api_client.jar

· ibmrfid_premises_api_ejbClient.jar

· ibmrfid_premises_api_ws.jar

· ibmrfid_premises_util.jar

· ibmse_common_util.jar

· ibmse_event_model.jar

· ibmse_event_model_ale_converter.jar

· ibmse_event_model_converter.jar

· ibmse_event_model_uuid.jar

· org.apache.regexp.jar

· Rfid.jar

· xsdbeans.jar

To create an application that uses events and the WebSphere Sensor Events API, copy all the JAR files.

 II Creating a WebSphere Sensor Events task agent MDB

WebSphere® Sensor Events handles events by using task agents. All task agents are message-driven beans (MDBs).

Follow these steps to create a task agent MDB:

(1)Create the EJB project.

1 In Rational® Application Developer for WebSphere® Software select File > New > Other > EJB > EJB Project and click Next.

o Complete the following tasks in the EJB Project window.For the project name, enter TemperatureEvent_EJB.

o For the EAR membership, select Add project to an EAR.

o For the EAR project name, enter TemperatureEvent_EAR.

2 Click Finish.

(2)Modify the EJB project's J2EE module dependencies.

1 In the Project Explorer view, select TemperatureEvent_EJB.

2 Select File > Properties > J2EE Module Dependencies.

Select all JAR files.Note: To add a JAR file to the classpath, check the box in front of the JAR file name.

3 Click OK.

(3)Create the task agent MDB.

1 In Rational® Application Developer for WebSphere® Software, select TemperatureEvent_EJB.

2 Select File > New > Other > EJB > Enterprise Bean and click Next.

o Complete the following tasks in the Enterprise Bean window.Select Message-drive bean.

o For the EJB project, select TemperatureEvent_EJB.

o For the bean name, enter TemperatureEventTaskAgent.

o For the source folder, enter ejbModule.

o For the default package, enter com.temperature.event.mdb.

3 Click Next.

4 In the Message-Driven Bean Type window, select JMS type and click Next.

5 In the Create a JMS Message-Driven Bean window, accept all the defaults and click Next.

6 In the EJB Java Class Details window, enter com.ibm.sensorevent.engine.baseagent.IBMSEAbstractTaskAgent for the bean superclass.

7 Click Next.

8 If the Confirm Enablement window appears, select Always enable activities and don't ask me againand click OK.

9 Close the class diagram editor (default.dnx) when it opens. It will not be used.

10 In the Project Explorer view, expand TemperatureEvent_EJB > ejbModule > com.temperature.event.mdb.

11 Double-click TemperatureEventTaskAgentBean.java to open the source editor There are errors in the generated code which will be corrected in the next step.

package com.temperature.event.mdb;

import com.ibm.sensorevent.model.IPayloadMetaData;

import com.ibm.sensorevent.model.ISensorEvent;

import com.temperature.event.payload.TemperatureEventPayload;

public class TemperatureEventTaskAgentBean 

    extends com.ibm.sensorevent.engine.baseagent.IBMSEAbstractTaskAgent

implements javax.ejb.MessageDrivenBean, javax.jms.MessageListener {

private static final long serialVersionUID = 1L;

private javax.ejb.MessageDrivenContext fMessageDrivenCtx;

// Method 1

    protected void onIBMSensorEvent(ISensorEvent event) {

        try {

            // display the event data

            TemperatureEventPayload payload = (TemperatureEventPayload) event.getPayload();

            int temperature = payload.getTemperature();

            long time = payload.getTime();

            System.out.println("task agent: temperature = " + temperature);

            System.out.println("task agent: time = " + time);

            // add sample data to event metadata

            IPayloadMetaData metadata = event.getPayloadMetaData();

            metadata.addBooleanAttribute("processed", true);

            // forward event to output channels

            this.publishOutbound(event);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

     // Method 2

    public void onMessage(javax.jms.Message msg) {

        super.onMessage(msg);

    }

    public javax.ejb.MessageDrivenContext getMessageDrivenContext() {

        return fMessageDrivenCtx;

    }

    public void setMessageDrivenContext(javax.ejb.MessageDrivenContext ctx) {

        fMessageDrivenCtx = ctx;

}

  public void ejbCreate() {

    }

     public void ejbRemove() {

    }

}

12 Select File > Save All.

13 Select File > Close All.

Example

In this task agent example:

· Method 1 - Overrides method onIBMSensorEvent as defined in IBmSEAbstractTaskAgent. This method handles events delivered to this task agent MDB. In this example

o The payload is retrieved from the event

o The payload attributes are displayed to the console

o Sample data is added to the event's payload metadata

o The event is sent to any registered output channel

· Method 2 - Passes processing of the JMS message to the superclass so that a call is automatically made to onIBMSensorEvent by IBMSEAbstractTaskAgent

· The remaining methods are generated by the EJB wizard

Every task agent MDB must contain the following:

· The onIBMSensorEvent method to handle the event

· The onMessage method to pass processing to the superclass

(4)Modify the EJB deployment descriptor.

1 In the Project Explorer view, expand TemperatureEvent_EJB.

2 Double-click Deployment Descriptor: TemperatureEvent_EJB. The EJB deployment descriptor editor opens.

3 In the Enterprise JavaBeans™ section of the Overview page in the EJB deployment descriptor editor, clickTemperatureEventTaskAgent. The Bean page displays.

4 Scroll in the top right pane to find the Activation Configuration section and click Add.

o Complete the following tasks in the Add Activation Configurations window:For the name, select destinationType.

o For the value, select javax.jms.Topic.

5 Click Finish.

o Scroll to the bottom right pane to find the WebSphere® Bindings section and complete the following tasks:Select JCA Adapter.

o For the ActivationSpec JNDI name, enter eis/TemperatureEventAS.

6 Select File > Save All.

7 Select File > Close All.

III Configuring WebSphere Application Server to handle an event with the custom payload

To instruct WebSphere® Application Server to deliver an event to a task agent MDB, create a WebSphere Application Server topic and activation specification. 

1 Start the configured server in the Rational® Application Developer for WebSphere Software Servers view.

2 Open a Web browser and browse to http://localhost:9060/ibm/console to access the WebSphere Application Server administrative console.

3 Click Log in. A user ID is not required.

4 Select Resources > JMS > Topics.

5 Expand the Scope section and select the Node scope (not Node and Server).

6 Click New.

7 Select Default messaging provider.

8 Click OK.

o Complete the following tasks in the Configuration section.For the Name, enter temperature.event.topic.

o For the JNDI name, enter jms/temperature.event.topic

o For the Topic name, enter ibmse//temperature/event. The two forward slashes (//) between ibmse” and temperature” are required. The syntax for this value is ibmse//event_type.

o For the Bus name, select ibmsensorevent.

o For the Topic space, select ibmse.

9 Click OK.

10 Click Save to complete creating the topic.

11 Select Resources > JMS > Activation specifications.

12 Expand the Scope section and select the Node scope (not Node and Server).

13 Click New.

14 Select Default messaging provider.

15 Click OK.

o Complete the following tasks in the Configuration section.For the Name, enter TemperatureEventAS.

o For the JNDI name, enter eis/TemperatureEventAS.

o For the Destination type, select Topic.

o For the Destination JNDI name, enter jms/temperature.event.topic.

o For the Bus name, select ibmsorevent.

16 Click OK.

17 Click Save to complete creating the activation specification.

Modifying the message selector for the PersistenceAS activation specification

About this task

By default, WebSphere® Sensor Events persistence only handles RFID tag read events and RFID aggreagation tag read events. The set of events handled by persistence is governed the message selector for the PersistenceAS activation specification. When an event is persisted by the WebSphere Sensor Events, you can create custom BIRT reports to display the event information.

Use these steps to modify the message selector for the PersistenceAS activation specification to include the event with the custom payload.

Procedure

1 In the WebSphere Application Server administrative console, select Resources > JMS > Activation specifications > PersistenceAS.

2 For the Message selector, enter ibmse LIKE '%/temperature/event' OR ibmse='RfidInventory/TagReport' OR ibmse='RfidInventory/TagAggregationReport' OR ibmse LIKE '%/report/TagReport' OR ibmse LIKE '%/report/TagAggregationReport'. The syntax to add the event with the custom payload isibmse LIKE 'event_type' with each conditional separated by OR.

3 Click OK.

4 Click Save to complete modifying the PersistenceAS activation specification.

5 Log out of the WebSphere Application Server administrative console.

IV Testing the custom payload

Normally, a Data Capture and Delivery agent creates the event and sends the event XML to WebSphere® Sensor Events. In order to avoid creating a Data Capture and Delivery agent just to test the event with the custom payload, this tutorial creates a servlet to create the event and send the event XML to WebSphere Sensor Events.

Follow these steps to test the custom payload:

(1)Configure WebSphere Sensor Events.

In this test, the task agent MDB publishes an event to all registered output channel events whose WebSphere® Sensor Events event template name matches the events event type.

About this task

In this tutorial the event profile is EDDR and the event type is temperature/event. When sent to WebSphere Sensor Events, this event is published to topic ibmse/EDDR/temperature/event topic. Therefore, the WebSphere Sensor Events event template name must be*/*/temperature/event.

Use these steps to configure WebSphere Sensor Events.

Procedure

1 Make sure the configured WebSphere Application Server profile is running in the Rational® Application Developer for WebSphere Software Servers view.

2 Open a Web browser and browse to http://localhost:9080/ibmrfidadmin to access the WebSphere Sensor Events Administrative Console.

3 In the WebSphere Sensor Events Administrative Console, select Event Processing Configuration > Event Templates.

4 Click New.

o Complete the following tasks in the Create Event Template page:For the Event Template Name, enter */*/temperature/event.

o For the Description, enter Temperature Event Template.

o In the list of Available Channels, select enterprise.out.channel : JMS.

o Click ->.

o Click Create Event Template.

(2)Create the Web project.

1 Restart the server in the Rational® Application Developer for WebSphere® Software Servers view to activate changes made in theWebSphere Application Server administrative console and WebSphere Sensor Events Administrative Console.

2 In Rational Application Developer for WebSphere Software select File > New > Other > Dynamic Web Project and click Next.

o Complete the following tasks in the Dynamic Web Project window.For the project name, enter TemperatureEvent_Web.

o For the EAR Membership, select Add project to an EAR.

o For the EAR Project Name, enter TemperatureEvent_EAR.

3 Click Finish.

4 If prompted to Open Associated Perspective, click No.

5 Close the Web diagram editor (WebDiagram.gph) when it opens. It will not be used.

(3)Modify the Web project's J2EE module dependencies.

Before creating any code, modify the Web project's J2EE module dependencies so that the required JAR files are in the classpath.

About this task

Use these steps to modify the J2EE module dependencies.

Procedure

1 In the Project Explorer view, select TemperatureEvent_Web.

2 Select File > Properties > J2EE Module Dependencies.

Select all JAR files.Note: To add a JAR file to the classpath, check the box in front of the JAR file name.

3 Click OK.

(4)Create the servlet.

About this task

Follow these steps to create the servlet.Procedure

1 In Rational® Application Developer for WebSphere® Software, select TemperatureEvent_Web.

2 Select File > New > Other > Web > Servlet and click Next.

o Complete the following tasks in the Create Servlet window.For the project, select TemperatureEvent_Web.

o For the folder, enter \TemperatureEvent_Web\src.

o For the Java™ package, enter com.temperature.event.web.

o For the class name, enter TemperatureEventServlet.

3 Click Finish. The source editor for TemperatureEventServlet.java opens.

package com.temperature.event.web;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.Random;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.ibm.sensorevent.model.IBMSensorEvent;

import com.ibm.sensorevent.model.ISensorEvent;

import com.ibm.sensorevent.model.converter.XMLConverter;

import com.temperature.event.payload.TemperatureEventPayload;

public class TemperatureEventServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    private static final long serialVersionUID = 1L;

    public TemperatureEventServlet() {

        super();

    }       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);

    }   

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            int temperature = (new Random()).nextInt(100);

            long time = System.currentTimeMillis();

            

            // create the event

            String profile = "EDDR";

            String eventType = "temperature/event";

            TemperatureEventPayload payload = (TemperatureEventPayload) TemperatureEventPayload.getInstance(profile + "/" + eventType);

            payload.setTemperature(temperature);

            payload.setTime(time);

            ISensorEvent event = IBMSensorEvent.getInstance(profile + "/" + eventType, payload);

            event.getHeader().setSourceId("E2");

            // convert to XML

            XMLConverter converter = (XMLConverter) XMLConverter.getInstance();

            String xml = converter.toXMLString(event);

            // send the XML to the Premises Server gateway

            this.sendToGateway(xml);

            // display a result in the browser

            PrintWriter pw = response.getWriter();

            response.setContentType("text/html");

            pw.println("<P>Sample Event Sent</P>");

            pw.println("<P>temperature = " + temperature + "</P>");

            pw.println("<P>time = " + time + "</P>");

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    private void sendToGateway(String xml) throws Exception {

        String urlString = "http://localhost:9080/ibmse/eventpublish";

        URL url = new URL(urlString);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setUseCaches(false);

        connection.setDoInput(true);

        connection.setDoOutput(true);

        connection.connect();

        StringBuffer data = new StringBuffer();     

        data.append("eventxml=" + URLEncoder.encode(xml, "UTF-8"));

        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());

        dos.writeBytes(data.toString());

        dos.flush();

        dos.close();

        // getting the response is required to force the request; 

        // otherwise, it might not even be sent at all

        InputStream is = connection.getInputStream();

        is.close();

    }

}

4 Select File > Save All.

5 Select File > Close All.

Example

In this example:

· Sample data for the temperature and time are generated

· An event with the TemperateEventPayload is created

· The event is converted to XML

· The XML is sent to the WebSphere Sensor Events

· A simple result is displayed in the Web browser to indicate that the event was sent

(5)Run the test.

Before you begin

Restart the WebSphere® Application Server profile.About this task

Use these steps to run and verify the test.

Procedure

1 In the Rational® Application Developer for WebSphere Software Servers view, right-click the configured WebSphere Application Serverprofile.

2 From the menu, select Add and Remove Projects....

3 In the list of available projects, select TemperatureEvent_EAR.

4 Click Add.

5 Click Finish. Wait for the process to complete.

Open a Web browser and browse to http://localhost:9080/TemperatureEvent_Web/TemperatureEventServlet.The Web browser displays the generated temperature and time values. This means the event was sent to WebSphere Sensor Events.

The Rational Application Developer for WebSphere Software console window displays the same generated temperature and time values. This means the event was received by the task agent MDB.

6 Using MQ Explorer, verify that the ENTERPRISE.OUT.Q queue in the IBM®.DC.QM queue manager contains a message. If so, this means that WebSphere Sensor Events is properly configured and that the event was sent to the registered output channels.

7 Using the DB2® Control Center, verify that the SAGE.EVENT table contains a persisted event. This means that the WebSphere Application Server persistence activation specification is properly configured to handle the event.