Welcome!

Java IoT Authors: Pat Romanski, Stackify Blog, Elizabeth White, Liz McMillan, Mamoon Yunus

Related Topics: Java IoT, Recurring Revenue

Java IoT: Blog Feed Post

JDev 11g: Programmatic Contextual Events

The point of the programmatic Contextual Event solution is to move away from a declarative approach

This post is yet another Contextual Event blog description with a slight programmatic twist. It was inspired by Lucas Jellema's OTN forum post on how to raise programmatic Contextual Events, and in addition uses techniques as demonstrated by Pino and Frank described below.

Readers might be interested in a thread on the ADF EMG about the design of Contextual Events in the ADF framework, and the idea of Implicit Contextual Events - The Rise and Rise of Contextual Events (or the birth of Implicit Contextual Events).

In that ADF EMG thread I allude to a near "million blogs" that already describe Contextual Events as supporting collateral for Oracle's documentation. If you're interested in other posts check out Pino Jeddah's or Frank Nimphius's screencasts.

While I certainly find the screencasts informative, for my own documentation purposes this blog lists out the whole set of steps 1 by 1. Once again readers hopefully will find it useful.

The point of the programmatic Contextual Event solution is to move away from a declarative approach which isn't ideal in all cases. In our specific use case we wanted programmatic control over the payloads between the publisher and consumer. In turn as of JDev 11.1.1.2.0 I'm not yet satisfied with the IDE's support for Contextual Events and payloads via the pageDef binding design editor; a code solution provides a level of transparency when coupled with the debugger.

It's worth pointing out from Lucas's OTN forum post this programmatic solution is only a half way house, it still requires an "event" binding in the relating pageDef files, however the event payloads themselves are dynamic and fully configurable in code.

Contextual Event Definitions

For the purposes of this blog entry, I'll be describing the 2 players in the Contextual Event scenario as the "Publisher" and the "Consumer".

The Contextual Event "Publisher" will be a standalone Bounded Task Flow (BTF) comprised of page fragments, that has been JARed as an ADF Library. We'll refer to this as the PublisherBTF. The PublisherBTF will be comprised of a single BTF with a single page fragment "PublisherPageFragment" containing a single button to raise events – very simple.

The Contextual Event "Consumer" will be a master ADF application, or in other words an application that calls the "PublisherBTF" and embeds it in a region within a page. We'll refer to this as the ConsumerMasterApp.

Goal

The goal for this blog is to demonstrate when a button is pressed in the PublisherBTF, a programmatic Contextual Event is raised via the button's ActionListener, with some coded payload, that the event is captured and handled by the ConsumerMasterApp. At the result of this blog, the payload itself is immaterial, it's the technique that's important.

Preparing the PublisherBTF

In this section I describe the setup of the PublisherBTF before we address configuring the solution for Contextual Events. As such I wont go through step by step setup instructions, I assume readers are familiar with the basics described here.

The PublisherBTF is a standard ADF Application, comprised of a Model & ViewController project. In turn the ViewController contains a single BTF "PublisherBTF.xml" containing a single fragment "PublisherPageFragment".


The BTF has only the fragment:


The fragment is comprised of the following code:




As can be seen the button via it's ActionListener refers a JSF bean "publisher" configured as follows:


The PublisherBean's doAction() method is where we'll raise the Contextual Event programmatically as described in the next section. Currently the method does nothing:

package view;

import javax.faces.event.ActionEvent;

public class PublisherBean {
public PublisherBean() {
}

public void doAction(ActionEvent actionEvent) {
// Add event code here...
}
}
Finally the PublisherPageFragment requires a relating pageDef bindings file, created by right clicking the open fragment in the design or editor mode, and selecting Go to Page Definition using the resulting dialog to generate the empty bindings file:


Raising the Contextual Event Programmatically from the PublisherBTF

Our goal is to raise the Contextual Event via the commandButton's doAction method() programmatically. A requirement for the code is that we have an Event binding published in the relating page fragment's pageDef file.

The easiest way to do this is to select the commandButton in the page fragment, then via the Property Inspector locate the subsection entitled Contextual Events, and select the green plus button, opening the Publish Contextual Event dialog:


From here we enter a name "publisherEvent". In the JDev 11.1.1.2.0 and 11.1.1.3.0 releases this dialog appears to have a fault in that it doesn't populate the Type field. Implicitly it should know if we're creating events from commandButtons the Type should be "Action Event" (or "Value Change Event" for fields). This may work in later releases, here I've just entered the text.

The result of this operation is a little hard to see in the pageDef designer. Instead the Structure Windows shows a "eventBinding" containing an "events" binding with one "event" binding called "publisherEvent" are created on your behalf:


For the record the relating pageDef XML code:


Package="view.pageDefs">











Note the ActionListener class in the eventBinding; we'll be raising the event from a commandButton so this configuration is important. In the example above I've also changed the eventBindings id from the default value "eventBinding" to "publisherEventBinding". This will make it easier to understand what's happening in our upcoming programmatic code.

From creating the eventBinding, the actionListener property of the commandButton will have been modified to call the eventBinding directly. We don't want this as we want to programatically raise the event. As such restore the original EL expression to call the PublisherBean's doAction method:

At this point this establishes the bindings required for raising the event. On returning to the PublisherBean's doAction() method, the following custom code demonstrates retrieving the eventBinding, setting up a payload and raising the event programmatically:

package view;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import oracle.adf.model.BindingContext;
import oracle.binding.BindingContainer;
import oracle.jbo.uicli.binding.JUEventBinding;

public class PublisherBean {
public PublisherBean() {
}

public void doAction(ActionEvent actionEvent) {

UIComponent component = actionEvent.getComponent();
Map attributes = component.getAttributes();

attributes.put("someParameter", "A String Value");
attributes.put("anotherParameter", Integer.valueOf(1234));

BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
JUEventBinding eventBinding = (JUEventBinding)bindingContainer.get("publisherEvent");

ActionListener actionListener = (ActionListener)eventBinding.getListener();
actionListener.processAction(actionEvent);
}
}
In this code the technique to raise the event and pass a variable payload is:

a) Retrieve the commandButton that raised the actionEvent as an UIComponent
b) Retrieve the UIComponent's attributes
c) Add 2 arbitrary attributes, in this case a String and Integer

This establishes the payload to send. What you send in terms of attribute names and data types is your choice. You could augment this code to fetch data from other value bindings, call Java code, whatever you need to do to get the data.

On completing this we move onto raising the event programmatically:

d) Fetch the page fragment's BindingContainer
e) Retrieve the eventBinding by it's id "publisherEventBinding" – note this maps back to the eventBinding id we changed in the pageDef file
f) Retrieve the eventBinding's ActionListener – this was also configured in the eventBinding in the pageDef file
g) Execute/process the action

This concludes the configuration of the PublisherBTF for raising events.

Preparing the ConsumerMasterApp

Similar to the PublisherBTF, in this section I'll describe the required skeleton of the consuming master ADF application. I'll assume readers are familiar with the basics without describing everything step by step.

The ConsumerMasterApp contains a standard Model/ViewController project setup with a single JSF page in the ViewController called ConsumerPage.jspx.

The PublisherBTF ADF Library JAR will be attached to the ConsumerMasterApp's ViewController project.

The ConsumerPage.jspx will have the PublisherBTF embedded in the page as a region as follows:


xmlns:h="http://java.sun.com/jsf/html" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">








Consuming the Contextual Event Programmatically in the ConsumerMasterApp

To configure the ConsumerPage to receive the event, we need:

a) a binding to receive the event and pass it to the handler method
b) a handler, essentially a Java class method to receive the event from the binding

To do this we create the handler first, then the binding to call the handler, then we back fill the handler's method code to retrieve the data.

To create the Handler, in the ConsumerMasterApp we create a bean ConsumerBean as follows:

package consumer.view;

public class ConsumerBean {

public void handleEvent(Object payload) {
// Add handler code here....
}
}
Note the handleEvent() method we've also added, this will eventually be called via the binding to allow us to programmatically handle the event.

The event binding requires that the handler be exposed as a Data Control. This is done by right clicking the ConsumerBean in the Application Navigator and selecting the Create Data Control option:


From this operation an xml file is created for the relating Data Control, and under the Data Control accordion in the Application Navigator, you will now see the ConsumerBean exposed (if you don't, click the refresh button in the Data Control accordion):


Finally to configure the handler, on the consuming page we create a methodAction binding in the resulting pageDef. This is done by selecting the Bindings and Executables tab, then the green plus button invoking the Insert item dialog where we select methodAction:


In the resulting Create Action Binding dialog, select the ConsumerBean Data Control, then the handleEvent() operation, leaving all else as default:


Selecting ok creates the associated methodAction binding:


Given we now have a handler to receive the event, we configure the ConsumerPage's bindings to subscribe to the PublisherBTF's event. To do this we open the ConsumerPage's pageDef file, selecting the Contextual Events tab, followed by the Subscribes tab and the green plus button. This opens the Subscribe to Contextual Event dialog where we will select the event to subscribe to, and the handler to action the received event:


Selecting the Looking Glass button on the Event field allows us via the resulting Select Contextual Event dialog to select the event "publisherEvent" from the PublisherBTF. Note it's possible to select the event from both the embedded PublisherBTF within the region of the ConsumerPage, or the event from the ADF Library. As the BTF has already been configured in the ConsumerPage, use the former:


On returning to the Subscribe to Contextual Event dialog the Type field will now map to an Action Event. As the "publisherEvent" name might not be unique across all BTFs you consume, you can filter the event by specifically specifying the BTF that raised it via the Publisher poplist:


If you select "Any", by design regardless of the BTF that raises the "publisherEvent", your handler will be called. We'll take the Any option for this simple example.

Next selecting the Handler button, from the Select Handler dialog we can select the handleEvent method we exposed as a methodAction binding:


Returning to the Subscribe to Contextual Event dialog, under the Parameters tab we create the following entry:


What this entry does is map the generic incoming data payload to the parameters of the handler method. Note the Name of the parameter is lowercase "payload" that matches to the ConsumerBean handleEvent() method's input parameter name. The IDE gives you no support in getting this correct, so it's up to you to make them match. In addition note the EL expression "#{payLoad}". Again notice the words are lowercase but there is a capital "L". Again the IDE gives you no support in getting this correct. I had a bit of whine about this in a previous blog post. Note if you get these wrong, the runtime behaviour is the event will still be called, yet no payload will be passed, which is a bit of a pain to debug.

For reference what you'll see in the pageDef designer:


And the resulting pageDef code:


Package="consumer.view.pageDefs">



xmlns="http://xmlns.oracle.com/adf/controller/binding"/>


RequiresUpdateModel="true" Action="invokeMethod" MethodName="handleEvent" IsViewObjectMethod="false">














At this point we've the handler configured, we've subscribed to the event, and on the event being called the handler will be called on our behalf. What's left is for us to add our code to the ConsumerBean handleEvent() method:

package consumer.view;

import javax.faces.component.UIComponent;
import javax.faces.event.ActionEvent;

public class ConsumerBean {

public void handleEvent(Object payload) {

ActionEvent actionEvent = (ActionEvent)payload;
UIComponent component = (UIComponent)actionEvent.getSource();

String someParameter = (String)component.getAttributes().get("someParameter");
Integer anotherParameter = (Integer)component.getAttributes().get("anotherParameter");

// Do something with the data
}
}
Of interest in the code, the payload itself is the actual ActionEvent raised via the PublisherBTF. From the ActionEvent it's possible to grab the UIComponent that raised the event, who in turn carries the data payload via its attributes. Note how we can cast the parameters/attributes back to the source class, which implies we can use sophisticated Java class constructs as parameters if required.

This concludes what needs to be setup. From here in your handleEvent() bean you're free to do whatever you need to with the data, possible write it to a binding, or pass it to another Java method and so on. In turn of course you don't even have to pass a payload, simply raising the event maybe all you require for the consuming application to do something.

Samples

The example PublisherBTF and ConsumerMasterApp ADF applications are available as a single zip. Note the ConsumerMasterApp is dependent on the ADF Library JAR generated via the PublisherBTF. You'll need to generate/deploy your own PublisherBTF ADF Library JAR, then remap the ConsumerMasterApp's ViewController ADF Library mapping to wherever the dependent JAR is located.

Conclusion

What may appear to be a lot of steps for configuring Contextual Events then handling them programmatically, actually becomes second nature after a couple of trials. Basically in the publisher you need to:

1) Create an eventBinding
2) Via a commandButton actionListener grab the eventBinding in code, attach a payload, and execute the event

From the consumer we need to:

1) Create a handler method
2) Publish the handler class as a Data Control
3) Create a methodAction binding for the Data Control
4) Subscribe to the publisher event, mapping the event and its payload to the method and its parameters
5) Returning to handler method, retrieve the parameters via the ActionEvent UIComponent

The benefit of the programmatic approach is you're now free to pass around any data payload with the flexibility of Java code. Without a doubt this doesn't replace the declarative solution to Contextual Events, but it's certainly good to know, and is much easier to debug as there's real code to place breakpoints.

Addendum

This blog entry was written against JDev 11.1.1.2.0.

Read the original blog entry...

More Stories By Chris Muir

Chris Muir, an Oracle ACE Director, senior developer and trainer, and frequent blogger at http://one-size-doesnt-fit-all.blogspot.com, has been hacking away as an Oracle consultant with Australia's SAGE Computing Services for too many years. Taking a pragmatic approach to all things Oracle, Chris has more recently earned battle scars with JDeveloper, Apex, OID and web services, and has some very old war-wounds from a dark and dim past with Forms, Reports and even Designer 100% generation. He is a frequent presenter and contributor to the local Australian Oracle User Group scene, as well as a contributor to international user group magazines such as the IOUG and UKOUG.

@ThingsExpo Stories
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
Consumers increasingly expect their electronic "things" to be connected to smart phones, tablets and the Internet. When that thing happens to be a medical device, the risks and benefits of connectivity must be carefully weighed. Once the decision is made that connecting the device is beneficial, medical device manufacturers must design their products to maintain patient safety and prevent compromised personal health information in the face of cybersecurity threats. In his session at @ThingsExpo...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
SYS-CON Events announced today that MobiDev, a client-oriented software development company, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ayehu provides IT Process Automation & Orchestration solutions for IT and Security professionals to identify and resolve critical incidents and enable rapid containment, eradication, and recovery from cyber security breaches. Ayehu provides customers greater control over IT infrastructure throu...
SYS-CON Events announced today that Elastifile will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...