Welcome!

Java IoT Authors: Yeshim Deniz, Liz McMillan, Stackify Blog, Pat Romanski, Jason Bloomberg

Related Topics: Java IoT, Mobile IoT

Java IoT: Article

Java J2EE Lite with Spring Framework

The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning

We have thus seen how declarative transactions have been introduced without changing application code.

Logging Service
It's sometimes desirable to log entry and exit points in business methods. We will create an advice that will do the logging and then define a pointcut specifying where the advice will need to be applied.

(Note that providing a logging service using Spring is appropriate for entry/exit points from a method, not so much for application-level logs.)

Listing 4 provides the code for LoggedMethodAdvice. As we can see, the LoggedMethodAdvice implements the AOP Alliance interface (http://aopalliance.sourceforge.net/) MethodInteceptor , which only has a single method, invoke (...).

The invocation.proceed () call is surrounded by the "advice" and therefore this advice is called the "around" advice. The actual logging is achieved via the standard log4j calls.

The pointcut is actually a Spring-supplied pointcut called NameMatchMethodPointcut. This pointcut accepts (via IoC) a collection of method names to which the advice needs to be applied. This is shown in listing 5.

The advice (loggedMethodAdvice) and pointcut (loggedMethodPointut) is combined together as the LoggedMethodAdvisor in the orderContext.xml file as shown in Listing 6.

Finally, in the BeanFactory (orderContext.xml file), the loggedMethodAdvisor is attached to the existing transactionProxy (myProxiedServiceWitheSeveralInterceptors) as a pre- Interceptor.

Seeing Logging in Action Using JUnit
The two test methods testLoggingUsingProxiedService() and testLoggingUsingNonProxiedService () can be used to test the Logging service.

Looking at the accompanying log4j file (made2order.log), we see that the proxied method logs statements for the placeOrder(), modifyOrder(), and dropOrder() but not for the showOrder(). The non-proxied method does not log any methods at all.

Auditing Service
This service shows how we can use the proxy mechanism to selectively audit methods that are executed by an external user (in our example). Here too we will be implementing AuditAdvice as a MethodBeforeAdvice. However, for the pointcut, instead of using the out-of-the-box NameMatchMethodPointcut (as in the case of logging), this time we will use an instance of DynamicMethodMatcherPointcut. This pointcut is implemented in the class AuditDynamicPointcut (see Listing 7). It allows us to dynamically match class names, method names, and arguments, in that order. In Listing 7 we see that the AuditDynamicPointcut class accepts a collection of methodNames. These are injected into the pointcut in the beanFactory. First the AuditDynamicPoint examines to see if the class being proxied is assignable from OrderService. If that is true, the next check is to see if the currently executed method's name is in the list of methodNames injected into this proxy. Finally the matches(Method method, Class clazz, Object[] o) method examines the arguments passed to the method and only returns true if the argument passed is false (representing externalUser = true).

We also see that in the orderContext.xml file (see Listing 8), the property methodNames is set to printReport signifying that the pointcut should return a true only if the methodName is printReport as shown in the implementation in Listing 8. The advice is tied to the pointcut resulting in an Advisor as shown in Listing 9.(Listings 9-20 and additional source code can be located when Listing 1 is clicked.)

As a result, this pointcut will apply the auditAdvice to the printReport method of OrderService only if the argument passed to printReport is false. In any other case, the advice will not be applied.

Although in made2order auditing is implemented as log4j output, note that AuditAdvice can be also be implemented by writing to the database, as a part of a separate transaction.

Seeing Auditing in Action Using JUnit
The test suite OrderServiceIntegrationTest's two methods testAuditingUsingProxiedService() and testAuditingUsingNonProxiedService() are executed. Both the methods make calls to the business method printReport(...), passing in an argument of internalUser the first time and an externalUser the second time. We see that:

  • The auditing statement is only logged on the proxied service.
  • The auditing statement is only logged on the proxied service when an externalUser makes that call.
Profiling Service
The profiling of methods is achieved via the ProfilingAdvice class (see Listing 10). Here, for illustration only, the use of a pointcut is avoided, so that every method that has the word "Long" in its name is intercepted. This is not the preferred way of interception as it's slower performing than interception using a pointcut.

Since there is no pointcut associated with this advice, it is directly added to the list of interceptors (without a corresponding advisor) to the TransactionalProxy (see Listing 11). The behavior of this service is similar to the Logging and Auditing service. Further explanation is omitted for the sake of brevity.

Reporting of Exceptions
It's often desirable to track certain exceptions in a production environment via e-mail notification or logging. We will see here how exceptions can be handled declaratively using Spring proxies.

The advice that is needed for this functionality implements the Spring-provided ThrowsAdvice interface. This tag interface requires the implementation of only one method called afterThrowing(...). The last argument to this method is of type Throwable. Hence, different behavior can be implemented for different exceptions as shown in Listing 12.

This advice, like the Profiling Advice, does not have a pointcut associated with it. However, unlike the Profiling Advice where the logic to test the method name existed within the ad-vice, the ThrowsAdvice is applied to any method throwing the mentioned exceptions.

Seeing Reporting of Exceptions in Action Using JUnit
From the test suite, run testProxiedServiceForExceptionReporting(). This method calls the printLongReport(...) method on the proxied orderService with three different arguments. The first two arguments cause the NullPointerException and the IllegalStateException, whereas the last call throws a generic RuntimeException. We see by looking at the log4j output that the ThrowsAdvice is applied in the first two cases but not in the third.

Data Source Switching
Enterprise applications may sometimes write to different databases. In this case the transaction that represents the unit-of-work will require an XA driver that can handle transactions across the different databases. This driver is understandably not as fast-performing as its plainer counterpart which deals with transactions spanning only one type of database.

Made2order illustrates a good solution to this problem by combining the power of IoC and AOP. Using IoC, the orderService is injected with a plain, non-xa data source, but, using AOP, the data source is switched to an xa one for certain methods that are configured declaratively.

First, in the orderContext.xml file, both the xa and non-xa data sources are injected into the XADataSourceAroundAdvice. (Note that the two dataSources are declared elsewhere in the BeanFactory.)

Then, the XADataSourceAroundAdvice is implemented as shown in Listing 14. Note how the dao instance is gotten from the service, then its data source is switched before the invocation and switched back after the invocation.

Next, the xaMethodPointCut is defined as a NameMatchMethodPointcut and two methods, placeOrder(...) and modifyOrder(...), are declared to be targets for the data source switch (see Listing 15). Finally, the advice and pointcut are combined to produce an Advisor as in Listing 16.

Seeing Data Source Switching in Action Using JUnit
In the test suite OrderServiceIntegrationTest, we can execute the method testDataSourceSwapping(). This method invokes the placeOrder(...), modifyOrder(...) and then the dropOrder(...). Looking at the log output, we see that the data source is swapped for the first two methods but not for the last method.

AOP and IoC in Concert
AOP and IoC are a synergetic combination of concepts. Where the BeanFactory provides us with a single point of reference for our service objects and other singleton resources, AOP allows us to elegantly decorate those references with interceptors.

The example of this in the made2order above can be enhanced thus: if at a later time another service's method (PurchasingService.cancelPurchase()) is modified to invoke OrderService.dropOrder(), and each is involved in writing to different databases, then PurchaseService.cancelPurchase() is a good candidate for xa resource swapping, while leaving OrderService.dropOrder() to use the default non-xa resource. That resource swapping can be achieved with the same ease of configuration and elegance as was done with OrderService.placeOrder() by making PurchaseService a Spring managed Bean with advised proxies.

At this point we have applied the infrastructure services of transactions, logging, auditing, profiling, exception monitoring, and data source swapping to our business interface and, at the same time, have not convoluted our business code with references to these services. Also we have shown how we can easily change the infrastructure services to apply (or not apply) to a set of methods via configuration changes to the pointcut parameters in the BeanFactory.

Spring and EJBs
We can now look at EJBs and discuss how EJBs play with Spring technologies. Since providing infrastructure services is the value proposition for both technologies (at least, in part), it would seem that there is an overlap. Let us look a little closer at the runtime services that the EJB container provides:

  • Remoting
  • Clustering
  • Security
  • Caching (in case of entity EJBs)
  • Persistence (in case of entity EJBs)
  • Transactions
Application servers typically bundle all the above infrastructure services in one EJB container. Our applications therefore end up being affected in two major ways:
  1. Applications have to carry the extra baggage of loading up the entire container even if it has to use only some of the services offered.
  2. Business objects are more coarsely designed to accommodate bandwidth limitations that come with EJBs being accessed remotely. (Typically you will not have an EJB for Order and another for LineItem.) Because of the invasive nature of EJBs (business classes have to extend from EJBObject/EJBRemote), you lose out on the possibility of a fine-grained OO design.

More Stories By Pankaj Tandon

Pankaj Tandon is a software engineer at Crowncastle. His interests include object-oriented design and development and architecting the software process using open source technologies. He is a Sun Certified Java developer for the Java 2 platform. He lives in Pittsburgh, PA, plays guitar, and mixes music in his spare time.

Comments (6) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Pankaj Tandon 02/21/06 10:38:18 AM EST

I just realized that if you are here then you have already found the online version of the article.. here is the link to the downloadable artifact then..
http://res.sys-con.com/story/feb06/180377/source.html

Click on "Additional Code II" to get the full webapp+ code.

Pankaj Tandon 02/17/06 05:48:23 PM EST

Hi all,
I have received several emails from folks telling me about this snafu on JDJs part.
The link is there burried somewhere in the JDJ labyrinth.
You can get to it and some performance analysis at:
http://technochord.blogspot.com/2006/02/j2ee-lite-with-spring-framework....

Bob Raker 02/16/06 11:37:12 AM EST

This was a very good article. But, where the hell does one go to download listing 9-20. Thanks.

Rob Moore 02/14/06 12:14:11 PM EST

Is the sample code available?

Thanks,

Rob

SYS-CON Brazil News Desk 02/14/06 09:46:50 AM EST

J2EE applications of late have become weight conscious. The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning: technology driven design! Fortunately a host of lightweight solutions are emerging, such as PicoContainer, Spring Framework, Hivemind, Hibernate, Castor, and Webwork. In this article I'll discuss my experience with the Spring Framework and how it can be used to make a J2EE application more maintainable, testable, and better performing.

SYS-CON India News Desk 02/13/06 02:55:13 PM EST

J2EE applications of late have become weight conscious. The combined burden of EJBs and coarse-grained component design has given the term test driven design a new meaning: technology driven design! Fortunately a host of lightweight solutions are emerging, such as PicoContainer, Spring Framework, Hivemind, Hibernate, Castor, and Webwork. In this article I'll discuss my experience with the Spring Framework and how it can be used to make a J2EE application more maintainable, testable, and better performing.

@ThingsExpo Stories
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.
SYS-CON Events announced today that CAST Software 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. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
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...
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...
SYS-CON Events announced today that Pulzze Systems 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. Pulzze Systems Inc, provides the software product "The Interactor" that uniquely simplifies building IoT, Web and Smart Enterprise Solutions. It is a Silicon Valley startup funded by US government agencies, NSF and DHS to bring innovative solutions to market.
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...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
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...
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
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...
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
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 Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...