Welcome!

Java IoT Authors: Elizabeth White, Pat Romanski, Yeshim Deniz, Liz McMillan, Paul Simmons

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
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smart...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
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, discussed how from store operations and ...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
"We view the cloud not as a specific technology but as a way of doing business and that way of doing business is transforming the way software, infrastructure and services are being delivered to business," explained Matthew Rosen, CEO and Director at Fusion, in this SYS-CON.tv interview at 18th Cloud Expo (http://www.CloudComputingExpo.com), held June 7-9 at the Javits Center in New York City, NY.
The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...