Welcome!

Java IoT Authors: Elizabeth White, Pat Romanski, Liz McMillan, Yeshim Deniz, Frank Lupo

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
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, 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. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, 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. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
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 ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion 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. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
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...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, 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. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that TidalScale 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. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...