<?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>Java Blog &#187; Core Java</title>
	<atom:link href="http://javapapers.com/category/core-java/feed/" rel="self" type="application/rss+xml" />
	<link>http://javapapers.com</link>
	<description>BLOG on core java, servlets, JSP, design patterns interview questions with quality answers, source code and discussions.</description>
	<lastBuildDate>Tue, 27 Jul 2010 18:48:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Type Erasure</title>
		<link>http://javapapers.com/core-java/type-erasure/</link>
		<comments>http://javapapers.com/core-java/type-erasure/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 18:47:20 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=391</guid>
		<description><![CDATA[Java generics uses Types. If you are not still using java generics, following example code explains you a simple generics usage:

package com.javapapers.sample;

import java.util.HashMap;
import java.util.Map;

public class TypeErasure {
	public static void main(String args[]) {

		Map&#60;String, String&#62; languageMap = new HashMap&#60;String, String&#62;();
		languageMap.put(&#34;1954&#34;, &#34;FORTRAN&#34;);
		languageMap.put(&#34;1958&#34;, &#34;LISP&#34;);
		languageMap.put(&#34;1959&#34;, &#34;COBOL&#34;);
		String language = languageMap.get(&#34;1954&#34;);
		System.out.println(&#34;Our favourite language is &#34;+language);
	}
}

In the above code, we instantiate a map [...]]]></description>
			<content:encoded><![CDATA[<p>Java generics uses Types. If you are not still using java generics, following example code explains you a simple generics usage:</p>
<pre class="brush: java;">
package com.javapapers.sample;

import java.util.HashMap;
import java.util.Map;

public class TypeErasure {
	public static void main(String args[]) {

		Map&lt;String, String&gt; languageMap = new HashMap&lt;String, String&gt;();
		languageMap.put(&quot;1954&quot;, &quot;FORTRAN&quot;);
		languageMap.put(&quot;1958&quot;, &quot;LISP&quot;);
		languageMap.put(&quot;1959&quot;, &quot;COBOL&quot;);
		String language = languageMap.get(&quot;1954&quot;);
		System.out.println(&quot;Our favourite language is &quot;+language);
	}
}
</pre>
<p>In the above code, we instantiate a map saying that the key and values will be String. These are type parameters. It provides you type safety.</p>
<p>Type erasure is a process to remove the types and map it to byte code. Just trying to give a formal definition for type erasure ;-) Type erasure happens at compile time. Java compiler removes those generic type information from source and adds casts as needed and delivers the byte code. Therefore the generated byte code will not have any information about type parameters and arguments. It will look like a old java code without generics. You want to have a look at it?</p>
<div id="attachment_392" class="wp-caption alignright" style="width: 410px"><img class="size-full wp-image-392" title="new_as_old" src="http://javapapers.com/wp-content/uploads/2010/07/new_as_old.jpg" alt="" width="400" height="292" /><p class="wp-caption-text">New as Old!</p></div>
<p>Compile above given source and get a class file. Then de-compile that generate class file and you will know what is inside. You may use JAD to de-compile. Else you can avoid the round trip and use the JDK itself directly on java source and find out how the compiled source will look like.<em><strong> javac -XD-printflat -d  .java</strong></em></p>
<pre class="brush: java;">
package com.javapapers.sample;

import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;

public class TypeErasure
{

    public TypeErasure()
    {
    }

    public static void main(String args[])
    {
        Map languageMap = new HashMap();
        languageMap.put(&quot;1954&quot;, &quot;FORTRAN&quot;);
        languageMap.put(&quot;1958&quot;, &quot;LISP&quot;);
        languageMap.put(&quot;1959&quot;, &quot;COBOL&quot;);
        String language = (String)languageMap.get(&quot;1954&quot;);
        System.out.println((new StringBuilder(&quot;Our favourite language is &quot;)).append(language).toString());
    }
}
</pre>
<p>You should note two things in the above de-compiled code.</p>
<ol>
<li> First thing is, &#8220;&lt;String, String&gt;&#8221; is missing.</li>
<li>Second thing is (String)languageMap.get(&#8220;1954&#8243;) a type cast is added.</li>
</ol>
<p>This is done by the java compiler while compiling java source code to byte code. This process is called java type erasure.</p>
<p>Main reason behind having type erasure at compile time is to give compatibility with old versions of java code where you don&#8217;t have generics. If you look at the definition of Map intereface using source available in JDK (beyond 1.5 ), it will be like</p>
<pre class="brush: java;">public interface Map&lt;K,V&gt; {</pre>
<p>So if you use the Map without generics that should work with latest code. Thats why the java type erasure is brought in. When you use generics compiler checks whether you use all you type properly or not. If something is wrong you get an error at compile time and you need not wait until run time and blow up your production.</p>
<h2>Consequences of Type Erasures</h2>
<p>A java class with parametrized type cannot be instantiated as it requires a call to constructor. At run-time the type is not available because of type erasure and the instantiation cannot be done.</p>
<pre class="brush: java;">
T instantiateElementType(List&lt;T&gt; arg)
{
  return new T(); //causes a compilation error
}
</pre>
<p>Because of type erasure, at run-time you will not be able to find out what was the predefined type. There are hacks available using Reflection, but it is not guaranteed that it will work in all cases. It is also not a formal way.</p>
<p>There is lots of discussions on whether you need type erasure or is it implemented in a good way is going around. Leave that aside. If you use java, its better to use generics as much as possible. Advantage you get in using generics is type safety and clarity in your code. Though type erasure is good or bad, better know about it. Because it is the one that translates your generic java code to byte code.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-knowledge">
<ul class="socials">
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Type+Erasure+-+http://javapapers.com/core-java/type-erasure/&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://javapapers.com/core-java/type-erasure/&amp;t=Type+Erasure" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a>
		</li>
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://javapapers.com/core-java/type-erasure/&amp;title=Type+Erasure" rel="nofollow" class="external" title="Digg this!">Digg this!</a>
		</li>
		<li class="shr-delicious">
			<a href="http://delicious.com/post?url=http://javapapers.com/core-java/type-erasure/&amp;title=Type+Erasure" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a>
		</li>
		<li class="shr-stumbleupon">
			<a href="http://www.stumbleupon.com/submit?url=http://javapapers.com/core-java/type-erasure/&amp;title=Type+Erasure" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a>
		</li>
		<li class="shr-technorati">
			<a href="http://technorati.com/faves?add=http://javapapers.com/core-java/type-erasure/" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a>
		</li>
		<li class="shr-mail">
			<a href="mailto:?subject=%22Type%20Erasure%22&amp;body=Link: http://javapapers.com/core-java/type-erasure/ (sent via shareaholic)%0D%0A%0D%0A----%0D%0A Java%20generics%20uses%20Types.%20If%20you%20are%20not%20still%20using%20java%20generics%2C%20following%20example%20code%20explains%20you%20a%20simple%20generics%20usage%3A%0D%0A%0D%0A%5Bjava%5D%0D%0Apackage%20com.javapapers.sample%3B%0D%0A%0D%0Aimport%20java.util.HashMap%3B%0D%0Aimport%20java.util.Map%3B%0D%0A%0D%0Apublic%20class%20TypeErasure%20%7B%0D%0A%09public%20static%20void%20main%28String%20args%5B%5D%29%20%7B%0D%0A%0D%0A%09" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/type-erasure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Address of a Java Object</title>
		<link>http://javapapers.com/core-java/address-of-a-java-object/</link>
		<comments>http://javapapers.com/core-java/address-of-a-java-object/#comments</comments>
		<pubDate>Mon, 05 Jul 2010 08:25:09 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=362</guid>
		<description><![CDATA[In conventional java programming, you will never need address or location of a java object from memory. When you discuss about this in forums, the first question raised is why do you need to know the address of a java object? Its a valid question. But always, we reserve the right to experiment. Nothing is [...]]]></description>
			<content:encoded><![CDATA[<p>In conventional java programming, you will never need address or location of a java object from memory. When you discuss about this in forums, the first question raised is why do you need to know the address of a java object? Its a valid question. But always, we reserve the right to experiment. Nothing is wrong in exploring uncharted areas.<img class="alignright size-full wp-image-363" title="address" src="http://javapapers.com/wp-content/uploads/2010/07/address.jpeg" alt="" width="141" height="291" /></p>
<p>I thought of experimenting using a little known class from sun package. Unsafe is a class that belongs to sun.misc package. For some of you the package might be new. You need not worry about it. If you have sun&#8217;s JDK then you have this class already.</p>
<p>When a class name is &#8220;Unsafe&#8221; in java, it calls for your attention immediately. Then I decided to dig deep into it and find what is unsafe about that class. Voila, it really opens up the pandora&#8217;s box. Its difficult to find the source of Unsafe. Get the source and look at the methods you will know what I am referring to.</p>
<p>Java&#8217;s security manager provides sufficient cover and ensures you don&#8217;t fiddle with memory that easily. As a first step, I thought of getting the memory location of a java object. Until the exploration, I too was 100% confident that it was not possible to find the location / address of an object in java.<img class="alignright size-full wp-image-364" title="logicaladdress" src="http://javapapers.com/wp-content/uploads/2010/07/logicaladdress.jpg" alt="" width="319" height="327" /></p>
<p>Sun&#8217;s Unsafe.java api documentation shows us an opportunity to get the address using the method objectFieldOffset. That method says, &#8220;<em>Report the location of a given field in the storage allocation of its class</em>&#8220;. It also says, &#8220;<em>it is just a cookie which is passed to the unsafe heap memory accessors</em>&#8220;. Whatsoever, I am able to get the storage memory location of an object from the storage allocation of its class.</p>
<p>You can argue that, what we have got is not the absolute physical memory address of an object. But we have got the logical memory address. The following program will be quite interesting for you!</p>
<p>As a first step, I have to get an object of Unsafe class. It is quite difficult as the constructor is private. There is a method named getUnsafe which returns the unsafe object. Java&#8217;s security manager asks you to make your <a title="Make your java code privileged." href="http://javapapers.com/core-java/is-your-java-code-privileged/">java source code privileged</a>. I used little bit of reflection and got an instance out. I know there are better ways to get the instance. But to bypass the security easily I chose the following.</p>
<p>Using Unsafe&#8217;s object just invoke objectFieldOffset and staticFieldOffset. The result is address / location of object in the storage allocation of its class.</p>
<p>Following example program runs well on JDK 1.6</p>
<pre class="brush: java;">
import sun.misc.Unsafe;
import java.lang.reflect.Field;

public class ObjectLocation {

 private static int apple = 10;
 private int orange = 10;

 public static void main(String[] args) throws Exception {
  Unsafe unsafe = getUnsafeInstance();

  Field appleField = ObjectLocation.class.getDeclaredField(&quot;apple&quot;);
  System.out.println(&quot;Location of Apple: &quot;
    + unsafe.staticFieldOffset(appleField));

  Field orangeField = ObjectLocation.class.getDeclaredField(&quot;orange&quot;);
  System.out.println(&quot;Location of Orange: &quot;
    + unsafe.objectFieldOffset(orangeField));
 }

 private static Unsafe getUnsafeInstance() throws SecurityException,
   NoSuchFieldException, IllegalArgumentException,
   IllegalAccessException {
  Field theUnsafeInstance = Unsafe.class.getDeclaredField(&quot;theUnsafe&quot;);
  theUnsafeInstance.setAccessible(true);
  return (Unsafe) theUnsafeInstance.get(Unsafe.class);
 }
}
</pre>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-knowledge">
<ul class="socials">
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Address+of+a+Java+Object+-+http://javapapers.com/core-java/address-of-a-java-object/&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://javapapers.com/core-java/address-of-a-java-object/&amp;t=Address+of+a+Java+Object" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a>
		</li>
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://javapapers.com/core-java/address-of-a-java-object/&amp;title=Address+of+a+Java+Object" rel="nofollow" class="external" title="Digg this!">Digg this!</a>
		</li>
		<li class="shr-delicious">
			<a href="http://delicious.com/post?url=http://javapapers.com/core-java/address-of-a-java-object/&amp;title=Address+of+a+Java+Object" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a>
		</li>
		<li class="shr-stumbleupon">
			<a href="http://www.stumbleupon.com/submit?url=http://javapapers.com/core-java/address-of-a-java-object/&amp;title=Address+of+a+Java+Object" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a>
		</li>
		<li class="shr-technorati">
			<a href="http://technorati.com/faves?add=http://javapapers.com/core-java/address-of-a-java-object/" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a>
		</li>
		<li class="shr-mail">
			<a href="mailto:?subject=%22Address%20of%20a%20Java%20Object%22&amp;body=Link: http://javapapers.com/core-java/address-of-a-java-object/ (sent via shareaholic)%0D%0A%0D%0A----%0D%0A In%20conventional%20java%20programming%2C%20you%20will%20never%20need%20address%20or%20location%20of%20a%20java%20object%20from%20memory.%20When%20you%20discuss%20about%20this%20in%20forums%2C%20the%20first%20question%20raised%20is%20why%20do%20you%20need%20to%20know%20the%20address%20of%20a%20java%20object%3F%20Its%20a%20valid%20question.%20But%20always%2C%20we%20reserve%20the%20right%20to%20experiment.%20Noth" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/address-of-a-java-object/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Java&#8217;s toLowerCase() has got a surprise for you!</title>
		<link>http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/</link>
		<comments>http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/#comments</comments>
		<pubDate>Sun, 09 May 2010 10:58:41 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=332</guid>
		<description><![CDATA[Have you ever encountered a surprise while using toLowerCase()? This is a widely used method when it comes to strings and case conversion. There is a nice little thing you should be aware of. 
toLowerCase() respects internationalization (i18n). It performs the case conversion with respect to your Locale. When you call toLowerCase(), internally toLowerCase(Locale.getDefault()) is [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever encountered a surprise while using toLowerCase()? This is a widely used method when it comes to strings and case conversion. There is a nice little thing you should be aware of. <a href="http://javapapers.com/wp-content/uploads/2010/05/hat-lion-rabbit.jpg"><img class="alignright size-full wp-image-333" title="No Rabbit Inside!" src="http://javapapers.com/wp-content/uploads/2010/05/hat-lion-rabbit.jpg" alt="" width="400" height="300" /></a></p>
<p>toLowerCase() respects <a title="Check list for Internationalization (i18n)" href="http://javapapers.com/core-java/check-list-for-internationalization-i18n/">internationalization</a> (i18n). It performs the case conversion with respect to your Locale. When you call <a title="toLowerCase() Java API" href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#toLowerCase()">toLowerCase()</a>, internally toLowerCase(Locale.getDefault()) is getting called.  It is locale sensitive and you should not write a logic around it interpreting locale independently.</p>
<pre class="brush: java;">
import java.util.Locale;

public class ToLocaleTest {
    public static void main(String[] args) throws Exception {
        Locale.setDefault(new Locale(&quot;lt&quot;)); //setting Lithuanian as locale
        String str = &quot;\u00cc&quot;;
		System.out.println(&quot;Before case conversion is &quot;+str+&quot; and length is &quot;+str.length());// Ì
        String lowerCaseStr = str.toLowerCase();
		System.out.println(&quot;Lower case is &quot;+lowerCaseStr+&quot; and length is &quot;+lowerCaseStr.length());// i?`
    }
}
</pre>
<p>In the above program, look at the string length before and after conversion. It will be 1 and 3. Yes the length of the string before and after case conversion is different. Your logic will go for a toss when you depend on string length on this scenario. When your program gets executed in a different environment, it may fail. This will be a nice catch in code review.</p>
<p>To make it safer, you may use another method toLowerCase(Locale.English) and override the locale to English always. But then you are not internationalized.</p>
<p>So the crux is, toLowerCase() is locale specific.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-knowledge">
<ul class="socials">
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Java%27s+toLowerCase%28%29+has+got+a+surprise+for+you%21+-+http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/&amp;t=Java%27s+toLowerCase%28%29+has+got+a+surprise+for+you%21" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a>
		</li>
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/&amp;title=Java%27s+toLowerCase%28%29+has+got+a+surprise+for+you%21" rel="nofollow" class="external" title="Digg this!">Digg this!</a>
		</li>
		<li class="shr-delicious">
			<a href="http://delicious.com/post?url=http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/&amp;title=Java%27s+toLowerCase%28%29+has+got+a+surprise+for+you%21" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a>
		</li>
		<li class="shr-stumbleupon">
			<a href="http://www.stumbleupon.com/submit?url=http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/&amp;title=Java%27s+toLowerCase%28%29+has+got+a+surprise+for+you%21" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a>
		</li>
		<li class="shr-technorati">
			<a href="http://technorati.com/faves?add=http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a>
		</li>
		<li class="shr-mail">
			<a href="mailto:?subject=%22Java%27s%20toLowerCase%28%29%20has%20got%20a%20surprise%20for%20you%21%22&amp;body=Link: http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/ (sent via shareaholic)%0D%0A%0D%0A----%0D%0A Have%20you%20ever%20encountered%20a%20surprise%20while%20using%20toLowerCase%28%29%3F%20This%20is%20a%20widely%20used%20method%20when%20it%20comes%20to%20strings%20and%20case%20conversion.%20There%20is%20a%20nice%20little%20thing%20you%20should%20be%20aware%20of.%20%0D%0A%0D%0AtoLowerCase%28%29%20respects%20internationalization%20%28i18n%29.%20It%20performs%20the%20case%20conversion%20with%20respect%20to%20your" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Is Your Java Code Privileged?</title>
		<link>http://javapapers.com/core-java/is-your-java-code-privileged/</link>
		<comments>http://javapapers.com/core-java/is-your-java-code-privileged/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 17:53:41 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=325</guid>
		<description><![CDATA[The java system code that is part of the JDK is considered God and has all the maximum privileges. For example it can read a system property by default. To easily understand it is better to consider java Applets. An Applet cannot read a system property by default because it belongs to different CodeSource and [...]]]></description>
			<content:encoded><![CDATA[<p>The java system code that is part of the JDK is considered God and has all the maximum privileges. For example it can read a system property by default. To easily understand it is better to consider java Applets. An Applet cannot read a system property by default because it belongs to different CodeSource and not in same domain as system code. Recall that the system code has all privileges.<img class="alignright size-full wp-image-327" title="Privilege" src="http://javapapers.com/wp-content/uploads/2010/03/privilege.jpg" alt="" width="419" height="271" /></p>
<p>Then what do you need to do for Applet to get that privilege? You need to explicitly grant those security privileges by creating a policy file. In that policy you specify what are all the privileges you are granting.</p>
<p>There is another option also. It is opposite of the above. You say that this code doesn&#8217;t require any security policy and it is privileged to do the same (anything) as system code. Do you smell something evil here? This is a risky thing to do. Giving away the security is OS dependent. &#8220;Privileged code + malicious user + hole in OS&#8221; will be a worst thing to tackle.</p>
<p>Therefore you need to keep the code block as minimum as possible, for which you are going to give privilege. You might require this in the following scenarios</p>
<ul>
<li>To read a file</li>
<li>To read a system property</li>
<li>To create a network connection to the local machine</li>
<li>To get direct access to files that contain fonts</li>
</ul>
<h2>How to make java code privileged?</h2>
<pre class="brush: java;">
   anyMethod() {
        ...other java code here...
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // put the privileged code here, example:
                System.loadLibrary(&quot;awt&quot;);
                return null; // in our scenario nothing to return
            }
        });
       ...other code continues...
  }
</pre>
<p><a href="http://java.sun.com/javase/6/docs/api/java/security/AccessController.html">AccessController API</a> explains more about java privileged code and examples.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-knowledge">
<ul class="socials">
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Is+Your+Java+Code+Privileged%3F+-+http://javapapers.com/core-java/is-your-java-code-privileged/&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://javapapers.com/core-java/is-your-java-code-privileged/&amp;t=Is+Your+Java+Code+Privileged%3F" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a>
		</li>
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://javapapers.com/core-java/is-your-java-code-privileged/&amp;title=Is+Your+Java+Code+Privileged%3F" rel="nofollow" class="external" title="Digg this!">Digg this!</a>
		</li>
		<li class="shr-delicious">
			<a href="http://delicious.com/post?url=http://javapapers.com/core-java/is-your-java-code-privileged/&amp;title=Is+Your+Java+Code+Privileged%3F" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a>
		</li>
		<li class="shr-stumbleupon">
			<a href="http://www.stumbleupon.com/submit?url=http://javapapers.com/core-java/is-your-java-code-privileged/&amp;title=Is+Your+Java+Code+Privileged%3F" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a>
		</li>
		<li class="shr-technorati">
			<a href="http://technorati.com/faves?add=http://javapapers.com/core-java/is-your-java-code-privileged/" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a>
		</li>
		<li class="shr-mail">
			<a href="mailto:?subject=%22Is%20Your%20Java%20Code%20Privileged%3F%22&amp;body=Link: http://javapapers.com/core-java/is-your-java-code-privileged/ (sent via shareaholic)%0D%0A%0D%0A----%0D%0A The%20java%20system%20code%20that%20is%20part%20of%20the%20JDK%20is%20considered%20God%20and%20has%20all%20the%20maximum%20privileges.%20For%20example%20it%20can%20read%20a%20system%20property%20by%20default.%20To%20easily%20understand%20it%20is%20better%20to%20consider%20java%20Applets.%20An%20Applet%20cannot%20read%20a%20system%20property%20by%20default%20because%20it%20belongs%20to%20different%20Code" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/is-your-java-code-privileged/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Serialize / De-Serialize Java Object From Database</title>
		<link>http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/</link>
		<comments>http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/#comments</comments>
		<pubDate>Sat, 09 Jan 2010 14:26:49 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=305</guid>
		<description><![CDATA[In recent days generalization have become popular in software development. You build a common platform and generate applications out of it to reduce the cost. In such applications an activity that will be frequently performed is serializing java objects to database.
There are many fancy tools and framework available to do this. Before using all of [...]]]></description>
			<content:encoded><![CDATA[<p>In recent days generalization have become popular in software development. You build a common platform and generate applications out of it to reduce the cost. In such applications an activity that will be frequently performed is serializing java objects to database.</p>
<p>There are many fancy tools and framework available to do this. Before using all of those, you need to understand the low level details of serializing a java object to database.<img src="http://javapapers.com/wp-content/uploads/2010/01/reconstructtheobject.gif" alt="" title="Reconstruct The Object" width="260" height="167" class="alignright size-full wp-image-306" /></p>
<p>In older days before the advent of JDBC 3.0 you need to completely rely on streams.</p>
<ol>
<li>Stream the object to a ByteArrayOutputStream via an ObjectOutputStream.</li>
<li>Convert the ByteArrayOutputStream to a byte array.</li>
<li>Call the setBytes method on the prepared statement.</li>
</ol>
<p>Now you can use Object type support from jdbc to store the object into database.</p>
<p>There are some key factors before performing serialization.<br />
1. Database in use<br />
2. Datatype to be used to persist the object</p>
<p>Also know some <a title="Fundamentals of Java Serialization" href="http://javapapers.com/core-java/java-serialization/">fundamentals of serialization</a>.</p>
<p>I have given a sample java source code below to serialize and de-serialize java object to mysql database. In that, I have commented a line<br />
Object object = rs.getObject(1);<br />
Enable this line and comment the following 4 lines and execute and see the result. You will learn one more point.</p>
<p>To de-serialize a java object from database:</p>
<ol>
<li>Read the byte array and put it into a ByteArrayInputStream</li>
<li>Pass that to an ObjectInputStream</li>
<li> Then read the object.</li>
</ol>
<p>Sample Java Source Code &#8211; Serialize to DB</p>
<p>Before you run the following example, you need to create a database and a table in it.<br />
Run the following query to create a table before running the sample java program.<br />
I used mysql and driver mysql-connector-java-5.0.3-bin.jar. You may use the database of your choice with tweaks to the connection strings.</p>
<pre class="brush: sql;">
 create database javaserialization;

 CREATE TABLE `serialized_java_objects` (
 `serialized_id` int(11) NOT NULL auto_increment,
 `object_name` varchar(20) default NULL,
 `serialized_object` blob,
 PRIMARY KEY  (`serialized_id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</pre>
<pre class="brush: java;">
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class SerializeToDatabase {

	private static final String SQL_SERIALIZE_OBJECT = &quot;INSERT INTO serialized_java_objects(object_name, serialized_object) VALUES (?, ?)&quot;;
	private static final String SQL_DESERIALIZE_OBJECT = &quot;SELECT serialized_object FROM serialized_java_objects WHERE serialized_id = ?&quot;;

	public static long serializeJavaObjectToDB(Connection connection,
			Object objectToSerialize) throws SQLException {

		PreparedStatement pstmt = connection
				.prepareStatement(SQL_SERIALIZE_OBJECT);

		// just setting the class name
		pstmt.setString(1, objectToSerialize.getClass().getName());
		pstmt.setObject(2, objectToSerialize);
		pstmt.executeUpdate();
		ResultSet rs = pstmt.getGeneratedKeys();
		int serialized_id = -1;
		if (rs.next()) {
			serialized_id = rs.getInt(1);
		}
		rs.close();
		pstmt.close();
		System.out.println(&quot;Java object serialized to database. Object: &quot;
				+ objectToSerialize);
		return serialized_id;
	}

	/**
	 * To de-serialize a java object from database
	 *
	 * @throws SQLException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Object deSerializeJavaObjectFromDB(Connection connection,
			long serialized_id) throws SQLException, IOException,
			ClassNotFoundException {
		PreparedStatement pstmt = connection
				.prepareStatement(SQL_DESERIALIZE_OBJECT);
		pstmt.setLong(1, serialized_id);
		ResultSet rs = pstmt.executeQuery();
		rs.next();

		// Object object = rs.getObject(1);

		byte[] buf = rs.getBytes(1);
		ObjectInputStream objectIn = null;
		if (buf != null)
			objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));

		Object deSerializedObject = objectIn.readObject();

		rs.close();
		pstmt.close();

		System.out.println(&quot;Java object de-serialized from database. Object: &quot;
				+ deSerializedObject + &quot; Classname: &quot;
				+ deSerializedObject.getClass().getName());
		return deSerializedObject;
	}

	/**
	 * Serialization and de-serialization of java object from mysql
	 *
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 * @throws IOException
	 */
	public static void main(String args[]) throws ClassNotFoundException,
			SQLException, IOException {
		Connection connection = null;

		String driver = &quot;com.mysql.jdbc.Driver&quot;;
		String url = &quot;jdbc:mysql://localhost/javaserialization&quot;;
		String username = &quot;root&quot;;
		String password = &quot;admin&quot;;
		Class.forName(driver);
		connection = DriverManager.getConnection(url, username, password);

		// a sample java object to serialize
		Vector obj = new Vector();
		obj.add(&quot;java&quot;);
		obj.add(&quot;papers&quot;);

		// serializing java object to mysql database
		long serialized_id = serializeJavaObjectToDB(connection, obj);

		// de-serializing java object from mysql database
		Vector objFromDatabase = (Vector) deSerializeJavaObjectFromDB(
				connection, serialized_id);

		connection.close();
	}
}
</pre>
<h3>Output of the above java program</h3>
<pre class="brush: plain;">
Java object serialized to database. Object: [java, papers]
Java object de-serialized from database. Object: [java, papers] Classname: java.util.Vector
</pre>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-knowledge">
<ul class="socials">
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Serialize+%2F+De-Serialize+Java+Object+From+Database+-+http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/&amp;t=Serialize+%2F+De-Serialize+Java+Object+From+Database" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a>
		</li>
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/&amp;title=Serialize+%2F+De-Serialize+Java+Object+From+Database" rel="nofollow" class="external" title="Digg this!">Digg this!</a>
		</li>
		<li class="shr-delicious">
			<a href="http://delicious.com/post?url=http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/&amp;title=Serialize+%2F+De-Serialize+Java+Object+From+Database" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a>
		</li>
		<li class="shr-stumbleupon">
			<a href="http://www.stumbleupon.com/submit?url=http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/&amp;title=Serialize+%2F+De-Serialize+Java+Object+From+Database" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a>
		</li>
		<li class="shr-technorati">
			<a href="http://technorati.com/faves?add=http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a>
		</li>
		<li class="shr-mail">
			<a href="mailto:?subject=%22Serialize%20%2F%20De-Serialize%20Java%20Object%20From%20Database%22&amp;body=Link: http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/ (sent via shareaholic)%0D%0A%0D%0A----%0D%0A In%20recent%20days%20generalization%20have%20become%20popular%20in%20software%20development.%20You%20build%20a%20common%20platform%20and%20generate%20applications%20out%20of%20it%20to%20reduce%20the%20cost.%20In%20such%20applications%20an%20activity%20that%20will%20be%20frequently%20performed%20is%20serializing%20java%20objects%20to%20database.%0D%0A%0D%0AThere%20are%20many%20fancy%20tools%20and" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Bye bye GoDaddy</title>
		<link>http://javapapers.com/core-java/bye-bye-godaddy/</link>
		<comments>http://javapapers.com/core-java/bye-bye-godaddy/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 20:28:24 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=296</guid>
		<description><![CDATA[It was a bumpy ride in 2009. Many highs and lows. I enjoyed every moment of it. December 2009 is an important month for javapapers. My hosting provider GoDaddy kept me completely busy.
As almost everybody ;-) in the web world I also got my due share of problems from Go Daddy. It all started with [...]]]></description>
			<content:encoded><![CDATA[<p>It was a bumpy ride in 2009. Many highs and lows. I enjoyed every moment of it. December 2009 is an important month for javapapers. My hosting provider GoDaddy kept me completely busy.</p>
<p>As almost everybody ;-) in the web world I also got my due share of problems from Go Daddy. It all started with trying to host multiple domains using the same hosting account. Economy pack didn&#8217;t have multiple hosting option and I was asked to upgrade to next higher plan by paying more bucks. Without spending much time on research I paid the amount. How stupid I was!
<div class="wp-caption alignright"><img class="alignright size-full wp-image-298" title="Poor Hosting Provider" src="http://javapapers.com/wp-content/uploads/2009/12/dilbert1.png" alt="" width="176" height="300" /></div>
<p>What I finally got was a hosting account mapped to one primary domain with all the sub domains visible through the primary one! I raised support requests. I got prompt replies. But I feel like yelling here. All the replies I got are from their robots! Can you imagine they have a software robot to reply for customers. If their robot is that much intelligent they need not be in hosting business. They would be providing software products for NASA.</p>
<p>It just grabs the keywords and responds with same pre-formatted template replies. I tried my BEST to reach a real person and all went in vain. This is what triggered me to look for options. One more issue I was living with from day one is too much advertisement. Their control panel is a crap. To find even a log out link it will take minutes. I was with Godaddy for atleast three years and got used to this interface nightmare.</p>
<p>One more issue (problems list with Godaddy is quite long) was, I am not able to map to a third part DNS server for a domain name. I had a domain registered with them and I was trying to point it to a third party hosting provider. Initially it gets set. But after a week or so (I am not able to find out the window period) they reset it to their own DNS server and a default page, which has tons of garbage advertisements.</p>
<p>I tried couple of times to point it back to my server, but I think they have a cron job to redo it again on a defined interval. This is a serious issue in the hosting world. I know this might be a very odd case but the real problem is I couldn&#8217;t get help from their support staff. Finally I was determined to ditch Godaddy and move to a new hosting provider.</p>
<p>This time I did volume of research on hosting providers. Cheap providers are off my list and I had quality as first criteria. I got some three providers. Then finally narrowed down it to mediatemple. Yes it is little heavy on bills, but I heard every penny is worth it. Multiple domain hosting option is a real carrot from them and the clean plesk control panel. I took the bait.</p>
<p>It was a very difficult process from moving the application, data from one hosting provided to another. Main thing is to avoid the downtime in between. You migth blackout and that might cause serious damage to rankings in search engines. I had to go through volume of blog posts and help documents. Finally I got succeeded without any damage.</p>
<p>In transfer of data, mediatemple phpmyadmin&#8217;s response is slow. Sometimes even I thought server is down. This is the only issue I got so far. As data import is a very rare job, I am not much worried about it. It is smooth sailing thereafter. Its been a week and there is no incident. We need to wait and see for performance of the mediatemple&#8217;s famed servers.</p>
<p>Voila, now javapapers is served to you from mediatemple. Of course with little extra cost for which I got extra quality. I got clean interface to deal with, excellent multiple site hosting option and above all a real person to get support. Do you realize that the pages are rendered quicker by fraction of a second ;-) Bye bye Godaddy.</p>
<p>Wish you a Happy New Year 2010!</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-knowledge">
<ul class="socials">
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Bye+bye+GoDaddy+-+http://javapapers.com/core-java/bye-bye-godaddy/&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!">Tweet This!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://javapapers.com/core-java/bye-bye-godaddy/&amp;t=Bye+bye+GoDaddy" rel="nofollow" class="external" title="Share this on Facebook">Share this on Facebook</a>
		</li>
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://javapapers.com/core-java/bye-bye-godaddy/&amp;title=Bye+bye+GoDaddy" rel="nofollow" class="external" title="Digg this!">Digg this!</a>
		</li>
		<li class="shr-delicious">
			<a href="http://delicious.com/post?url=http://javapapers.com/core-java/bye-bye-godaddy/&amp;title=Bye+bye+GoDaddy" rel="nofollow" class="external" title="Share this on del.icio.us">Share this on del.icio.us</a>
		</li>
		<li class="shr-stumbleupon">
			<a href="http://www.stumbleupon.com/submit?url=http://javapapers.com/core-java/bye-bye-godaddy/&amp;title=Bye+bye+GoDaddy" rel="nofollow" class="external" title="Stumble upon something good? Share it on StumbleUpon">Stumble upon something good? Share it on StumbleUpon</a>
		</li>
		<li class="shr-technorati">
			<a href="http://technorati.com/faves?add=http://javapapers.com/core-java/bye-bye-godaddy/" rel="nofollow" class="external" title="Share this on Technorati">Share this on Technorati</a>
		</li>
		<li class="shr-mail">
			<a href="mailto:?subject=%22Bye%20bye%20GoDaddy%22&amp;body=Link: http://javapapers.com/core-java/bye-bye-godaddy/ (sent via shareaholic)%0D%0A%0D%0A----%0D%0A It%20was%20a%20bumpy%20ride%20in%202009.%20Many%20highs%20and%20lows.%20I%20enjoyed%20every%20moment%20of%20it.%20December%202009%20is%20an%20important%20month%20for%20javapapers.%20My%20hosting%20provider%20GoDaddy%20kept%20me%20completely%20busy.%0D%0A%0D%0AAs%20almost%20everybody%20%3B-%29%20in%20the%20web%20world%20I%20also%20got%20my%20due%20share%20of%20problems%20from%20Go%20Daddy.%20It%20all%20started%20with%20" rel="nofollow" class="external" title="Email this to a friend?">Email this to a friend?</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/core-java/bye-bye-godaddy/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
