azizkhani.net

I know that I know nothing

Fluent Object Creation

clock January 23, 2013 22:02 by author Administrator
Many posts have been written on this subject (overwhelmingly many) but I just wanted to contribute my two-cents and write a short post about how I use the Fluent Object Creation pattern or object builders in Java to instantiate Value Objects.

 Value Objects are abstractions that are defined by their state (value) rather than their address in memory. Examples of value objects are things like money, a number, a coordinate, etc. They are used not to describe Business Objects but rather descriptions of concrete indivisible entities.  Also, they make great candidates for adding them to collections and maps.


In Java, Value Objects should be declared final and provide no setter methods, basically making it's state immutable after creation, this is a very important requirement. Declaring them final makes them unable to serve as parent objects. This is done by design since value objects should model small and concrete entities. The reason being is that we should be able to create and compare multiple copies of these objects, which is always done by state not by reference. In addition, you should declare proper equals() and hashCode() methods to qualify for a proper value object.

In C++, the same principles apply. In C++ you should make use of the Copy Constructor and overload the assignment and comparison operators.  

The Fluent Object Creation pattern makes value object instantiation elegant and clean. There are many benefits that can be gained by using fluent object creation as we will see shortly. 

 

 

 

The end result of applying this pattern from the API user's perspective will look like the following:

 


Money fiveEuros = new Money.Builder()
   .currency(Currency.EURO)
   .value(5.0L)
   .countryOfOrigin("Spain")
   .type("Coin")
   .reverse("Map of Europe")
   .obverse("Map of Spain")
   .addColor("Bronze")
   .addColor("Silver")
   .year("1880")
.build();


I think you would agree that this pattern flows a lot more smoother as opposed to this:


Money fiveEuros = new Money();
fiveEuros.setCurrency(Currency.EURO);
fiveEuros.setValue(5.0L);
fiveEuros.countryOfOrigin("Spain");
fiveEuros.type("Coin");
fiveEuros.reverse("Map of Europe");
fiveEuros.obverse("Map of Spain");
List<String> colors = new ArrayList<String>();
for(String color: new String[] {"Bronze", "Silver"}) {
   colors.add(color);
}
fiveEuros.setColors(colors);
fiveEuros.setYear("1880");


Which seems broken and has lots of typing and repetition. This is an example of building a pretty big  value object in my opinion, most of tend to be very small.

Before we talk about the benefits of creating objects this way, let's have a look at the structure of this pattern:


public final class Money {
   
      private Long value;
      private String countryOfOrigin;     
      private Currency currency;
      private String type; 
      private String reverse;
      private String obverse;    
      private List<String> colors;
     private Date year;    
 
      private Money() {   }

     // -- getters, hashCode, equals -- //

     // Static inner Builder class
   publicstaticclass Builder {
        private Money _temp = new Money();
 
        public Builder countryOfOrigin(String countryOfOrigin) {
_temp.contryOfOrigin = countryOfOrigin;
         returnthis;
}
 
public Builder currency(Currency c) {
_temp.currency = c;
returnthis;
}
 
public Builder type(String t) {
_temp.type = t;
returnthis;
}
 
public Builder reverse(String r) {
_temp.reverse = r;
returnthis;
}


       public Builder obverse(String o) {
_temp.obverse = o;
return this;
}


public Builder addColor(String c) {
if(_temp.colors == null) {
              _temp.colors = new ArrayList<String>(); 
           }
           _temp.colors.add(c);
return this;
}
 
         public Builder year(String y) {
              if(y == null || y.isEmpty()) {
                  _temp.year = new Date();
              }
              else {
                  _temp.year = DateFormat.parse(y);
              }
return this;
}
 
public Money build() {
                // Validate object
               if(Strings.isNullOrEmpty(_temp.name) || _temp.currency == null) {
                  throw new IllegalArgumentException("Coin currency and value required");
               }
return_temp;
}
    } }


This is also a matter of taste, but I prefer the static inner class approach. I like the canonical nature of referring to the builder as Money.Builder. Also making it static is required since the builder instance needs to live independently of the enclosing class.

I like this pattern because it has the following benefits:

  1. Greater object encapsulation: I can easily enforce object construction using builders by making the Money constructor private (this is just stylistic). This completely hides all of the intricacies of creating this object: list creation, date parsing, etc. From the user's perspective, what we end up with is an object that is simple to instantiate. My illustration is a very simple one, but imagine more complex object graphs.
  2. Code readability: Using this pattern to create objects, makes unit tests and code very easy to read and follow. 
  3. Less typing in the long run: Even though you have to add an extra builder method for every added attributes, the amount of typing you save in the long run makes it worth while. 


Conclusion

Using the fluent creation pattern is more work up front, but the benefits of having it pays off at the end. It makes instantiating objects very elegant and clean. You don't have to use it with Value Objects, most of the benefit of using Fluent Object Creation is when you need to build pretty complex object graphs, but I wanted to show that it can also suit small value objects.

 

 

 

refer:http://www.reflectivethought.net/2013/01/fluent-object-creation.html



Object Associations

clock January 20, 2013 21:37 by author Administrator


 


Composition: the Employee is encapsulated within the Company . There is no way for the outside world to get a reference to the Employee. The Employee is created and destroyed with the company

final class Company{
private final Employee Employee;
{
    Company(EmpDetails details) {
    engine = new Employee(details);
  }
   void assign() {
      emp.work();
   }
}

 

Aggregation: The Company also performs its functions through an Employee, but the Employee is not always an internal part of the Company . Employees can be exchanged, or even completely removed. As the employee is injected, the Employee reference can live outside the Company.

final class Company{
  private Employee engine;
  void addEmployee(Employee emp) {
    this.emp = emp;
  }
  void assign() {
    if (emp != null)
      emp.work();
  }
}

 

Dependency: The company does not hold the employee reference. It receives an employee reference only to the scope an operation. Company is dependent on the Employee object to perform an operation

final class Company{
  void assign(Employee emp) {
    if (emp != null)
      emp.work();
  }
}

Abstraction: Defines the basic operations the implementer should adher to. Employee interface lists the general behavior of an employee

public interface Employee{
 public void work();
 public void off();
 public void quit();
}

Realisation: A class implements the behavior defined by the other other class or interface

public abstract class Engineer implements Employee{
 public void work();
 public void off();
 public void quit();
}

Generalization: A class which is a special form of a parent class

 public class SWEngineer extends Engineer {
 public void work()
 {
  System.out.println('SW Engineer working');
 }
 public void off()
 {
  System.out.println('SW Engineer is off today');
 }
 public void quit()
 {
  System.out.println('SW Engineer is quitting');
 }

}

Association Defines a relationship between classes. Compositon and Aggregation are types of associations
Composition the Employee is encapsulated within the Company . There is no way for the outside world to get a reference to the Employee. The Employee is created and destroyed with the company
Aggregation The Company also performs its functions through an Employee, but the Employee is not always an internal part of the Company . Employees can be exchanged, or even completely removed. As the employee is injected, the Employee reference can live outside the Company.
Dependency The company does not hold the employee reference. It receives an employee reference only to the scope an operation. Company is dependent on the Employee object to perform an operation
Abstraction Defines the basic operations the implementer should adher to. Employee interface lists the general behavior of an employee
Realization A class implements the behavior defined by the other other class or interface
Generalization A class which is a special form of a parent class

UML Relationship Pointers

ref:http://techie-experience.blogspot.gr/2013/01/quick-summary-object-associations.html



Simple Cross Site Scripting (XSS) Servlet Filter

clock January 12, 2013 16:42 by author Administrator

Ran into some issues on some of our Java sites today and needed a quick fix to protect the sites from malicious Cross Site Scripting (XSS) attempts. If you're not aware of what XSS is and have websites that have sensitive user data, you may want to read up, you're probably vulnerable, which means your users are vulnerable. I'm not claiming this is a perfect solution, but it was easy to implement and corrected the vulnerabilities with form and url injection. We basically have a Servlet Filter that's going to intercept every request sent to the web application and then we use an HttpServletRequestWrapper to wrap and override the getParameter methods and clean any potential script injection.


Here's the Filter:

package com.greatwebguy.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class CrossScriptingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void destroy() {
        this.filterConfig = null;
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
    }
}
   

Here's the wrapper:

 

package com.greatwebguy.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public final class RequestWrapper extends HttpServletRequestWrapper {
    public RequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }
    public String[] getParameterValues(String parameter) {
      String[] values = super.getParameterValues(parameter);
      if (values==null)  {
                  return null;
          }
      int count = values.length;
      String[] encodedValues = new String[count];
      for (int i = 0; i < count; i++) {
                 encodedValues[i] = cleanXSS(values[i]);
       }
      return encodedValues;
    }
    public String getParameter(String parameter) {
          String value = super.getParameter(parameter);
          if (value == null) {
                 return null;
                  }
          return cleanXSS(value);
    }
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(value);
    }
    private String cleanXSS(String value) {
                //You'll need to remove the spaces from the html entities below
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        return value;
    }
}

 

Add this to the top of your web.xml:

<filter>
    <filter-name>XSS</filter-name>
    <display-name>XSS</display-name>
    <description></description>
    <filter-class>com.greatwebguy.filter.CrossScriptingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>XSS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

I'm sure the cleanXSS replacements aren't the most efficient way of doing this, you could replace it StringEscapeUtils.escapeHtml from commons lang to simplify it a little, it's up to you, it all depends on what your site is doing and whether it's going to be a pain having all the html escaped, you could also adjust the url-pattern of the filter to be more specific to your application urls, so that everything under your app isn't running through the filter.

Some things to be aware of with this approach, you'll need to account for what you've encoded or in some cases you'll end up with weird characters in your database and possibly in validation of your input boxes. Some would recommend a more positive validation rather than negative validation and only allow a certain range of characters, it's up to you, but it is something to think about.

 

refrence:http://greatwebguy.com/programming/java/simple-cross-site-scripting-xss-servlet-filter/



Good Developer, Bad Developer

clock January 10, 2013 21:13 by author Administrator
Good developer Bad developer
Good developer is an artist, a craftsman who enjoys the process of creation. Bad developer considers himself as a programmer, responsible for generating lines of code.
Good developer understands the problems of the customers Bad developer understands only the technical problem at hand. Good developer does not define the why, but constantly strives to understand why. He’s responsible for the how, and still sees the big picture. Bad developer is focused on building classes and methods and configuration files, but does not get the big picture.
Good developer understands the complete architecture of the product. Bad developer knows only the components he’s written. Good developer fully understands the technologies that are used within the product. He understands what they are used for, and how they work internally.
Good developer is not afraid of new technologies but embraces them by quickly getting a grip. Bad developer only sticks to what he knows. His immediate reaction to any technical change is negative.
Good developer is constantly learning and improving his skills. Good developer reads technical articles, and finishes several technical books a year. Bad developer does not have time to learn. He’s always too busy with other stuff.
Good developer cares about the product quality. He is also very much concerned with the process quality. Good developer pushes himself to create bug-free code; bad developer leaves it to QA to find bugs to fix.
Good developer develops features which create value for customers. Bad developer completes tasks. Good developer will never claim the requirements are incomplete, and will make sure to fully understand the features he’s working on. Bad developer will wait until the finest details are available. To emphasize: good developer is the CEO of the feature – he’s going to make sure he always has the information needed to accomplish the feature, and in case information is missing he’ll make sure he gets it.
Good developer is not afraid to go into anyone’s code. Bad developer is afraid of others looking into his. Good developer understands that it shouldn’t take more time to write self-explanatory and well-documented code. Bad developer always needs to allocate extra time to document and simplify.
Good developer will never feel his code is good enough, and will always continue to clean and fix. Good developer always strives to create elegant solutions but understands that his job is to deliver value to customers. Bad developer thinks only about the elegance of his code and leave the job of delivering value to others.
   


About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In