<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>@InitBinder &#187; design patterns</title>
	<atom:link href="http://initbinder.com/categories/java/design-patterns/feed" rel="self" type="application/rss+xml" />
	<link>http://initbinder.com</link>
	<description>My thoughts, notes and ideas as a passionate software engineer</description>
	<lastBuildDate>Sat, 24 Mar 2012 13:29:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Is TDD Only for &#8230; Junior Developers??</title>
		<link>http://initbinder.com/articles/is-tdd-only-for-junior-developers.html</link>
		<comments>http://initbinder.com/articles/is-tdd-only-for-junior-developers.html#comments</comments>
		<pubDate>Sun, 24 Apr 2011 03:05:45 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[best practices]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=1027</guid>
		<description><![CDATA[Just before the Easter holidays, I had a discussion with two senior developers from my project about TDD. These guys are experienced software engineers that have been around for some time: they have 11 and 20 years of experience in &#8230; <a href="http://initbinder.com/articles/is-tdd-only-for-junior-developers.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Just before the Easter holidays, I had a discussion with two senior developers from my project about TDD. These guys are experienced software engineers that have been around for some time: they have 11 and 20 years of experience in software development under their belts.</p>
<p>I don&#8217;t claim to be an advocate for TDD. Currently, I do not practice it (yet), but I do recognize and appreciate its importance. TDD really &#8220;forces&#8221; you to have clear understanding about the business requirements to be implemented. You cant implement what you do not understand, right? Because you have to write the test first, your code becomes more solid, less bug prune and you have better test coverage.</p>
<p>Sure, writing the test first its an interesting concept: You start writing a test, and you discoverer that you need a class, and possibly a function. You create the class, function and keep writing the test. Basically, you write few lines of test, and few lines of code, few more lines of test and few more lines of code etc. etc.</p>
<p>Ok, I think I diverted a bit, back to the topic <img src='http://initbinder.com/bunker/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  The discussion took an interesting turn, and I still keep thinking about it. My question to them was &#8211; what do you think about TDD? The responses I received totally surprised me.</p>
<p>One of the claims supported by them, was that TDD does not serve much purpose, and a developer will end up re-factoring the unit tests eventually anyway as a result of re-factoring the concrete classes as the development goes on. So if latter is the case, my colleagues argued that there is no point writing unit tests first. Its better to finish writing concrete class, before attempting to write any unit tests.</p>
<p>Also, one of the developers claimed that many books and articles written on TDD discuss examples that are quite simple to implement, and in reality it is quite difficult to use TDD for complex business scenarios.</p>
<p>Another claim was that TDD should be used to teach junior developers the importance of unit testing, the experienced developers don&#8217;t really need to use it. The developers should follow KISS principles instead.</p>
<p>I respected their opinions about it, but it seemed fundamentally wrong to me that such experienced developers claim that TDD is basically overrated. The feeling that I got from them was that a lot of developers and software engineers in IT industry really got it wrong.</p>
<p>It got me wondering how, after more than ten years of experience in the industry, one does not appreciate one of the best software engineering practices around &#8230;</p>
<p>Offcourse, having said all that, I must point out that TDD is not suitable for every case. TDD can be effective only when it is clear what need to be implemented and there is a deep understanding of requirements.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/is-tdd-only-for-junior-developers.html/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How To Define a Spring Bean With Generics Parameter</title>
		<link>http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html</link>
		<comments>http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html#comments</comments>
		<pubDate>Tue, 15 Mar 2011 18:00:39 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=882</guid>
		<description><![CDATA[At the time when this article was written, the Spring framework does not allow to define beans in application context xml file using parameterized classes. The reason for that is that generics parameters are compiler information, and not run-time. Compiler &#8230; <a href="http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At the time when this article was written, the Spring framework does not allow to define beans in application context xml file using parameterized classes. The reason for that is that generics parameters are compiler information, and not run-time. Compiler information is something that Spring does not care about. For example, the following (or something similar) will NOT work:</p>
<p>[java]<br />
&lt;bean id=&quot;someClass&quot; class=&quot;asia.javabeans.SomeClass&lt;asia.javabeans.Blah&gt;&quot;  /&gt;<br />
[/java]</p>
<p>Sometimes, this restriction can create a problem if you have a parameterized class that has to be loaded by Spring. As a workaround, create an empty child class that extends your  parameterized class, and then use that class&#8217;s canonical name as your bean definition. Consider the following  parameterized parent and the extending child classes:</p>
<p>[java]<br />
public class SomeParent&lt;Blah&gt; {</p>
<p>}</p>
<p>public class Child extends SomeParent&lt;Blah&gt; {<br />
   // Just an empty class<br />
}<br />
[/java]</p>
<p>and your Spring definition can now look like this:</p>
<p>[java]<br />
&lt;bean id=&quot;childClass&quot; class=&quot;asia.javabeans.Child&quot; /&gt;<br />
[/java]</p>
<p>The down side here is that you get stuck with an empty class, but at least you can have your bean definition in your application context xml file.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/how-to-define-spring-bean-with-a-generic-parameter.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inheritance and Generics with Abstract Data Types</title>
		<link>http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html</link>
		<comments>http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html#comments</comments>
		<pubDate>Tue, 15 Mar 2011 06:20:01 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[abstract generics]]></category>
		<category><![CDATA[design concepts]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[inheritance]]></category>

		<guid isPermaLink="false">http://javabeans.asia/?p=873</guid>
		<description><![CDATA[In this article, I want to demonstrate a simple inheritance example that uses generics.  The abstract parent class is generic in the type, and it defines an abstract method that accepts as a method parameter the generic data type. The &#8230; <a href="http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this article, I want to demonstrate a simple inheritance example that uses generics.  The abstract parent class is generic in the type, and it defines an abstract method that accepts as a method parameter the generic data type.</p>
<p>The generic data type used by the extending child in the implementation of the abstract method. This example is going to discuss the benefit of this approach.</p>
<p>Consider the following parent class:</p>
<p>[java]<br />
public abstract class Parent&lt;T&gt; {<br />
    protected abstract void process(T data);<br />
}<br />
[/java]</p>
<p>Consider the following two child classes that extend the parent:</p>
<p>[java]<br />
public class Child extends Parent&lt;SomeClass&gt; {<br />
    @Override<br />
    public void process(SomeClass data) {<br />
        // Do stuff<br />
    }<br />
}<br />
[/java]</p>
<p>[java]<br />
public class AnotherChild extends Parent&lt;OtherClass&gt; {<br />
    @Override<br />
    public void process(OtherClass data) {<br />
        // Do stuff<br />
    }<br />
}<br />
[/java]</p>
<p>You can clearly see how this approach creates flexibility when multiple child classes require different data type parameters when implementing the abstract method. Because of the generic type setting in the abstract method, any data type can be passed to the child. This approach can be particularly useful when implementing a strategy design pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/inheritance-and-generics-with-abstract-data-types.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Brainteaser: Overridable methods</title>
		<link>http://initbinder.com/articles/brainteaser_overridable_methods.html</link>
		<comments>http://initbinder.com/articles/brainteaser_overridable_methods.html#comments</comments>
		<pubDate>Sat, 18 Apr 2009 02:02:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[brainteaser]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[overridable methods]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2009/04/18/brainteaser_overridable_methods.html</guid>
		<description><![CDATA[Consider the following case of inheritance: [java] public class Parent { public Parent() { getValue(); } public void getValue() { } } public class Child extends Parent { private final Integer integer; public Child() { integer = new Integer(888); } &#8230; <a href="http://initbinder.com/articles/brainteaser_overridable_methods.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Consider the following case of inheritance:</p>
<p>[java]<br />
public class  Parent {<br />
   public Parent()  {<br />
	getValue();<br />
   }<br />
   public void getValue()  {</p>
<p>   }<br />
}</p>
<p>public class  Child extends Parent {<br />
   private final Integer integer;<br />
   public Child()  {<br />
	integer = new Integer(888);<br />
   }</p>
<p>   @Override<br />
   public void getValue()  {<br />
	System.out.println(integer);<br />
   }<br />
}<br />
[/java]</p>
<p>Question: What would the following program print, why?</p>
<p>[java]<br />
public class  Test {<br />
   public static void main(String[] args)  {<br />
	Child child = new Child();<br />
	child.getValue();<br />
   }<br />
}<br />
[/java]</p>
<p>Lets assume that getValue() implementation in Child class was changed to:</p>
<p>[java]<br />
@Override<br />
public void getValue()  {<br />
     System.out.println(integer.toString());<br />
}<br />
[/java]</p>
<p><strong>Question</strong>: What would the output of the Test class be now, why?</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/brainteaser_overridable_methods.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Brainteaser: Broken Case of Inheritance</title>
		<link>http://initbinder.com/articles/brainteaser_broken_case_of_inheritance.html</link>
		<comments>http://initbinder.com/articles/brainteaser_broken_case_of_inheritance.html#comments</comments>
		<pubDate>Sun, 05 Apr 2009 10:34:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[brainteaser]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2009/04/05/brainteaser_broken_case_of_inheritance.html</guid>
		<description><![CDATA[Consider the following case of inheritance: [java] public class ExtendingHashSet&#60;E&#62; extends HashSet&#60;E&#62; { private int counter = 0; public ExtendingHashSet() { } @Override public boolean add(E e) { counter++; return super.add(e); } @Override public boolean addAll(Collection&#38;lt;? extends E&#38;gt; c) { &#8230; <a href="http://initbinder.com/articles/brainteaser_broken_case_of_inheritance.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Consider the following case of inheritance:</p>
<p>[java]<br />
public class ExtendingHashSet&lt;E&gt; extends HashSet&lt;E&gt;  {<br />
   private int counter = 0;</p>
<p>   public ExtendingHashSet() {</p>
<p>   }</p>
<p>   @Override<br />
   public boolean add(E e)  {<br />
      counter++;<br />
      return super.add(e);<br />
   }</p>
<p>   @Override<br />
   public boolean addAll(Collection&amp;lt;? extends E&amp;gt; c)  {<br />
      counter += c.size();<br />
      return super.addAll(c);<br />
   }</p>
<p>   public int getCounter()  {<br />
      return counter;<br />
   }<br />
}<br />
[/java]</p>
<p>Created instance:</p>
<p>[java]<br />
ExtendingHashSet&lt;String&gt; s = new ExtendingHashSet&lt;String&gt;();<br />
s.addAll(Arrays.asList(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;));<br />
[/java]</p>
<p><strong>Question</strong>: What value would <em>s.getCounter()</em> method return at this point and why?</p>
<p>Looking forward for your answers dear readers</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/brainteaser_broken_case_of_inheritance.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Prevent iFrame Breakaway</title>
		<link>http://initbinder.com/articles/how_to_prevent_iframe_breakaway.html</link>
		<comments>http://initbinder.com/articles/how_to_prevent_iframe_breakaway.html#comments</comments>
		<pubDate>Sun, 29 Mar 2009 06:37:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[iframe breakaway]]></category>
		<category><![CDATA[iframe breakout]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2009/03/29/how_to_prevent_iframe_breakaway.html</guid>
		<description><![CDATA[Few days ago I was searching for a solution to the problem I&#8217;ve encountered &#8211; I needed to prevent a third party page to break out of iframe inside a web page of my web application. For people who are &#8230; <a href="http://initbinder.com/articles/how_to_prevent_iframe_breakaway.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Few days ago I was searching for a solution to the problem I&#8217;ve encountered &#8211; I needed to prevent a third party page to break out of iframe inside a web page of my web application. For people who are not closely familiar with JavaScript, the following JS snippet will make it more clear how page can break out of iframe:</p>
<p>[java]<br />
if (top.location.href != self.location.href)  {<br />
    top.location.href = self.location.href;<br />
}<br />
[/java]</p>
<p>If the current page is not the parent window &#8211; become the parent window.</p>
<p>I needed to implement something on my end, that would block or prevent the above script or similar to it from executing. I&#8217;ve spent several hours browsing the Net, talking to people on IRC and simply playing trial and error.</p>
<p>After some time, I understood that I wont be able to find a solution to my problem, simply because there is none unfortunately. But, having said that, I have some findings to share:</p>
<ol>
<li>There is iframe <em>security </em>attribute which only works on IE. Setting this attribute to security=&#8221;restricted&#8221;, will prevent iframe to break out. Its always &#8220;nice&#8221; to see that MS have few tricks up their sleeve <img src='http://initbinder.com/bunker/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Also, on one of the forums, someone mentioned that the same attribute will work under Opera as well as under IE. I personally haven&#8217;t tested it my self under Opera, I can just say that it works for IE and not FF.</li>
<li>To make use of <em>window.onbeforeunload</em> event and prompt user with a dialog that requires user&#8217;s input if he agrees to navigate away from the current page. If user disagrees (clicks &#8220;cancel&#8221;), he will remain on the current page. So here in a sense iframe breakaway was canceled. By the way, there is no way to suppress the dialog prompt and make event from clicking &#8220;cancel&#8221; default.</li>
<li>To grab the content of third party page using <a title="http://au.php.net/curl" href="http://au.php.net/curl" target="_blank">PHP Curl</a> lib and to create your own placeholder page for that content. Then the placeholder page can be put inside iframe. The page or the grabbed content will not attempt to breakout, but any request submitted to the placeholder page (hyper link or button click on the grabbed content) will cause page to unload.</li>
</ol>
<p>Also, while researching, I came across this <a title="Preventing Frame Busting and Click Jacking (UI Redressing)" href="http://coderrr.wordpress.com/2009/02/13/preventing-frame-busting-and-click-jacking-ui-redressing/" target="_blank">post</a> that talks about preventing iframe breakaway and click jacking with the help of 204 header response code.</p>
<p>After all that, my conclusion is:<br />
If the page inside iframe is not yours, in other words it is a page hosted under another domain, its not possible actually to stop a page from unloading. Having something like that,  would allow malicious sites to &#8220;trap&#8221; a user indefinitely.</p>
<p>I would love to hear any other suggestions regarding iframe breakout you may have dear readers.</p>
<p>Cheers</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/how_to_prevent_iframe_breakaway.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java and Those Frameworks</title>
		<link>http://initbinder.com/articles/java_and_those_frameworks.html</link>
		<comments>http://initbinder.com/articles/java_and_those_frameworks.html#comments</comments>
		<pubDate>Sat, 15 Nov 2008 09:14:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[design concepts]]></category>
		<category><![CDATA[frameworks]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2008/11/15/java_and_those_frameworks.html</guid>
		<description><![CDATA[I came across an interesting article that discusses today&#8217;s application developers making extensive use of different frameworks in their applications. This is the writer&#8217;s opinion: &#8230;Todays projects are over bloated from the use of frameworks that dont really produce a &#8230; <a href="http://initbinder.com/articles/java_and_those_frameworks.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I came across an interesting <a href="http://it-tactics.blogspot.com/2008/11/simple-it.html" target="_blank">article</a> that discusses today&#8217;s application developers making extensive use of different frameworks in their applications.</p>
<p>This is the writer&#8217;s opinion:</p>
<blockquote><p>&#8230;Todays projects are over bloated from the use of frameworks that dont really produce a real benefit. Developers spend around 75% of their time just on set up and configuration&#8230;</p></blockquote>
<p>The question I would like to ask you dear readers:<em><br />
Do todays application developers really exaggerate the use of frameworks?</em></p>
<p>I think it would be a difficult question to answer. First some clarification is needed &#8211; what is exaggeration really? The number of frameworks used or the reduced performance as a result of use of these framework? Or the amount of time developer spends on  installation and configuration?</p>
<p>I think first as a developer, one must understand the pros and cons of the framework, and how will it affect the performance of the application to be designed. The developer must have clear idea about what is he trying to achieve by using a particular framework in his application, and whether the framework is going to give him the desired result.</p>
<p>As a developer, when designing an application, one may ask questions which framework should be used depending on application&#8217;s requirements. Often the will not be just one framework choice, but several frameworks.</p>
<p>Of course not every developer may face the same situation mentioned above. Proprietary developers rely on leading market software vendors to provide the necessary solutions in one big product bundle.</p>
<p>One has to take several things into account such as future enhancements and possible requirements changes by the client. Using several frameworks to support an application may be look exaggerated at start, but on the long run it may turn out as a better decision. The time spent at the start on initial framework configuration will be paid off during further implementation and maintenance.</p>
<p>In conclusion, I think the ability to know which framework to put for use and when, can come only with experience.</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/java_and_those_frameworks.html/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Brainteaser: Broken Comparator</title>
		<link>http://initbinder.com/articles/brainteaser_broken_comparator.html</link>
		<comments>http://initbinder.com/articles/brainteaser_broken_comparator.html#comments</comments>
		<pubDate>Sat, 18 Oct 2008 14:25:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[brainteaser]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[comparator]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2008/10/19/brainteaser_broken_comparator.html</guid>
		<description><![CDATA[Question: The following program returns result &#8220;1&#8243;, which indicates that first Integer value is greater than the second, why? [java] import java.util.*; public class Example { public static void main(String[] args) { System.out.println(&#38;amp;quot;Result: &#38;amp;quot; + naturalOrder.compare(new Integer(90), new Integer(90))); } &#8230; <a href="http://initbinder.com/articles/brainteaser_broken_comparator.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong>Question</strong>: The following program returns result &#8220;1&#8243;, which indicates that first Integer value is greater than the second, why?</p>
<p>[java]<br />
import java.util.*;</p>
<p>public class Example  {</p>
<p>   public static void main(String[] args)  {<br />
      System.out.println(&amp;amp;quot;Result: &amp;amp;quot; +<br />
	   naturalOrder.compare(new Integer(90),<br />
				new Integer(90)));<br />
   }</p>
<p>private static Comparator&amp;amp;lt;Integer&amp;amp;gt; naturalOrder =<br />
				new Comparator&amp;amp;lt;Integer&amp;amp;gt;()  {<br />
   public int compare(Integer first, Integer second)  {<br />
	return first &amp;amp;lt; second ? -1 : (first == second ? 0 :1);<br />
   }<br />
  };<br />
}</p>
<p>[/java]</p>
<p>Please note:<br />
In this case, comparator for natural order on Integer is written for example only, and in practice there is no need to write it.</p>
<p>Looking forward for your answers dear readers</p>
<p>Resources:<br />
<span class="removed_link" title="http://www.oracle.com/publications">Effective Java</span></p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/brainteaser_broken_comparator.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hack any Java class using reflection attack</title>
		<link>http://initbinder.com/articles/hack_any_java_class_using_reflection_attack.html</link>
		<comments>http://initbinder.com/articles/hack_any_java_class_using_reflection_attack.html#comments</comments>
		<pubDate>Mon, 13 Oct 2008 02:05:20 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[reflection attack]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2008/10/13/hack_any_java_class_using_reflection_attack.html</guid>
		<description><![CDATA[Have you ever thought how secure your application is? Well reflection attack can demonstrate how vulnerable Java classes are. In this post, I will try to apply reflection attack on a simple Java class to demonstrate vulnerabilities and what can &#8230; <a href="http://initbinder.com/articles/hack_any_java_class_using_reflection_attack.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Have you ever thought how secure your application is? Well reflection attack can demonstrate how vulnerable Java classes are. In this post, I will try to apply reflection attack on a simple Java class to demonstrate vulnerabilities and what can be done to prevent it (in most cases).</p>
<p>Consider a POJO class:</p>
<p>[java]<br />
public final class VictimClass  {</p>
<p>	private String password = &quot;default_password&quot;;<br />
	private static final int USER_ID = 3452678;<br />
	private String privateFiled = &quot;default_value&quot;;</p>
<p>	/**<br />
	 * Private constructor that should<br />
	 * not be invoked<br />
	 */<br />
	private VictimClass()  {<br />
		System.out.println(&quot;Oops&#8230; &quot; +<br />
		&quot;This private constructor was not &quot; +<br />
			&quot; suppose to be invoked&quot;);<br />
	}</p>
<p>	/**<br />
	 * Private accessor<br />
	 */<br />
	private String getPassword()  {<br />
		return password;<br />
	}</p>
<p>	 /**<br />
	 * Private mutator<br />
	 */<br />
	private void setPassword(String password)  {<br />
		this.password = password;<br />
	}</p>
<p>	 /**<br />
	 * Private static method<br />
	 */<br />
	private static int getUsersId()  {<br />
		return USER_ID;<br />
	}<br />
}</p>
<p>[/java]</p>
<p>The POJO contains private constructor and several private methods and fields, which I will attempt to invoke and modify using reflection attack.</p>
<p>Now, I cannot say that reflection attacks are possible due to a Java bug. No, its simply how Java classes were designed. The core reflection facility was originally designed for component based application builder tools.</p>
<p>In <em>java.lang.reflect, </em><em>Constructor, </em><em>Method </em>and <em>Field </em>extend from parent <em>AccessibleObject </em>class. These objects provide access to the class&#8217;s methods and fields. By calling inherited parent method <em>setAccessible(), </em>private variables and methods including private constructors become accessible.</p>
<p>My tester class:</p>
<p>[java]<br />
import java.lang.reflect.Constructor;<br />
import java.lang.reflect.Method;<br />
import java.lang.reflect.Field;<br />
import java.lang.reflect.Modifier;<br />
import java.lang.ClassNotFoundException;<br />
import java.lang.InstantiationException;<br />
import java.lang.IllegalAccessException;<br />
import java.lang.reflect.InvocationTargetException;<br />
import java.lang.NoSuchMethodException;</p>
<p>public class Tester  {</p>
<p>   private static String CLASS_NAME = &quot;VictimClass&quot;;<br />
   private static Class victimClass = null;<br />
   private static Object victimClassObj = null;</p>
<p>   public static void main(String[] args)  {<br />
	victimClass = loadClass(victimClass, CLASS_NAME);<br />
	printClassStructure();<br />
	attack();<br />
   }</p>
<p>    private static Class loadClass(Class clazzor, String className)  {<br />
 	Thread thread = Thread.currentThread();<br />
	ClassLoader classLoader =<br />
			thread.getContextClassLoader();</p>
<p>	try {<br />
		clazzor = Class.forName(className, true, classLoader);<br />
	}<br />
	catch (ClassNotFoundException e) {<br />
		System.err.println(&quot;Error: could not find class: &quot;<br />
			+ CLASS_NAME);<br />
	}</p>
<p>	return clazzor;<br />
   }</p>
<p>   private static void printClassStructure()  {</p>
<p>	Constructor[] constructors =<br />
			victimClass.getDeclaredConstructors();<br />
	for (Constructor c : constructors) {<br />
		int modifier = c.getModifiers();<br />
		System.out.println(&quot;Declared constructor name: &quot; +<br />
			c.getName() + &quot;ntis accessible: &quot; +<br />
			c.isAccessible() + &quot;ntis private: &quot; +<br />
			Modifier.isPrivate(modifier) + &quot;n&quot;);<br />
	}</p>
<p>	Method[] methods = victimClass.getDeclaredMethods();<br />
	for (Method m : methods) {<br />
		int modifier = m.getModifiers();<br />
		System.out.println(&quot;Declared method name: &quot; + m.getName() +<br />
			&quot;ntis accessible: &quot; +<br />
			m.isAccessible() +<br />
			 &quot;ntis private: &quot; +<br />
			Modifier.isPrivate(modifier) +<br />
			 &quot;ntis static: &quot; +<br />
			Modifier.isStatic(modifier) + &quot;n&quot;);<br />
	}</p>
<p>	Field[] fields = victimClass.getDeclaredFields();<br />
	for (Field f : fields) {<br />
		int modifier = f.getModifiers();<br />
		System.out.println(&quot;Declared field name: &quot; + f.getName() +<br />
			&quot;ntis accessible: &quot; +<br />
			f.isAccessible() +<br />
			 &quot;ntis private: &quot; +<br />
			Modifier.isPrivate(modifier) +<br />
			 &quot;ntis static: &quot; +<br />
			Modifier.isStatic(modifier) +<br />
			 &quot;ntis final: &quot; +<br />
			Modifier.isFinal(modifier) + &quot;n&quot;);<br />
	}<br />
   }</p>
<p>   private static void attack()  {</p>
<p>     Field[] fields = victimClass.getDeclaredFields();<br />
     Method[] methods = victimClass.getDeclaredMethods();<br />
     Constructor[] constructors =<br />
		victimClass.getDeclaredConstructors();<br />
   //make constructor accessible<br />
   constructors[0].setAccessible(true);</p>
<p>   System.err.println(&quot;Initiating reflection attack:&quot;);<br />
   try {<br />
   //create new object by invoking private constructor<br />
   victimClassObj = constructors[0].newInstance(new Object[] {});</p>
<p>   //make static method accessible and get its value<br />
   //please note: when invoking static method,<br />
   //object represented by this Method is null<br />
   methods[2].setAccessible(true);<br />
   Object o = methods[2].invoke(null, new Object[] {});<br />
   System.out.println(&quot;Got user ID from private static accessor: &quot;<br />
		 + o.toString());</p>
<p>   //make method accessible and get its value<br />
   methods[0].setAccessible(true);<br />
   o = methods[0].invoke(victimClassObj, new Object[] {});<br />
   System.out.println(&quot;Got original password from private accessor: &quot;<br />
	+ o.toString());</p>
<p>   //make method accessible and set to it new value<br />
   methods[1].setAccessible(true);<br />
   System.out.println(&quot;Injecting new password using private mutator&quot;);<br />
   methods[1].invoke(victimClassObj, new Object[] {&quot;injected_password&quot;});</p>
<p>   //get method&#8217;s its new value<br />
   o = methods[0].invoke(victimClassObj, new Object[] {});<br />
   System.out.println(&quot;Got injected password from private accessor: &quot;<br />
	 + o.toString());</p>
<p>   //make field accessible and get its value<br />
   fields[2].setAccessible(true);<br />
   o = fields[2].get(victimClassObj);<br />
   System.out.println(&quot;Got private field: &quot; + o);</p>
<p>   //make field accessible and set to it new value<br />
   System.out.println(&quot;Injecting value to a private field:&quot;);<br />
   fields[2].set(victimClassObj, &quot;new_default_value&quot;);</p>
<p>   //get field&#8217;s its new value<br />
   o = fields[2].get(victimClassObj);<br />
   System.out.println(&quot;Got updated private field: &quot; + o);</p>
<p>   //make field accessible and get its value<br />
   fields[1].setAccessible(true);<br />
   o = fields[1].get(victimClassObj);<br />
   System.out.println(&quot;Got private static field: &quot; + o);</p>
<p>   //make field accessible and set to it new value<br />
   System.out.println(&quot;Injecting value to a private static final field:&quot;);<br />
   fields[1].set(null, new Integer(2));</p>
<p>   //get field&#8217;s its new value<br />
   o = fields[1].get(victimClassObj);<br />
   System.out.println(&quot;Got updated private static final field: &quot; + o);</p>
<p>   }<br />
   catch (InstantiationException e) {<br />
	System.err.println(&quot;Error: could not instantiate: &quot; + e);<br />
   }</p>
<p>   catch (IllegalAccessException e) {<br />
	System.err.println(&quot;Error: could not access: &quot; + e);<br />
   }</p>
<p>   catch (InvocationTargetException e) {<br />
	System.err.println(&quot;Error: could not invoke the target: &quot; + e);<br />
   }<br />
  }<br />
}</p>
<p>[/java]</p>
<p>The call to <em>setAccessible() </em>can be restricted if SecurityManager is set, then any attempt to call the method above will result in exception. If required, it is possible to grant permission <em>java.reflect.ReflectPermission &#8220;suppressAccessChecks&#8221;</em> using external java.policy file or by applying security policy programmatically. This permission will allow invocation of <em>setAccessible()</em>. My other post <a href="http://javabeans.asia/2008/10/12/how_to_set_securitymanager_and_java_security_policy_programmatically.html">How to set SecurityManager and Java security policy programmatically</a> explains how this can be achieved. Please note: by doing so, you can allow malicious access to your classes.</p>
<p>This is what happens when program executes:<br />
I am using reflection, to get a print out of declared constructors, methods and fields. Following that, I am invoking private static and non-static method and attempting to change the value of private declared fields.</p>
<p>The program produces the following output:</p>
<p>[java]<br />
Declared constructor name: VictimClass<br />
        is accessible: false<br />
        is private: true</p>
<p>Declared method name: setPassword<br />
        is accessible: false<br />
        is private: true<br />
        is static: false</p>
<p>Declared method name: getUsersId<br />
        is accessible: false<br />
        is private: true<br />
        is static: true</p>
<p>Declared method name: getPassword<br />
        is accessible: false<br />
        is private: true<br />
        is static: false</p>
<p>Declared field name: password<br />
        is accessible: false<br />
        is private: true<br />
        is static: false<br />
        is final: false</p>
<p>Declared field name: USER_ID<br />
        is accessible: false<br />
        is private: true<br />
        is static: true<br />
        is final: true</p>
<p>Declared field name: privateFiled<br />
        is accessible: false<br />
        is private: true<br />
        is static: false<br />
        is final: false</p>
<p>Initiating reflection attack:<br />
Oops&#8230; This private constructor was not  suppose to be invoked<br />
Got user ID from private static accessor: 3452678<br />
Got original password from private accessor: default_password<br />
Injecting new password using private mutator<br />
Got injected password from private accessor: injected_password<br />
Got private field: default_value<br />
Injecting value to a private field:<br />
Got updated private field: new_default_value<br />
Got private static field: 3452678<br />
Injecting value to a private static final field:<br />
Error: could not access: java.lang.IllegalAccessException: Field is final<br />
[/java]</p>
<p>As output shows above, it is not possible to set a value to the filed that is final. Therefore, it would be good idea to make fields final whenever possible. As it was shown before, it prevents reflection attack (when trying to set a new value), plus to that its good for performance optimization (memory allocation).</p>
<p>So what we got so far? When we have a POJO, it is possible to invoke private constructor, private static and non-static methods and change the value of private fields.</p>
<p>Enumerators on other hand do not allow invocation of their private constructors. An attempt to do so will result in <em>IllegalArgumentException</em> exception: &#8220;Cannot reflectively create enum objects&#8221;. Enums are safe against invocation of private constructors through reflection attacks.</p>
<p>Since enum object instances cannot be created through reflection, private non-static methods cannot be invoked. Having said that, it is still possible to invoke private static methods on enum using reflection, like on any other Java class.</p>
<p><strong>Update</strong>: private non-static methods <strong>can</strong> be invoked on enum class, please refer to comments.</p>
<p>In conclusion, number of steps can be taken, in case someone really wants to prevent reflection attack on non-enum Java classes:</p>
<ol>
<li>Make fields final whenever possible</li>
<li>Private constructor can throw an exception if there will be an attempt to invoke it.</li>
<li>Applying security policy without <em>ReflectPermission</em> and setting security manager</li>
</ol>
<p>I hope that I was descriptive enough here, I will appreciate your comments here.</p>
<p>The source code for this post was tested in my Eclipse and is attached.</p>
<p>Cheers</p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/hack_any_java_class_using_reflection_attack.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to Set SecurityManager and Java Security Policy Programmatically</title>
		<link>http://initbinder.com/articles/how_to_set_securitymanager_and_java_security_policy_programmatically.html</link>
		<comments>http://initbinder.com/articles/how_to_set_securitymanager_and_java_security_policy_programmatically.html#comments</comments>
		<pubDate>Sat, 11 Oct 2008 23:16:00 +0000</pubDate>
		<dc:creator>Alexander Zagniotov</dc:creator>
				<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[reflection attack]]></category>
		<category><![CDATA[security policy]]></category>

		<guid isPermaLink="false">http://javabeans.asia/2008/10/12/how_to_set_securitymanager_and_java_security_policy_programmatically.html</guid>
		<description><![CDATA[In this example I want to show how to use SecurityManager to prevent unauthorized access to private members of a Java class, for example using reflection to invoke private constructor. Besides that I also want to show how Java security &#8230; <a href="http://initbinder.com/articles/how_to_set_securitymanager_and_java_security_policy_programmatically.html">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this example I want to show how to use SecurityManager to prevent unauthorized access to private members of a Java class, for example using reflection to invoke private constructor. Besides that I also want to show how Java security policy can be set programmatically with permission allowing to invoke private constructor through reflection when security manager is in place.</p>
<p>Consider a POJO:</p>
<p>[java]<br />
public final class VictimClass  {<br />
	/**<br />
	 * Private constructor that should<br />
	 * not be invoked<br />
	 */<br />
	private VictimClass()  {<br />
	   System.out.println(&quot;Instance created&quot;);<br />
           System.out.println(<br />
               &quot;Constructor was made accessible&quot;);<br />
	}<br />
}<br />
[/java]</p>
<p>I want to prevent invocation of private constructor, by setting security manager. After first invocation attempt, I do want to invoke private constructor by granting required permission by refreshing current security policy.</p>
<p>This is my tester class:</p>
<p>[java]<br />
import java.lang.reflect.Constructor;<br />
import java.lang.ClassNotFoundException;<br />
import java.lang.InstantiationException;<br />
import java.lang.IllegalAccessException;<br />
import java.lang.reflect.InvocationTargetException;<br />
import java.lang.NoSuchMethodException;<br />
import java.security.AccessControlException;<br />
import java.lang.reflect.ReflectPermission;<br />
import java.security.SecurityPermission;</p>
<p>public class Tester  {</p>
<p>	private static String CLASS_NAME = &quot;VictimClass&quot;;<br />
	private static Class victimClass = null;</p>
<p>	public static void main(String[] args)  {</p>
<p>	loadClass(victimClass, CLASS_NAME);</p>
<p>	//apply default policy with one permission<br />
	System.setProperty(&quot;java.security.policy&quot;,&quot;default.policy&quot;);</p>
<p>	try {<br />
	  //Setting security manager<br />
	  SecurityManager sm = new SecurityManager();<br />
	  System.setSecurityManager(sm);<br />
	} catch (SecurityException e) {<br />
	  System.err.println(&quot;Error: could not set security manager: &quot; + e);<br />
	}</p>
<p>	//first attempt to make constructor accessible<br />
	try  {<br />
	  makeConstructorAccessible();<br />
	}<br />
	catch (AccessControlException e) {<br />
	  System.err.println(<br />
		&quot;Could not made constructor accessible: &quot; + e.getMessage());<br />
	}</p>
<p>	System.out.println(&quot;Applying ReflectPermission programmatically&#8230;&quot;);<br />
	SecurityPolicy.getPolicy().addPermission(<br />
		new ReflectPermission(&quot;suppressAccessChecks&quot;));<br />
	SecurityPolicy.getPolicy().addPermission(<br />
		new SecurityPermission(&quot;setPolicy&quot;));<br />
	SecurityPolicy.getPolicy().refresh();<br />
	makeConstructorAccessible();<br />
	}</p>
<p>private static void loadClass(Class clazzor, String className)  {<br />
	Thread thread = Thread.currentThread();<br />
	ClassLoader classLoader =<br />
				thread.getContextClassLoader();</p>
<p>	try {<br />
	 victimClass = Class.forName(className, true, classLoader);<br />
	}<br />
	catch (ClassNotFoundException e) {<br />
	 System.err.println(&quot;Error: could not find class: &quot;<br />
			+ CLASS_NAME);<br />
	}<br />
}</p>
<p>private static void makeConstructorAccessible()  {<br />
	Constructor[] constructors =<br />
			victimClass.getDeclaredConstructors();<br />
	//make constructor accessible<br />
	constructors[0].setAccessible(true);</p>
<p>   try {<br />
	System.out.println(<br />
	&quot;Creating new instance by invoking private constructor&quot;);<br />
	constructors[0].newInstance(new Object[] {});<br />
   }<br />
	catch (InstantiationException e) {<br />
	  System.err.println(&quot;Error: could not instantiate: &quot; + e);<br />
	}<br />
	catch (IllegalAccessException e) {<br />
	  System.err.println(&quot;Error: could not access: &quot; + e);<br />
	}<br />
	catch (InvocationTargetException e) {<br />
	  System.err.println(&quot;Error: could not invoke the target: &quot; + e);<br />
	}<br />
  }<br />
}<br />
[/java]</p>
<p>This is what happens when program executes:</p>
<p>Before setting SecurityManager, I am applying default security policy from external file with security permission &#8220;setPolicy&#8221;, that will allow me to reset new security policy in the future.</p>
<p>My default security policy:</p>
<p>[java]<br />
grant {<br />
	permission java.security.SecurityPermission &quot;setPolicy&quot;;<br />
};<br />
[/java]</p>
<p>When SecurityManager is set, it restricts everything except whats permitted by security policy that was set previously. You can view list of Java permissions that can be set here.</p>
<p>By default, the private constructors,methods and fields are inaccessible. So if you want to use reflection, and invoke private constructor of this POJO, it will result in<br />
IllegalAccessException since the constructor above has private modifier.</p>
<p>This restriction can be bypassed by calling parent method setAccessible(). To remind: java.lang.reflect.Constructor, java.lang.reflect.Method and java.lang.reflect.Field extend from parent java.lang.reflect.AccessibleObject class.</p>
<p>By calling inherited parent method setAccessible(), private variables and methods including private constructors become accessible.</p>
<p>With SecurityManager set, an attempt to invoke setAccessible() will result in AccessControlException. Following that, I am granting required ReflectPermission suppressAccessChecks by applying my own security policy. This will allow me to invoke private constructor in my POJO.</p>
<p>Now, having said that, I have to say that granting ReflectPermission with action suppressAccessChecks can be extremely dangerous as it allows private constructors to become accessible, as the example above shows. Not only constructors, but inaccessible fields and methods can become accessible, which can allow room for reflection attacks. In my other post Hack any Java class using reflection attack I explain how this can be achieved.</p>
<p>When I am applying my own security policy, please note that I am granting again security permission &#8220;setPolicy&#8221;. Because I am reseting default policy set previously, I have to grant &#8220;setPolicy&#8221; permission again if I want to keep applying new security policies in the future at run time of this program.</p>
<p>Below is my own implementation of java.security.Policy class, I tried to put enough comments to make things straight forward to you readers:</p>
<p>[java]<br />
import java.security.Policy;<br />
import java.security.CodeSource;<br />
import java.lang.reflect.ReflectPermission;<br />
import java.security.SecurityPermission;<br />
import java.security.*;<br />
import java.lang.RuntimePermission;<br />
import java.util.*;</p>
<p>public class SecurityPolicy extends Policy {</p>
<p>	private PermissionCollection perms = null;</p>
<p>    //lazy initialization class holder<br />
    private static class SecurityPolicyHolder {<br />
	private static final SecurityPolicy policy = new SecurityPolicy();<br />
    }</p>
<p>    private SecurityPolicy() {<br />
	perms = new Permissions();<br />
    }</p>
<p>    public static SecurityPolicy getPolicy() {<br />
	return SecurityPolicyHolder.policy;<br />
    }</p>
<p>    public PermissionCollection getPermissions(CodeSource codesource) {<br />
        return perms;<br />
    }</p>
<p>    //invoked when new Permission is added to the current security Policy<br />
	public boolean implies(ProtectionDomain domain, Permission permission)  {</p>
<p>	//get permission collection from the domain<br />
	PermissionCollection domainPermissions = domain.getPermissions();</p>
<p>	//get enumeration of permission elements<br />
	Enumeration&lt;Permission&gt; permissions = domainPermissions.elements();</p>
<p>	//convert to array list (dont have to, i just dont like enumerations)<br />
	ArrayList&lt;Permission&gt; list = Collections.list(permissions);</p>
<p>	//Checks to see if the specified permission is<br />
	//implied (subset of) by the collection of<br />
	//Permission objects held in this PermissionCollection<br />
	if (!domainPermissions.implies(permission)) {</p>
<p>		//permission collection in the domain is read-only,<br />
		//Exception will be thrown if Permission object<br />
		//is added to read-only collection<br />
		if (domainPermissions.isReadOnly()) {</p>
<p>			//Because collection is read-only,<br />
			//add Permission objects to the local<br />
			//permission collection instead<br />
			for (Permission p :list) {<br />
				if (!perms.implies(p)) {<br />
				   perms.add(p);<br />
				}<br />
			}</p>
<p>			//assign local permission collection as a<br />
			//domain permission collection<br />
			domainPermissions = perms;<br />
		}<br />
		else {<br />
			//if domain permission collection is not read only,<br />
			//just add new permission to it<br />
		  domainPermissions.add(permission);<br />
		}</p>
<p>		//check if now domain has the new Permission<br />
		return domainPermissions.implies(permission);<br />
	}</p>
<p>		return false;<br />
	}</p>
<p>	public void addPermission(Permission permission)  {<br />
        perms.add(permission);<br />
	}<br />
        //you can write your own implementation<br />
	//of refresh method<br />
        @Override<br />
	public void refresh() {<br />
         Policy.setPolicy(this);<br />
	}<br />
}<br />
[/java]</p>
<p>The following shows program output. Please not that first attempt to make private constructor accessible resulted in exception. After required permission was granted, new object instance was succesfully created through reflection:</p>
<p>[java]<br />
Could not made constructor accessible:<br />
access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)<br />
Applying ReflectPermission programmatically&#8230;<br />
Creating new instance by invoking private constructor<br />
Constructor was made accessible<br />
Instance created<br />
[/java]</p>
<p><strong>Please note</strong>:<br />
I did test this code. But I am not sure whether my SecuriyPolicy class implemented efficiently. The source code for this post is attached.</p>
<p><a href="http://initbinder.com/bunker/wp-content/uploads/2008/10/set_java_security_policy.zip">set java security policy sourcecode</a></p>
]]></content:encoded>
			<wfw:commentRss>http://initbinder.com/articles/how_to_set_securitymanager_and_java_security_policy_programmatically.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  initbinder.com/categories/java/design-patterns/feed ) in 0.31103 seconds, on May 18th, 2012 at 2:09 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 18th, 2012 at 3:09 pm UTC -->
