Java IoT Authors: Elizabeth White, Pat Romanski, Stackify Blog, Yeshim Deniz, Liz McMillan

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..

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:

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?



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
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Artificial intelligence, machine learning, neural networks. We’re in the midst of a wave of excitement around AI such as hasn’t been seen for a few decades. But those previous periods of inflated expectations led to troughs of disappointment. Will this time be different? Most likely. Applications of AI such as predictive analytics are already decreasing costs and improving reliability of industrial machinery. Furthermore, the funding and research going into AI now comes from a wide range of com...
"When we talk about cloud without compromise what we're talking about is that when people think about 'I need the flexibility of the cloud' - it's the ability to create applications and run them in a cloud environment that's far more flexible,” explained Matthew Finnie, CTO of Interoute, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
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 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...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, 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. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Ayehu will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara California. 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 infras...
In this presentation, Striim CTO and founder Steve Wilkes will discuss practical strategies for counteracting fraud and cyberattacks by leveraging real-time streaming analytics. In his session at @ThingsExpo, Steve Wilkes, Founder and Chief Technology Officer at Striim, will provide a detailed look into leveraging streaming data management to correlate events in real time, and identify potential breaches across IoT and non-IoT systems throughout the enterprise. Strategies for processing massive ...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
In his session at Cloud Expo, Alan Winters, an entertainment executive/TV producer turned serial entrepreneur, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to ma...
SYS-CON Events announced today that Enzu will exhibit at SYS-CON's 21st Int\ernational Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enzu’s mission is to be the leading provider of enterprise cloud solutions worldwide. Enzu enables online businesses to use its IT infrastructure to their competitive advantage. By offering a suite of proven hosting and management services, Enzu wants companies to focus on the core of their ...
We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, 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 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 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...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assista...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists looked at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deliver...
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), provided an overview of various initiatives to certify the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldwide re...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
IoT solutions exploit operational data generated by Internet-connected smart “things” for the purpose of gaining operational insight and producing “better outcomes” (for example, create new business models, eliminate unscheduled maintenance, etc.). The explosive proliferation of IoT solutions will result in an exponential growth in the volume of IoT data, precipitating significant Information Governance issues: who owns the IoT data, what are the rights/duties of IoT solutions adopters towards t...