DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Java Decorator Pattern Example

Java Decorator Pattern Example

George Valotas user avatar by
George Valotas
·
Sep. 26, 11 · Interview
Like (0)
Save
Tweet
Share
13.89K Views

Join the DZone community and get the full member experience.

Join For Free

I cannot say that I am good at explaining theory. I just read it and try to apply it where possible! After all practice and theory are theoretically exactly the same! So If you are intrested in theory, I think that this article at Wikipedia can explain pretty well what it is all about. But if you are like me I do not know if you will remember what exactly is and where to use something, if you haven't used it at least once!

A real example using the Decorator pattern

The funny thing is that I've been using this pattern a lot (even if I did not initially realize it) and I'm pretty sure that many of you have. Where? Within every web application that uses a servlet directly. The scenario is that I want to make sure that when I use the getRemoteAddr() of a request I should always first check if there is an X-Forwarded-For header within the request and if so use that ip address. The solution is a custom HttpServletRequest. The servlet api gives us the tool so we can avoid writing a lot of boilerplate code which is called HttpServletRequestWrapper. The class should look like the one below.

public class XFFAwareReq extends HttpServletRequestWrapper {
  
  public XFFAwareReq(HttpServletRequest request) {
    super(request);
  }

  @Override
  public String getRemoteAddr() {
    String xff = getXForwardedFor();
    return xff != null ? xff : super.getRemoteAddr();
  }

  public String getXForwardedFor() {
    String xff = getHeader("X-Forwarded-For");
    if (xff == null || "".equals(xff)) return null;
    return getIpFromXFF(xff);
  }

  protected static final String getIpFromXFF(String xff) {
   //extract and return the ip from the X-Forwarded-For header
  }
}

If you are also intrested in how to actually use it,that is with a Servlet filter:

public class HttpServletRequestDecoratorFilter implements Filter {
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    //do nothing
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    request = decorate(request);
    chain.doFilter(request, response);
  }

  private ServletRequest decorate(ServletRequest request) {
    try {
      HttpServletRequest req = (HttpServletRequest) request;
      return new XFFAwareReq(req);
    }
    catch (ClassCastException e) {
      // As we are not able to cast the request to an Http one, we just return the same object
      return request;
    }
  }

  @Override
  public void destroy() {
    // Do nothing
  }
}

Cool, but where is the power of decoration? We just wrapped a class providing some more logic to it. Well, the other day you have the request to prevent your site from xss attacks. A way to do that is to filter the request parameters and strip or escape bad characters or group of characters. Of cource we can just add some functionality to our existing class (XFFAwareRequest) and also rename it to reflect the new functionality added. This solution thought breaks the principle of separation of concerns. What do we do then? Easy, create another decorator to provide the new functionality (and only that) overriding the getParameter method and replacing or removing the bad stuff.

public class XSSAwareReq extends HttpServletRequestWrapper {

  protected XSSAwareReq(HttpServletRequest req) {
    super(req);
  }

  @Override
  public String getParameter(String name) {
    return super.getParameter(name)
      .replaceAll("<", "<")
      .replaceAll(">", ">")
      .replaceAll("\\(", "(")
      .replaceAll("\\)", ")")
      .replaceAll("'", "'")
      .replaceAll("eval\\((.*)\\)", "")
      .replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"")
      .replaceAll("script", "");
  }
}

Then all you have to do is to decorate the first HttpServletRequest a little bit more, which is as easy as adding the line req = new XSSAwaareReq(req) before the return new XFFAwareReq(req); one letting the XFFAwareRequest untouchable and not breaking for example existing tests! Now you know that you've used the decorator pattern in your web apps!

From: http://blog.valotas.com/2011/09/java-decorator-pattern-example.html
Decorator pattern Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Power of Docker Images: A Comprehensive Guide to Building From Scratch
  • Building a RESTful API With AWS Lambda and Express
  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Keep Your Application Secrets Secret

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: