Spring Patterns: Best Practices and Design Strategies Book Review

This is a book review of Pro Java™ EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework

About the Book

Apress describes this book as

Pro Java™ EE Spring Patterns focuses on enterprise patterns, best practices, design strategies, and proven solutions using key Java EE technologies including JSP™, servlets, EJB™, and JMS APIs.

This Java EE patterns resource, catalog, and guide, with it’s patterns and numerous strategies, documents and promotes best practices for these technologies, implemented in a very pragmatic way using the Spring Framework and it’s counters.

The book was written by Dhrubojyoti Kayal. Dhrubojyoti works as a senior consultant with Capgemini Consulting. He has more than five years of experience developing and designing applications and products leveraging Enterprise Java technologies. His areas of interest include the Spring Framework, ORM, SOA, refactoring, prefactoring, and performance engineering.

In this book the author takes us through the process of refactoring a legacy system built without using patterns or the Spring Framework into a shiny new system leveraging Spring and design patterns. Throughout the book he takes us through this practical, real-word example.

Introduction to the MVC Pattern

The first chapter introduces you to the MVC pattern. I think that this book is for a well versed J2EE professional developer, who would probably be familiar with the pattern, so this chapter may have been overkill. However, the basis of this book is to refactor an antiquated web application to use Spring and the Spring MVC, so a clear and thorough understanding of the MVC pattern is necessary. Most readers of this book can probably skip this chapter. On the other hand it is written well enough that it would serve a good resource for any rookie developers that you might be working with who need to learn this pattern.

Patterns

Each chapter of this book takes you through the concepts of a common pattern, describes how the Spring Framework is used to implement that pattern, and then replaces the legacy insurance system code with new spring code. Once you get into the patterns, the book is divided into four major sections. These sections are

This division helps to keep the conversation between the author and the reader focused and also makes it easy to find later when you come back to reference this information.

The Best Part

My favorite part about this book is that it is a patterns book. I like to read books based on patterns more than any other type of book. Patterns books are naturally broken down into small, manageable chunks of information. When written, patterns are usually described using a common, easy to follow template and are small enough to read an entire pattern in one sitting, whether that sitting be while you are eating your lunch or a quick read before hitting the pillow. Because they are written this way, it is easy to read this book very quickly and easy to find what you are looking for when you come back later for specific information. Pattern-based books are great.

I also liked this book because it takes you through all the layers of a real-world system. As developers we all have to work with legacy code. If you don’t your very lucky. Because this is real world it is very easy to follow along with the author and the project and see the benefits of Spring and refactoring to patterns.

Needs Refactoring

It’s a good, well-written book, but there are some things that I think need to be changed.

First, as with any book with code examples, there is some odd code that should be rewritten or removed. For example, there is a business bean that has a DAO injected into it via a setter. However, this bean also contains a getter for that DAO. This is not common practice and, in my opinion, not recommended.

And second, all of the presentation patterns are in a single chapter, and all of the business and integration patterns are in their own chapters. I think each pattern should have had its own chapter. I just prefer the clearer boundaries between patterns and I think it would make finding these patterns later, when I come to reference the book, a little easier.

You Should Read this Book

You should read this book if you are a developer who uses Spring, and especially if you use Spring MVC. This is a great resource and a great way to learn about how Spring utilizes patterns internally to implement its services. Of course it also shows you how to use Spring to add patterns to your current code base. You should read this book if you use an MVC framework that is not Spring MVC and are considering Spring MVC for  your next project or are considering adapting Spring MVC to your current project. While this book deals with more than just the Spring MVC, the entire presentation tier section is based on it.

Or Not…

I do recommend this book to most developers, however you should not read Spring Patterns if you are not well versed with J2EE/JEE and the Spring framework. If you are looking to learn Spring, there are other books that might be more suitable.

Here are some last notes, straight from Apress, about this book:

Table of Contents

Finally, here is the table of contents:

Share

Read HTML with Java – Then 7 Fun Things to do to It

There are several ways to get the HTML content of a URL from Java. There are even more ways to get the HTML using open source java libraries. Last week Lars Vogel shared how to get the HTML using nothing but the SDK.

SDK

final URL url = new URL("http://blog.codehangover.com");
final InputStream inputStream = new InputStreamReader(url);
final BufferedReader reader
             = new BufferedReader(inputStream).openStream();

String line;

while ((line = reader.readLine()) != null) {
   System.out.println(line);
}

reader.close();

Apache Commons HttpClient

You can also use the Apache Commons HttpClient for a slightly easier to use library.

HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://blog.codehangover.com");

try {
 client.executeMethod(method);

 byte[] responseBody = method.getResponseBody();

 System.out.println(new String(responseBody));

} catch (Exception e) {

 e.printStackTrace();

} finally {

 method.releaseConnection();
}





But the real fun comes after you get the HTML. Now you get to work with it.

7 Things to do with HTML Source in Java

1. Extract the Text from the Markup

I worked on a web application that was similar to a feed reader. One of the features that we supported was searching the pages. To do this I needed to extract the text from the markup. I use the CyberNeko HTML Parser for this task.

private String getHtmlFilteredString(Reader reader)
{

  // create element remover filter
  ElementRemover remover;
  remover = new ElementRemover();
  remover.removeElement("script");
  remover.removeElement("link");
  remover.removeElement("style");
  remover.removeElement("CDATA");
  remover.removeElement("<!--");
  remover.removeElement("meta");

  OutputStream stream = new ByteArrayOutputStream();

  try
  {
    String encoding = "ISO-8859-1";
    XMLDocumentFilter writer = new Writer(stream, encoding);

    XMLDocumentFilter[] filters = {remover, writer};

    XMLInputSource source = new XMLInputSource(null, null, null, reader, null);

    XMLParserConfiguration parser = new HTMLConfiguration();
    parser.setProperty("http://cyberneko.org/html/properties/filters", filters);

    parser.parse(source);

  } catch (Exception e) {

    e.printStacktrace();
  }

  String content = stream.toString().trim();

  return content;
}

2. Extract Links

To find all of the links in an HTML fragment, maybe for your own spider, or to extract email addresses, you can use HtmlParser


Collection<String> links = new ArrayList<String>();

try {

  URI uriLink = new URI(url);
  Parser parser = new Parser();
  parser.setInputHTML(htmlBody);
  NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter (LinkTag.class));

  for (int i = 0; i < list.size (); i++){
    LinkTag extracted = (LinkTag)list.elementAt(i);
    String extractedLink = extracted.getLink();
    links.add(extractedLink);
  }

} catch (Exception e) {

  e.printStackTrace();
}

3. Change Links

Using the previous code, instead of calling getLink, you can call setLink to change the href. For example, this might be used by any type of analytics software that needs to track hits.

4. Collect Email Addresses

Using the previous code, before adding the link to the Collection, chech to see if it uses the mailto protocol by calling the boolean method isMailLink()

  for (int i = 0; i < list.size (); i++){

    LinkTag extracted = (LinkTag)list.elementAt(i);

    if (extracted.isMailLink())
    {
      String extractedLink = extracted.getLink();
      links.add(extractedLink);
    }
  }

5. Collect Images

Still using HtmlParser, you can extract images by filtering on the ImageTag.


Collection<String> imageUrls = new ArrayList<String>();

try {

  URI uriLink = new URI(url);
  Parser parser = new Parser();
  parser.setInputHTML(htmlBody);
  NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter (ImageTag.class));

  for (int i = 0; i < list.size (); i++){
    ImageTag extracted = (ImageTag)list.elementAt(i);
    String extractedImageSrc = extracted.getImageUrl();
    imageUrls.add(extractedImageSrc);
  }

} catch (Exception e) {

  e.printStackTrace();
}

6. Add Syntax Highlighting

If you’re going to present the source on screen you have to add syntax highlighting. If you’re displaying on a web page, I would highly recommend using something like SyntaxHighligher, which is what we use on this blog. If you are displaying an a Swing app, you can use a tool called  Syntax which is now several years old.

try {

     ToHTML toHTML = new ToHTML();

     toHTML.setInput(new FileReader("Source.java"));
     toHTML.setOutput(new FileWriter("Source.java.html"));
     toHTML.setMimeType("text/x-java");
     toHTML.setFileExt("java")

     toHTML.writeFullHTML();

 } catch (Exception e){

    e.printStackTrace();
 }

7. Diff Two Sources

Once you get the HTML source of two URLs, or you have an old version of the HTML stored somewhere, you might want a nicely formatted diff output.

Madlep wrote his own method to handle the diff and output the results over on Stackoverflow.com

Given some simple input, his code gives simple output.


String one = "" +
    "<ul>" +
    "  <li>item 1</li>" +
    "  <li>item 2</li>" +
    "</ul>";

String two = "" +
    "<p>This is text</p>" +
    "<ul>" +
    "  <li>item 1</li>" +
    "  <li>item 2</li>" +
    "  <li>item 3</li>" +
    "</ul>";

System.out.println(diffSideBySide(one, two));

Outputs

                     >  <p>This is text</p>
<ul>                    <ul>
 <li>item 1</li>          <li>item 1</li>
 <li>item 2</li>          <li>item 2</li>
                     >    <li>item 3</li>
</ul>                   </ul>

3 More Things to do with the HTML

This list sure feels incomplete at only 7 of a nice even 10 things. What else could you you do with the HTML? Ill pick the top three from the comments and finish this blog post with them.

(read html in java) (java get html source)

I may be available for questions

Share

Getting friendly with Spring, JUnit and EasyMock.

Here are some steps that can get you using Spring, JUnit and EasyMock all together in some Test Driven Development hotness.

Start by adding the following lines to the top of your unit test. Specifying Autowire by name ensures you get the injection you want and will stop those Spring errors that there are more than one of the same type of mock objects in your mock-applicationContext.xml. When you specify the Spring Junit runner you must provide one ore more context configurations with @ContextConfiguration.

MyClassUnitTest.java

...
@Configurable(autowire = Autowire.BY_NAME)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:com/some/domain/someproject/resources/mock-applicationContext.xml"})
public class MyClassUnitTest {
...
     @Autowired private Collaborator mockCollaborator;

     @Before
     public void setup() throws Exception {
     ...
     }

     @After
     public void teardown() throws Exception {
     ...
     }

     @Test
     public void testMyClass() throws Exception {

          //Set your mock behavior here
          ....

          EasyMock.replay(mockCollaborator);

          MyClass myClass = new MyClass(mockCollaborator);
          myClass.run();
          EasyMock.verify(mockCollaborator);

          // Other JUnit assertions
          ...
     }
 }

Then add your mocks to your mock-applicationContext.xml (an applicationContext in your test resources just for providing your unit tests with spring injection dependencies):

mock-applicationContext.xml

...
<bean id="mockCollaborator" name="mockCollaborator" class="org.easymock.EasyMock" factory-method="createStrictMock">
     <constructor-arg value="com.some.domain.someproject.Collaborator"/>
</bean>

<bean id="mockOtherCollaborator" name="mockOtherCollaborator" class="org.easymock.EasyMock" factory-method="createStrictMock">
     <constructor-arg value="com.some.domain.someproject.OtherCollaborator"/>
</bean>
...

Ensure your maven pom has the following test-scoped dependency:

pom.xml

...
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-test</artifactId>
     <version>2.5.6</version>
     <scope>test</scope>
</dependency>
...

Then use your mocks as normal. Make sure you call EasyMock.reset(mock) in your @After teardown() method so that each of your mocks are reset for each test. You can also tell Spring to reset the context after a test if needed with @DirtiesContext.

For official documentation and tutorials check out these links.

Spring

http://www.springsource.org/documentation

JUnit

http://www.junit.org

EasyMock

http://easymock.org/Documentation.html

Share

← Previous PageNext Page →