<?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>etechGuide . . . &#187; Java</title>
	<atom:link href="http://etechGuide.in/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://etechGuide.in</link>
	<description>Know more , share more</description>
	<lastBuildDate>Fri, 25 Jun 2010 13:58:23 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating a Temporary File</title>
		<link>http://etechGuide.in/java/creating-a-temporary-file/</link>
		<comments>http://etechGuide.in/java/creating-a-temporary-file/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 06:57:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[file]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=524</guid>
		<description><![CDATA[<p>We use temporary file in our day to day applications. This post would talk on how to create a temporary file using Java Programming language. Java gives us a direct API to create a temporary file with some options.</p>
A temporary file can be created depending on certain condition and can be closed and deleted depending on some condition. For an example, lets assume we can upload and install a plug-in(a file) on an application. ]]></description>
			<content:encoded><![CDATA[<p>We use temporary file in our day to day applications. This post would talk on how to create a temporary file using Java Programming language. Java gives us a direct API to create a temporary file with some options.</p>
<p>A temporary file is a normal file that is created to hold the data temporarily. Efficient memory management is one of the important aspect of any normal application. Creation of temporary files and effective use of them help an application to free the memory in need for other purpose.</p>
<p>A temporary file can be created depending on certain condition and can be closed and deleted depending on some condition. For an example, lets assume we can upload and install a plug-in(a file) on an application. This file can be uploaded as a temporary file in a system defined temporary directory and can be installed from there. On a successful installation completion the temp file can be deleted permanently from the temporary directory.</p>
<p> Lets have a look at the following example , </p>
<h4><span style="text-decoration: underline;">Listing 1 : Creating the Temporary file</span></h4>
<pre class="brush: java">
package com.etechGuide.java.features;

import java.io.File;
import java.io.IOException;

public class TempCreation {
	public static void main(String[] args) {
		try {
			File tempFile = File.createTempFile(&quot;mailTogoa&quot;, &quot;.ddd&quot;);
			System.out.print(&quot;Created temporary file with name &quot;);
			System.out.println(tempFile.getAbsolutePath());
			tempFile.deleteOnExit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
</pre>
<p>The Line number 9 creates a temporary file. Java IO provides an API like ,<br />
createTempFile(String prefix, String suffix) ;<br />
          -Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.<br />
In the above programming example , we have used the API to create a temporary file whose prefix is mailTogoa and suffix is .ddd. This file will be created under the system defined temporary directory.<br />
Java IO provides another API to create a temporary file . With the help of this API , you can create a temporary file in user defined location. The method look like this ,<br />
createTempFile(String prefix, String suffix, File directory)<br />
           -Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.<br />
Both the above methods are public static method in the java.io.File class.</p>
<p>Line number 12 we call the deleteOnExit() method so that the temporary file can be deleted on JVM exit.</p>
<p>Last thing to be mentioned is , how to get the temporary file location pragmatically. Have a look at the following code list</p>
<h4><span style="text-decoration: underline;">Listing 2 : Detect the Temporary Directory</span></h4>
<pre class="brush: java">
package com.etechGuide.java.features;

public class DetectTempDirectory {

	private static final String SYSTEM_PROPERTY_TEMP_FOLDER = &quot;java.io.tmpdir&quot;;

	public static void main(String[] args) {
		String sTempFolder = System.getProperty(SYSTEM_PROPERTY_TEMP_FOLDER);
		System.out.println(sTempFolder);
	}
}
</pre>
<p> java.io.tmpdir property has the operating system specific temporary directory location. In the above example , we have read the property and printed on console.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fcreating-a-temporary-file%2F&amp;linkname=Creating%20a%20Temporary%20File"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/creating-a-temporary-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Story behind start() and run() methods of Java Thread</title>
		<link>http://etechGuide.in/java/story_behind_start_and_run_method_thread/</link>
		<comments>http://etechGuide.in/java/story_behind_start_and_run_method_thread/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 06:58:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=448</guid>
		<description><![CDATA[<p>The basic concept of creating a java thread is to extend the class java.lang.Thread or to implement java.lang.Runnable interface. In both the cases , implementation of run() method is mandatory for your thread to be a meaningful Thread.</p>
<p>The run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? What are the problems if we do so ? </P>
<p>Click below to have a look at the detail explanation.</p>]]></description>
			<content:encoded><![CDATA[<p>The basic concept of creating a java thread is to extend the class java.lang.Thread or to implement java.lang.Runnable interface. In both the cases , implementation of run() method is mandatory for your thread to be a meaningful Thread.</p>
<p>But , how do you execute a thread successfully ? Take an example of the class below. This is a thread for installation purpose.</p>
<h4><strong><span style="text-decoration: underline;">Listing 1 : Install Thread</span> </strong></h4>
<pre class="brush: java">
public class InstallThread extends Thread {

	public InstallThread(String threadName){
		super(threadName);
	}

	@Override
	public void run() {
		super.run();
		System.out.println(&quot;installing......&quot;);
	}

}
</pre>
<p>The above class does not install anything but gives you an impression of how to create a basic thread. You must have to give an implementation of the run() method.</p>
<p>Have a look at the following class where the instance of the install thread will be created and <em>started</em>.</p>
<h4><strong><span style="text-decoration: underline;">Listing 2 : Start the Install Thread</span> </strong></h4>
<pre class="brush: java">
public class InstallThreadTest {

	public static void main(String[] args) {
		InstallThread installThread = new InstallThread(&quot;Install Thread;&quot;);
		installThread.start();
		System.out.println(&quot;Installed.&quot;);
	}
}
</pre>
<p> We have started the thread using the start() method of the Thread class rather using the public run() method of the thread we have created.Why it&#8217;s only proper to call the start() method to start the thread instead of calling the run() method directly?</p>
<p>Because the run() method is not an ordinary class method. It should only be called by the Java Virtual Machine(JVM). We write threads because we want multi-threading in most of the cases. Writing thread classes is not about a single sequential thread, it&#8217;s about the use of multiple threads running at the same time and performing different tasks in a single program.
</p>
<p>The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. Improvement in the performance can be achieved by doing so.</p>
<p>You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller&#8217;s thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready.<br />
               </P></p>
<p>Here is a twist. Don&#8217;t expect your run method to be executed for all the treads in the same order of start() method execution. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. </p>
<p>The JVM must implement a scheduling mechanism that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fstory_behind_start_and_run_method_thread%2F&amp;linkname=Story%20behind%20start%28%29%20and%20run%28%29%20methods%20of%20Java%20Thread"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/story_behind_start_and_run_method_thread/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Version Control in Java Serialization &#8211; serialVersionUID</title>
		<link>http://etechGuide.in/java/version-control-in-java-serialization-serialversionuid/</link>
		<comments>http://etechGuide.in/java/version-control-in-java-serialization-serialversionuid/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 10:50:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[version control]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=401</guid>
		<description><![CDATA[In my last post on java object serialization , I have explained how to write an object to an object stream and how to read the object state under a different java virtual machine. Lets assume, we have created a class and instantiated it and serialized(Written the state to the file system) it too. Now [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post on <a href="http://etechguide.in/java/java-object-serialization-developers-guide/">java object serialization</a> , I have explained how to write an object to an object stream and how to read the object state under a different java virtual machine. Lets assume, we have created a class and instantiated it and serialized(Written the state to the file system) it too. Now , we have updated the class file(Added a field to the class) and trying to read the state of the saved object. In this scenario, the class version of the stored object and the class version of the modified class are different. Hence we would get an exception &#8211; the java.io.InvalidClassException. This problem is called as versioning Problem.<br />
                It happens because all the serialization-capable classes are given a unique identifier. If the identifier of the class is not same as the identifier of the stored(saved) object, the exception will be thrown. This unique identifier for all the classes is maintained in a field named , <strong>serialVersionUID</strong>. If you want to get rid of the versioning problem , you need to add the unique identifier into your class and give it a some unique value.This would always ensure that the class version and the saved object version are always the same , irrespective of changes you make in the class file.<br />
                At this point the question could be , how to add the unique value to the variable serialVersionUID. Don&#8217;t worry , whenever you create a class which implements java.io.serializable marker interface , the class become serialization-capable class. Java compiler assigns a unique identifier against each serialization-capable class. you can get the identifier values in the following way.<br />
                JDK distribution comes with a utility called <strong>serialver</strong> which helps you to get the identifier value. Set the JAVA_HOME variable with the correct JDK path.Open the command prompt and type the following and press Enter key,<br />
<div id="command" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="serialver -show" src="http://etechGuide.in/wp-content/uploads/2009/08/versionControl/command_windows.PNG" alt="serialver -show" title="serialver -show" width="600" height="103" /><br />
<p class="wp-caption-text">serialver -show command</p></div><br />
Pressing Enter key should popup an input window which would ask you to provide the class name to get the identifier value. Two very important things to remember here .<br />
1. You should provide fully qualified class name.<br />
2. your class name should not have the .class extension (ex &#8211; com.etechguide.java.UserObject).<br />
Provide the class name and press the Show button. An id should be populated against Serial Version field.<br />
The popup window should look like,<br />
<div id="serialver_popup_window" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="serialver popup window" src="http://etechGuide.in/wp-content/uploads/2009/08/versionControl/serialver.PNG" alt="serialver popup window" title="serialver popup window" width="492" height="103" /><br />
<p class="wp-caption-text">serialver popup window</p></div><br />
Once you get the serial version key(unique Identifier) , copy and paste it in you java class file as a part of your code.<br />
<div id="code" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="code snippet" src="http://etechGuide.in/wp-content/uploads/2009/08/versionControl/Code.PNG" alt="code snippet" title="code snippet" width="416" height="119" /><br />
<p class="wp-caption-text">code snippet</p></div><br />
If you are coding in the Eclipse IDE , as soon as you create a class which implements java.io.Serializable , you would get an warning ,<em>The serializable class UserData does not declare a static final serialVersionUID field of type long</em>. It means the compiler warns you to add the unique identifier to get rid of the versioning problems.<br />
It is worth to mention that the version will work as long as changes are compatible. Example of a compatible change is , adding a field to the class. At the same time an incompatible change is changing the object&#8217;s hierarchy or deleting fields. You can get the whole list of compatible and incompatible changes <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html">here</a>.   </p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fversion-control-in-java-serialization-serialversionuid%2F&amp;linkname=Version%20Control%20in%20Java%20Serialization%20%26%238211%3B%20serialVersionUID"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/version-control-in-java-serialization-serialversionuid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple way to Write to XML using Java</title>
		<link>http://etechGuide.in/java/xml_java_write/</link>
		<comments>http://etechGuide.in/java/xml_java_write/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 11:57:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=372</guid>
		<description><![CDATA[Often it becomes necessary for application programmer to read from or write to XML pragmatically. There are many different ways to deal with XML using Java programming language. I am going to share one of them. Let me start this post with an use case. While reading through the use case , we should learn how to use Java to write to XML file. Lets Start . . .]]></description>
			<content:encoded><![CDATA[<p>Often it becomes necessary for application programmer to read from or write to XML pragmatically. There are many different ways to deal with XML using Java programming language. I am going to share one of them. Let me start this post with an use case. While reading through the use case , we should learn how to use Java to write to XML file.</p>
<p><strong><u>Use case :</u></strong><br />
Look at the following XML file (dept_HR_Products.xml) which holds the information about different products in a department and several employees belongs to each product. The XML defines , the department dept_HR_Products has three products , product_1 , product_2 and product_3 respectively. product_1 has 2 employees , product_2 has 1 employee where product_3 has 2 employees. This XML holds the name, designation(desig in the XML), employee Id and Manager name as well.<br />
Spend some time to look and understand the XML file.</p>
<h4><strong><u>Listing 1 : dept_HR_Products.xml</u></strong></h4>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;
&lt;dept_HR_Products&gt;

	&lt;product_1&gt;
		&lt;employee&gt;
			&lt;id&gt;2345&lt;/id&gt;
			&lt;desig&gt;Associate&lt;/desig&gt;
			&lt;manager&gt;Alex Braton&lt;/manager&gt;
			&lt;name&gt;Yan Botham&lt;/name&gt;
		&lt;/employee&gt;

		&lt;employee&gt;
			&lt;id&gt;1000&lt;/id&gt;
			&lt;desig&gt;Product Manager&lt;/desig&gt;
			&lt;manager&gt;Borrek Marteen&lt;/manager&gt;
			&lt;name&gt;Krishna Sharma&lt;/name&gt;
		&lt;/employee&gt;
	&lt;/product_1&gt;

	&lt;product_2&gt;
		&lt;employee&gt;
			&lt;id&gt;122&lt;/id&gt;
			&lt;desig&gt;sse&lt;/desig&gt;
			&lt;manager&gt;Alex B&lt;/manager&gt;
			&lt;name&gt;Chand T&lt;/name&gt;
		&lt;/employee&gt;
	&lt;/product_2&gt;

	&lt;product_3&gt;
		&lt;employee&gt;
			&lt;id&gt;34&lt;/id&gt;
			&lt;desig&gt;sse&lt;/desig&gt;
			&lt;manager&gt;Vipul T&lt;/manager&gt;
			&lt;name&gt;Rahim&lt;/name&gt;
		&lt;/employee&gt;

		&lt;employee&gt;
			&lt;id&gt;340&lt;/id&gt;
			&lt;desig&gt;sse&lt;/desig&gt;
			&lt;manager&gt;Vipul T&lt;/manager&gt;
			&lt;name&gt;Sharma&lt;/name&gt;
		&lt;/employee&gt;
	&lt;/product_3&gt;

&lt;/dept_HR_Products&gt;
</pre>
<p>Lets assume , our application demands us to insert a new employee record to the XML file on click on a button from GUI. So we provide all the details like , employee ID , Designation , Name and Manager&#8217;s name from the GUI and click on the submit button to insert the employee record to XML(This is an example , I am sure that you would be having a plan of using a database to do it ). To insert the record to the XML , we need XML node notation . We need to form a node like following and write a routine to insert it ,</p>
<pre class="brush: xml">
&lt;employee&gt;
			&lt;id&gt;100&lt;/id&gt;
			&lt;desig&gt;Product Manager&lt;/desig&gt;
			&lt;manager&gt;Simon T&lt;/manager&gt;
			&lt;name&gt;Krishna Sharma&lt;/name&gt;
&lt;/employee&gt;
</pre>
<p>So , we are sure about the attributes an employee can have in our XML store. We should create a DTO(Data transfer object) for Employee which should consist all the attributes an employee can have and setters , getters method for them.<br />
A Employee DTO should look like ,</p>
<h4><strong><u>Listing 2 : Employee DTO</u></strong></h4>
<pre class="brush: java">
package com.etecguide.java.xmlWrite.dto;
import java.io.Serializable;

public class Employee implements Serializable{
	private String userName;
	private String empId;
	private String designation;
	private String manager;

	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getEmpId() {
		return empId;
	}
	public void setEmpId(String empId) {
		this.empId = empId;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
	public String getManager() {
		return manager;
	}
	public void setManager(String manager) {
		this.manager = manager;
	}
      // Overriding toString() method
	public String toString(){
		StringBuffer sb = new StringBuffer();
		sb.append(getUserName());
		sb.append(&quot;:&quot;);
		sb.append(getEmpId());
		sb.append(&quot;:&quot;);
		sb.append(getDesignation());
		sb.append(&quot;:&quot;);
		sb.append(getManager());
		sb.append(&quot;]&quot;);
		return sb.toString();

	}
}
</pre>
<p>Now , Lets get into the business. Lets have a look at the <strong>Listing 3</strong> which lists the Java code to insert a node to the XML file. Input parameters to the method are ,<br />
xmlFileName &#8211; Name of the XML File.<br />
productName &#8211; Name of the product(product_1,product_2,product_3) selected from the GUI.<br />
employee &#8211; Employee DTO object which would have populated with the employee details provided from GUI.<br />
Have a look at the following code and lets do a step-by-step analysis.</p>
<h4><strong><u>Listing 3 : Write to the XML file</u></strong></h4>
<pre class="brush: java">
public static void addToDepartment(String xmlFileName, String productName,
			Employee employee) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {

		File file = new File(xmlFileName);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(file);

		Element rootElement = doc.getDocumentElement();

		NodeList product = rootElement.getElementsByTagName(productName);

		for (int i = 0; i &lt; product.getLength(); i++) {
			Node productNode = product.item(i);

			Node empNode = doc.createElement(&quot;employee&quot;);

			Node idNode = doc.createElement(&quot;id&quot;);
			Node idTextNode = doc.createTextNode(&quot;id&quot;);
			idTextNode.setTextContent(employee.getEmpId());
			idNode.appendChild(idTextNode);

			Node desigNode = doc.createElement(&quot;desig&quot;);
			Node desigTextNode = doc.createTextNode(&quot;desig&quot;);
			desigTextNode.setTextContent(employee.getDesignation());
			desigNode.appendChild(desigTextNode);

			Node managerNode = doc.createElement(&quot;manager&quot;);
			Node managerTextNode = doc.createTextNode(&quot;manager&quot;);
			managerTextNode.setTextContent(employee.getManager());
			managerNode.appendChild(managerTextNode);

			Node nameNode = doc.createElement(&quot;name&quot;);
			Node nameTextNode = doc.createTextNode(&quot;name&quot;);
			nameTextNode.setTextContent(employee.getUserName());
			nameNode.appendChild(nameTextNode);

			empNode.appendChild(idNode);
			empNode.appendChild(desigNode);
			empNode.appendChild(managerNode);
			empNode.appendChild(nameNode);

			productNode.appendChild(empNode);
			break;
		}

		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer trs = tFactory.newTransformer();

		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new FileOutputStream(new File(
				xmlFileName)));

		trs.transform(source, result);
	}
</pre>
<p>We create a file object using the file name at the line number 5. Then create a DocumentBuilderFactory and a DocumentBuilder. We need a Document object that represents the parsed xml document. We create a Document object at the line number 8. Next Step is to get the root Element ( i.e, dept_HR_Products) and then get the list of all the nodes inside. As we know the product name , we can form a product node element to get all the child node under the specified product node. We achieve this at the line number 12.<br />
             The use of for-loop is unnecessary in this case ( as , we know the product name). We can directly get a product node using ,
<pre class="brush: java">Node productNode = product.item(0); </pre>
<p>instead of iterating through the for-loop.<br />
            Now we are going to create the node for the new employee along with the data we have passed through Employee DTO. Line 19-37 does this. We create an <employee> node and add <id> , <desig>, <name> , <manager> as a child node to it. Ultimately we add the employee node to the product node at the line number 44. Whatever we have written so far , we have written to the document , not to the XML file in the file System. The next step is to transform the document to the XML file. Here we have used javax.xml.transform.Transformer to do that.<br />
           We create a Transformer object at the line number 49 and create a Dom Source from the document at the line number 51. We create a StreamResult object using the xml file. Finally , the transformation happen at line number 55 ,
<pre class="brush: java">trs.transform(source, result);</pre>
<p>.With this the new node for employee should be written to the XML file.<br />
          There could be several other ways to do the same. One should change the above code depending on the structure of the node in the XML. Best of luck for your all future insertion to the XML. Share your views and ideas to do insert to the XML using different techniques.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fxml_java_write%2F&amp;linkname=Simple%20way%20to%20Write%20to%20XML%20using%20Java"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/xml_java_write/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Java Object Serialization &#8211; Developer&#8217;s Guide</title>
		<link>http://etechGuide.in/java/java-object-serialization-developers-guide/</link>
		<comments>http://etechGuide.in/java/java-object-serialization-developers-guide/#comments</comments>
		<pubDate>Thu, 16 Jul 2009 09:19:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=323</guid>
		<description><![CDATA[Class is the heart of Java programming and object is a representative of the class. In day to day java programming , we create object and use that in different way.But the life span of an object is till the JVM(Java Virtual Machine) is up. Once JVM is down , there is no existence of the object you have created.But Java has a mechanism which allows you to store(save) your object ( let me say, object state) and you can use the stored object under a different JVM , in a different application or after restarting your own JVM. Isn't it cool ? Read this post to start with Java Serialization API.]]></description>
			<content:encoded><![CDATA[<p>Class is the heart of Java programming and object is a representative of the class. In day to day java programming , we create object and use that in many different ways.But the life span of an object is till the JVM(Java Virtual Machine) is up. Once JVM is down , there is no existence of the object you have created.But Java has a mechanism which allows you to store(save) your object ( let me say, object state) and you can use the stored object under a different JVM , in a different application or after restarting your own JVM. Isn&#8217;t it cool ? This mechanism (let me call it , API) is called <strong>Java Serialization API </strong> which is really small, strong and easy to use.<br />
<div id="objSerialization" class="wp-caption alignleft" style="width: 610px"><br />
<img class="size-full wp-image-38" title="Object Serialization" src="http://etechGuide.in/wp-content/uploads/2009/07/Object_Serialization/Object_Serialization.jpeg" alt="Object Serialization" title="Object Serialization" width="516" height="311" /><br />
<p class="wp-caption-text">Object Serialization</p></div><br />
Object serialization is the process of saving an object state to the sequence of bytes and restoring the object state after rebuilding those bytes together for any future use. let me start with the basic process of object serialization.An object of a class can be made serialized if the class implements a marker interface <strong>java.io.Serializable</strong>.<br />
Lets Create an User class to serialize the User object and restore it to use in the future. As mentioned , User class should implement java.io.Serializable marker interface to serialize the User class object.</p>
<h4><u>Listing 1 : Create a User class which implements java.io.Serializable</u></h4>
<pre class="brush: java">
package com.etechguide.java.serialization;

import java.io.Serializable;
import java.util.Date;

public class UserData implements Serializable {
	// Name of the User
	private String userName;
	// Employee Id of the User
	private String empId;
	// Creation date of the User in the database
	private Date creationDate;
	// Default constructor
	public UserData(){

	}
	/**
	 * Method to get the User Name
	 * @return String
	 */
	public String getUserName() {
		return userName;
	}
	/**
	 * Method to get the Employee Id
	 * @return String
	 */
	public String getEmpId() {
		return empId;
	}
	/**
	 * Method to get the User Creation
	 * Date and time
	 * @return java.util.Date instance
	 */
	public Date getCreationDate() {
		return creationDate;
	}
	/**
	 * Method to set the User name
	 * @param userName
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}
	/**
	 * Method to set the Employee Id
	 * @param empId
	 */
	public void setEmpId(String empId) {
		this.empId = empId;
	}
	/**
	 * Method to set the user creation
	 * Date and time
	 * @param creationDate
	 */
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
}
</pre>
<p>We would serialize the User object in the form of bytes to the file system. Remember Java i/o programming for file reading and writing ? Yes , we are going to do something of that sort. Look at the following code which should serialize the User object to a file system file , say , user.ser.</p>
<h4><u>Listing 2 : Serializing the User object to file system file user.ser</u></h4>
<pre class="brush: java">
package com.etechguide.java.serialization;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

public class PersistUser {

	public static void main(String[] args) {
		String fileName = &quot;user.ser&quot;;
		String userName = &quot;admin&quot;;
		String empId = &quot;889776&quot;;
		Date userCreationDate = new Date();

		UserData userData = new UserData();
		FileOutputStream fos = null;
		ObjectOutputStream out = null;

		try {
			fos = new FileOutputStream(fileName);
			out = new ObjectOutputStream(fos);
			userData.setUserName(userName);
			userData.setEmpId(empId);
			userData.setCreationDate(userCreationDate);
			out.writeObject(userData);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
</pre>
<p>Look at the line number 27 in <strong>Listing 2</strong> .The method writeObject(Object object) does the main tricks of writing object&#8217;s state to file system in the form of sequence of bytes.We have created on User object at the line number 17 and set the values to it.We have created java.io.FileOutputStream object and java.io.ObjectOutputStream object to call the writeObject method. Once run the above main() method , one file called user.ser should be created. This file would have all the state stored for the user object. You can take this file (user.ser) to any other Jvm , any other application and restore the User object state to use it further.Before we proceed to restore the state of the User object under a new jvm or a new application , there are few things to remember and take care.<br />
1. You should have the User.java class accessible to the new Jvm or the new application to restore the object&#8217;s state.You can access the class from a jar file in your new environment.<br />
2. User Object class files and the methods are not saved into the user.ser file , only the state of the Object which is saved.<br />
If you have understood both the pointers stated above , lets go ahead and restore the object information.</p>
<h4><u>Listing 3 : Restoring the User object state from user.ser</u></h4>
<pre class="brush: java">
package com.etechguide.java.serialization;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Date;

public class RestoreUserState {

	public static void main(String[] args) {
		// Specify the full path of the
		// user.ser file
		String filename = &quot;user.ser&quot;;
		UserData userData = null;
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(filename);
			in = new ObjectInputStream(fis);
			userData = (UserData) in.readObject();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(&quot;Accessing Date and Time = &quot; + new Date().toString());
		System.out.println(&quot;user name = &quot; + userData.getUserName());
		System.out.println(&quot;emp id = &quot; + userData.getEmpId());
		System.out.println(&quot;creation Date and Time = &quot;
				+ userData.getCreationDate().toString());
	}
}
</pre>
<p>Look at the line number 20 in the <strong>Listing 3</strong>.This is where the restoration is taking place.Look more closely to understand , we are casting the return type of readObject method to the User type.It is why we need the access to User class in the new jvm / new application.in.readObject() returns a java.lang.Object by-default. lets run the program and see the output.<br />
<strong><u>Output :</u></strong><br />
<span class='output'><br />
Accessing Date and Time = Thu Jul 16 13:07:02 IST 2009<br />
user name = admin<br />
emp id = 889776<br />
creation Date and Time = Thu Jul 16 12:28:21 IST 2009<br />
</span><br />
It is clear from output of the program , User object&#8217;s state was saved at Thu Jul 16 12:28:21 IST 2009 with information like user name = admin and employee id=889776. We can clearly see the difference between the time we restore the User object , i.e , Thu Jul 16 13:07:02 IST 2009 and the creation time.<br />
So intention is clear now. We have tried to create an User object with it&#8217;s user name , employee id and creation date properties . Then we saved the state of it to the file system and restored it for future use. Cool , huh ? The basic process of doing object serialization is very simple and straight-forward. But there are few more things that we should know about object serialization.</p>
<h4><u>Learning 1 : java.lang.Object is not Serializable</u></h4>
<p>Parent call of all java class is java.lang.Object. Object class does not implement the marker interface java.lang.Serializable , hence a direct object of java.lang.Object class can not be serialized. So why all java objects can not be serialized automatically. But there are plenty ready made serialized type available in java. Few of them are array , String , Swing components etc. </p>
<h4><u>Learning 2 : Do Thread serializable?</u></h4>
<p>The answer is No. Thread is not serializable like Socket.No one would try to use the Thread belongs to one application under one jvm to another jvm for another application.</p>
<h4><u>Learning 3 : Want to serialize an object which has a non-serializable field.</u></h4>
<p>Yes , you can serialize an object which has a non-serializable state declared like instance of a Thread. But there is a difference. You have to mark the variable declaration as,<br />
<strong>transient</strong> private Thread myThread explicitly. look at the declaration, the key word transient to force the java serialization not to store the state of the field while storing the object&#8217;s state.</p>
<h4><u>Learning 4 : I would like to serialize an object and send through metwork.</u></h4>
<p>Yes possible. One of the main purpose of using Java Serialization mechanism is , one should serialize / de-serialize the object network.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fjava-object-serialization-developers-guide%2F&amp;linkname=Java%20Object%20Serialization%20%26%238211%3B%20Developer%26%238217%3Bs%20Guide"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/java-object-serialization-developers-guide/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Reflection Mechanism</title>
		<link>http://etechGuide.in/java/reflection/</link>
		<comments>http://etechGuide.in/java/reflection/#comments</comments>
		<pubDate>Wed, 27 May 2009 06:47:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=191</guid>
		<description><![CDATA[Can you ever think of writing a Java program without a class ? I know the answer is 'NO'. As a class is the heart of the java program , it is always good to know about the in and out of the class. Java provides a very ordinary(but strong enough) API to know more about java classes , methods and fields. This API is known as Java Reflection API. Don't you wonder how Eclipse IDE gives you the Auto complete feature ? How web application deployment descriptor (web.xml for tomcat) works ? The basic answer is REFLECTION. Have a look.]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Java Reflection - Class and Instantiate Objects--></p>
<p>Java reflection API provides a way to know more about your own class which includes methods and fields. The power of reflection helps you load a class dynamically , create an object of a class at the run time , inspect your fields , methods and modifiers at the run time and many more.There are few draw-backs of the Java Reflection and we are going to discuss that at the end of this tutorial. Lets start with a very simple way to know about your class , super class and modifiers.</p>
<h4>Listing 1 : Know about class , super class and modifiers</h4>
<pre class="brush: java">
private static void getBasicClassInfo() {

// User is a class in package com.etechguide.java.reflection
User user = new User();
Class klass = user.getClass();
// Another way of getting class object
// Class klass = User.class;
Class superKlass = klass.getSuperclass();
int modifier = klass.getModifiers();
System.out.println(&quot;Class is :&quot; + klass);
System.out.println(&quot;Super Class of User Class is :&quot; + superKlass);
System.out.println(&quot;Is Public Class : &quot; + Modifier.isPublic(modifier));
System.out.println(&quot;Is final Class : &quot; + Modifier.isFinal(modifier));
System.out.println(&quot;Is Abstract Class : &quot;
+ Modifier.isAbstract(modifier));

}
</pre>
<p>Have a look at the code in <strong>Listing 1</strong> . At the line number 3 we create an object of a class User which is under a package say , com.etechguide.java.reflection. At the line number 4 we create a java.lang.Class object(klass) from the user object.This class object(klass) gives us the handle to get all the information of the User class.At the line number 7 we get the super class of the class User and we use the java.lang.reflect.Modifier from reflection API at the line number 11 , 12 and 13 to know if the class is final public , final or abstract.Modifier class uses the integer flag to determine the type modifier of the class.<br />
<strong><span style="text-decoration: underline;">output :</span> </strong><br />
<span class="output"><br />
Class is :class com.etechguide.java.reflection.User<br />
Super Class of User Class is :class java.lang.Object<br />
Is Public Class : true<br />
Is final Class : false<br />
Is Abstract Class : false</span><br />
java.lang.Class object can be archived in two other ways.Lets have a look at the following code below ,</p>
<h4>Listing 2 : Know about Class.forname</h4>
<pre class="brush: java">
private static Object instantiateUserWithDefaultConstructor()
throws ClassNotFoundException, InstantiationException,
IllegalAccessException {

Class klass = Class.forName(&quot;com.etechguide.java.reflection.User&quot;);
Object userObj = klass.newInstance();
// This will call the toString method of User Object
System.out.println(&quot;User object created : \n&quot; + userObj);
return userObj;
}
</pre>
<p>At the line number 5 , we create a java.lang.Class object by using Class.forname(class_name) method. forname(class_name) is a static method of the class java.lang.Class.Point to remember is forname(class-name) method takes a String class name as argument and create the java.lang.Class object. The class name passed as an argument to the method , should be a fully qualified class name ( with full package name) not a class name alone.<br />
At the line number 6 , we create an instance of the class User. The java.lang.Class object for the class com.etechguide.java.reflection.User is the klass and we create an instance of com.etechguide.java.reflection.User by calling klass.newInstance().<br />
<strong><span style="text-decoration: underline;">output :</span> </strong><br />
<span class="output"><br />
The output of the program should be the toString method called on the User object.<br />
</span><br />
It&#8217;s time to go deep into reflection and get more details on the classes and objects. In my last two example codes in <strong>Listing 1</strong> and <strong>Listing 2</strong> , I have used a class called com.etechguide.java.reflection.User.  Lets have a full picture of the com.etechguide.java.reflection.User class .</p>
<h4>Listing 3 : User class</h4>
<pre class="brush: java">

package com.etechguide.java.reflection;

import java.math.BigDecimal;

public class User {

private String userId;
private String userName;
private String userAddress;
private String phoneNumber;
private BigDecimal income;
private boolean isMarried;

public User() {
super();
System.out.println(&quot;Creating object with default constructor ... &quot;);
userId = &quot;admin&quot;;
userName = &quot;Administrator&quot;;
userAddress = &quot;Geneva&quot;;
phoneNumber = &quot;001384959569&quot;;
income = new BigDecimal(356786);
isMarried = true;
}

public User(String userId, String userName, String userAddress,
String phoneNumber, BigDecimal income, boolean isMarried) {
System.out
.println(&quot;Creating object with parameterized constructor ... &quot;);
this.userId = userId;
this.userName = userName;
this.userAddress = userAddress;
this.phoneNumber = phoneNumber;
this.income = income;
this.isMarried = isMarried;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserAddress() {
return userAddress;
}

public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public BigDecimal getIncome() {
return income;
}

public void setIncome(BigDecimal income) {
this.income = income;
}

public boolean isMarried() {
return isMarried;
}

public void setMarried(boolean isMarried) {
this.isMarried = isMarried;
}

public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(&quot;userId &quot; + userId + &quot;\n&quot;);
buffer.append(&quot;userName &quot; + userName + &quot;\n&quot;);
buffer.append(&quot;userAddress &quot; + userAddress + &quot;\n&quot;);
buffer.append(&quot;phoneNumber &quot; + phoneNumber + &quot;\n&quot;);
if (income != null)
buffer.append(&quot;income &quot; + income.intValue() + &quot;\n&quot;);
buffer.append(&quot;isMarried &quot; + isMarried);
return buffer.toString();
}

private void SOP(String message) {
System.out.println(&quot;SOP Message&quot;);
System.out.println(message);
}

}
</pre>
<p>Our next target is to use java reflection to instantiate the User class by using the parameterized constructor of User class. Have a look at the following code in the next page .</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Freflection%2F&amp;linkname=Java%20Reflection%20Mechanism"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/reflection/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Custom Exception in Java</title>
		<link>http://etechGuide.in/java/custom-exception-in-java/</link>
		<comments>http://etechGuide.in/java/custom-exception-in-java/#comments</comments>
		<pubDate>Tue, 26 May 2009 08:24:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[exception]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=177</guid>
		<description><![CDATA[When a program violates the constraints of Java programing language , Java virtual machine(JVM) throws an error signal to the program. These signals are known as Exception in Java programing language. Excpetions are of two types. Checked (Compile-time) exception and un-checked(run-time) exception. JVM has a collection of exceptions that will be thrown at compile time with the exception message and the print stack trace. A developer can create their own exception which is closely related to the application he or she is developing. A Custom exception can be used to form a better customized message to the user of your application. Have a look.]]></description>
			<content:encoded><![CDATA[<p>When a program violates the constraints of Java programing language , Java virtual machine(JVM) throws an error signal to the program. These signals are known as Exception in Java programing language. Excpetions are of two types. Checked (Compile-time) exception and un-checked(run-time) exception. JVM has a collection of exceptions that will be thrown at compile time with the exception message and the print stack trace. A developer can create their own exception which is closely related to the application he or she is developing.<br />
To create a custom exception , the custom exception class has to extend java.lang.Exception class.</p>
<pre class="brush: java">
public class MyException extends Exception{
// Your code goes here.
}
</pre>
<p>Lets take an example of an application which transfers the money from one account to another.The application enforces two constraints while the transfer take place.<br />
constraints 1 : The amount of money to be transferred should be greater than 100 rs. (INR) per transaction.<br />
constraints 2 : The amount of money to be transferred should be lesser than 25,000 rs (INR) per transaction.<br />
Lets create a MoneyTransferException class which extends java.lang.Exception class</p>
<h4>Listing 1 : MoneyTransferException.java</h4>
<pre class="brush: java">
package com.etechguide.java.exception;
public class MoneyTransferException extends Exception {
private static final long serialVersionUID = 1L;
public MoneyTransferException() {
// Constructor without a message
super();
}
public MoneyTransferException(String transferMsg){
// Constructor with a message
super(transferMsg);
}
}
</pre>
<p>Now we need two different kind of exceptions that can be thrown when,<br />
1. Transfer amount reached below 100 rs. (MinMoneyTransferException)<br />
2. Transfer amount reached above 25,000 rs. (MaxMoneyTransferException)<br />
Lets create both the classes which extends MoneyTransferException created in Listing 1.</p>
<h4>Listing 2 : MinMoneyTransferException.java</h4>
<pre class="brush: java">
package com.etechguide.java.exception;
public class MinMoneyTransferException extends MoneyTransferException {
private static final long serialVersionUID = 1L;
public MinMoneyTransferException() {
super();
System.out.println(&quot;Minimum limit has been reached&quot;);
}
public MinMoneyTransferException(String minTransferMsg){
super(minTransferMsg);
}
}
</pre>
<h4>Listing 3 : MaxMoneyTransferException.java</h4>
<pre class="brush: java">
package com.etechguide.java.exception;
public class MaxMoneyTransferException extends MoneyTransferException {
private static final long serialVersionUID = 1L;
public MaxMoneyTransferException() {
super();
System.out.println(&quot;Max limit has been reached..&quot;);
}
public MaxMoneyTransferException(String maxTransferMsg){
super(maxTransferMsg);
}
}
</pre>
<p>Now we will use these two exceptions in our program to validate that no transaction should take place if it violates the above constraints.</p>
<h4>Listing 4 : MoneyTransferTest.java</h4>
<pre class="brush: java">

package com.etechguide.java.exception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MoneyTransferTest {

/**
* A method which transfer money
* @param amount - to be transferred
* @throws MinMoneyTransferException - If amount is less than 100
* @throws MaxMoneyTransferException - If amount is greater than 25000
*/
private void transferMoney(long amount) throws
MinMoneyTransferException, MaxMoneyTransferException{

// Transfer should occur is the amount to be transferred
// is within the range of 100 and 25000.

if(amount &gt;= 100 &amp;&amp; amount &lt;= 25000){
System.out.println(&quot;Transfer amount is correct&quot;);
System.out.println(&quot;System is ready for transfer&quot;);
}
// Amount is less than 100. Lets throw an exception
//, i.e , MinMoneyTransferException
if(amount &lt;100){
throw new MinMoneyTransferException
(&quot;The amount &quot;+amount+&quot; rs. is too less to transfer.Minimum limit is 100 rs.&quot;);
}

// Amount is greater than 25000.
// Lets throw an exception , i.e , MaxMoneyTransferException

if(amount &gt; 25000){
throw new MaxMoneyTransferException
(&quot;The amount &quot;+amount+&quot; rs. is more than 25,000 rs.Maximum limit is 25,000 rs.&quot;);
}
System.out.println(&quot;Money has been transferred successfully&quot;);
}

// Main method

public static void main(String[] args) {
MoneyTransferTest moneyTransferTest = new MoneyTransferTest();
// prompt the user to enter the Transfer amount
System.out.print(&quot;Enter the transfer amount: &quot;);
// open up standard input
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
String amount = null;
// read the amount from the command-line
try {
amount = br.readLine();
Long amountL = new Long(amount);
moneyTransferTest.transferMoney(amountL.longValue());
} catch (MinMoneyTransferException e) {
System.out.println(e.getMessage());
} catch (MaxMoneyTransferException e) {
System.out.println(e.getMessage());
} catch (IOException ioe) {
System.out.println(&quot;IO error trying to read the amount!&quot;);
System.exit(1);
}
}

}
</pre>
<p>Lets run the program MoneyTransferTest.java in Listing 4 for three different amount of transfer,<br />
80 rs , 23434 rs and 34564 rs.<br />
<strong>Output</strong> (for 80 rs):<br />
Enter the transfer amount: 80<br />
The amount 80 rs. is too less to transfer.Minimum limit is 100 rs.<br />
<strong>Output </strong>(for 23434 rs):<br />
Enter the transfer amount: 23434<br />
Transfer amount is correct<br />
System is ready for transfer<br />
Money has been transferred successfully<br />
<strong>Output</strong> (for 34564 rs):<br />
Enter the transfer amount: 34564<br />
The amount 34564 rs. is more than 25,000 rs.Maximum limit is 25,000 rs.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fcustom-exception-in-java%2F&amp;linkname=Custom%20Exception%20in%20Java"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/custom-exception-in-java/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Reading a Manifest file from Jar file</title>
		<link>http://etechGuide.in/java/reading_a_manifest_file_from_jar_file/</link>
		<comments>http://etechGuide.in/java/reading_a_manifest_file_from_jar_file/#comments</comments>
		<pubDate>Wed, 13 May 2009 10:55:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Manifest]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=153</guid>
		<description><![CDATA[When a JAR file is created, it automatically bundles a default manifest file. There can be only one manifest file in a jar archive, and it always has the path name META-INF/MANIFEST.MF. This post describes , how to read the Manifest.MF file from a Jar file. Have a look at it.]]></description>
			<content:encoded><![CDATA[<p>When a JAR file is created, it automatically bundles a default manifest file. There can be only one manifest file in a jar archive, and it always has the path name META-INF/MANIFEST.MF. This post describes , how to read the Manifest.MF file from a jar file. A jar file can support huge range of functionality like , version control , main class defination , electronic signing etc. All these functionality can be achieved through Manifest.MF. A Jar builder post all the required information about the Jar in Manifest.MF file and an application developer would read the Manifest.MF to retrieve the information and work on it.</p>
<p>A simple Manifest.MF would look like this ,</p>
<pre class="brush: bash">

Manifest-Version: 1.0
Main-Class: com.etechguide.java.feature.IdentityNeeded
Name: etechguide/Manifest/
Sealed: true
Specification-Title: &quot;Teaching manifest&quot;
Specification-Version: &quot;1.1&quot;
Implementation-Vendor: &quot;http://etechGuide.in&quot;
</pre>
<p>Lets see how to read some of these properties at runtime and do something useful.<br />
Let us assume we have a jar file named etechguide.jar which has a Manifest.MF file with following specifications,</p>
<pre class="brush: bash">

Manifest-Version: 1.0
Main-Class: com.etechguide.expert.IdentityNeeded
Implementation-Vendor: &quot;http://etechGuide.in&quot;
</pre>
<p>Manifest-Version is the Version of the application given as a Jar. Main-Class is the entry point to the application. It should have a full qualified class name and the class should have a public static void main(String []args) method.Implementation-Vendor is the  the application/jar provider.<br />
Say ,com.etechguide.expert.IdentityNeeded Class look like as ,</p>
<pre class="brush: java">
package com.etechguide.expert

public class IdentityNeeded {
public void someMethod(){
System.out.println(&quot;I do not do anything.&quot;);
}
public static void main(String args[]){
System.out.println(&quot;I need Identity&quot;);
}
}
</pre>
<p>Our intention is to read the Manifest.MF file from the etechGuide.jar file and instantiate the Main-class , i.e , com.etechguide.expert.IdentityNeeded and call it&#8217;s main method.<br />
Lets read the manifest file first,</p>
<pre class="brush: java">
public static final String MANIFEST = &quot;META-INF/MANIFEST.MF&quot;;
public static final String MAIN_CLASS = &quot;Main-Class&quot;;

public String readManifest(JarFile jar) throws IOException {
String mainClass = null;
ZipEntry zipEntry = jar.getEntry(MANIFEST);
if (zipEntry == null) {
// Throw some customized exception here
}
InputStream inputStream = jar.getInputStream(zipEntry);
BufferedReader reader = null;
String key = null;
String value = null;
String lineReader = null;
int inx;
reader = new BufferedReader(new InputStreamReader(inputStream));
// Parsing the Manifest information

while ((lineReader = reader.readLine()) != null &amp;&amp; lineReader.length() &gt; 0) {
if ((inx = lineReader.indexOf(&quot;:&quot;)) &gt; 0) {
key = lineReader.substring(0, inx);
value = lineReader.substring(inx + 1).trim();
} else if (lineReader.charAt(0) == &#039; &#039;) {
value += lineReader.substring(1);
} else {
key = value = &quot;&quot;;
continue;
}
if (key.equalsIgnoreCase(MAIN_CLASS)) {
mainClass = value;
break;
}
}
inputStream.close();
reader.close();
jar.close();

return mainClass;
}
</pre>
<p>The above method takes a JarFile as an input parameter and parse the Manifest.MF file to return the mainClass which is<br />
com.etechguide.expert.IdentityNeeded in this example.<br />
Now you can instantiate the class to call it&#8217;s methods as ,</p>
<pre class="brush: java">
Class cls = Class.forName(mainClass);
IdentityNeeded identityNeeded = (IdentityNeeded) cls.newInstance();
identityNeeded.main(null); // This would call your main method
identityNeeded.someMethod(); // Some other public method can be accessed in this way.
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Freading_a_manifest_file_from_jar_file%2F&amp;linkname=Reading%20a%20Manifest%20file%20from%20Jar%20file"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/reading_a_manifest_file_from_jar_file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Static Import</title>
		<link>http://etechGuide.in/java/java-static-import/</link>
		<comments>http://etechGuide.in/java/java-static-import/#comments</comments>
		<pubDate>Thu, 30 Apr 2009 06:38:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[static import]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=105</guid>
		<description><![CDATA[Java 5 introduces a feature of importing static member of other class without qualifying by the class name. We should not keep any static member in an interface and then inherit from that rather it is a better idea to import them to a new class.This post illustrates the step-by-step procedure to achieve it.]]></description>
			<content:encoded><![CDATA[<p>This tutorial gives an idea on a feature introduced in Java 5 , Static Import  . In order to access static member of a class ,it is recomended to qualify the references by the class they belongs to.<br />
For an example ,
<pre class="brush: java">Math.sqrt(Math.pow(45, 2));</pre>
<p> &#8211; here sqrt and pow are the static methods of the class Math.<br />
A static import allows unqualified access to static member of a class.We should not keep any static member in an interface and then inherit from that rather it is a better idea to import them to a new class.<br />
Static import can be achieved in two ways,<br />
1. Single static import &#8211; Import a particular static member of a class.</p>
<pre class="brush: java">import static packageName.ClassName.staticMemberName;</pre>
<p>For an example , if you want to access Math class&#8217;s static member sqrt and pow the import should be,</p>
<pre class="brush: java">
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
</pre>
<p>2. Static import on demand &#8211; Import all static member of a class.</p>
<pre class="brush: java">
import static packageName.ClassName.*;
</pre>
<p>In this case the import should be import static
<pre class="brush: java">java.lang.Math.*</pre>
<p>Have look at the following codes :</p>
<p>This is a class with Static methods :</p>
<pre class="brush: java">
package com.etechguide.java.feature;
public class ClassWithStaticMembers {
public static void talk(){
System.out.println(&quot;I am talking&quot;);
}
public static void walk(){
System.out.println(&quot;I am walking&quot;);
}
}
</pre>
<p>This is a class with Static veriables :</p>
<pre class="brush: java">
package com.etechguide.java.feature;
public class ClassWithStaticVers {
public static String fruit = &quot;Apple&quot;;
public static String name = &quot;Anthony&quot;;
public static String state = &quot;green&quot;;
}
</pre>
<p>This class is making use of the static import</p>
<pre class="brush: java">
package com.etechguide.java.feature;
import static com.etechguide.java.feature.ClassWithStaticMembers.talk;
import static com.etechguide.java.feature.ClassWithStaticVers.*;
public class StaticImport {
public static void main(String[] args) {
talk(); // A static method from the class ClassWithStaticMembers in the package
// com.etechguide.java.feature
// Walk(); This also a staic method of the class ClassWithStaticMembers but not
// accessible as we have not imported it. To access this method ,
ClassWithStaticMembers.walk();

//Here accessing all the static variables of the class  ClassWithStaticVers

System.out.println(name + &quot; loves &quot; + state +&quot; &quot;+ fruit);

}
}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fjava-static-import%2F&amp;linkname=Java%20Static%20Import"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/java-static-import/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singleton &#8211; What it is and why is Singleton ?</title>
		<link>http://etechGuide.in/java/singleton-what-it-is-and-why-is-singleton/</link>
		<comments>http://etechGuide.in/java/singleton-what-it-is-and-why-is-singleton/#comments</comments>
		<pubDate>Fri, 24 Apr 2009 09:15:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://etechGuide.in/?p=65</guid>
		<description><![CDATA[Sometimes it&#8217;s the requirement of the application to maintain only one instance of a class . This instance will be accessed throughout the a software life cycle of the application.This type of classes are called Singleton class.
Typical examples could be ,Logger,Print spoolers,Connection pool etc.
Singleton is ideal if an application developer wants to make sure only [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes it&#8217;s the requirement of the application to maintain only one instance of a class . This instance will be accessed throughout the a software life cycle of the application.This type of classes are called Singleton class.<br />
Typical examples could be ,Logger,Print spoolers,Connection pool etc.<br />
Singleton is ideal if an application developer wants to make sure only one instance of the class should be created. Give a global point of access to the object of the class.<br />
Follow the code below,</p>
<pre class="brush: java">
package com.etechguide.java.classtype;

public class SingleTon {
private SingleTon() {
// Not doing anything
}
static private SingleTon instance = null;

/**
* @return the unique instance.
*/
static public SingleTon getInstance() {
if(instance == null ) {
instance = new SingleTon();
}
return instance;
}
}
</pre>
<p>Here I have provided a default private constructor,</p>
<pre class="brush: java">
private SingleTon() {
// Not doing anything
}
</pre>
<p>and then provide a way to one point global access,</p>
<pre class="brush: java">
static public SingleTon getInstance() {
if(instance == null ) {
instance = new SingleTon();
}
return instance;
}
</pre>
<p>The above SingleTon Class should be improved to make the access method Synchronized to prevent thread Problems.This can be achieved as,</p>
<pre class="brush: java">
public static synchronized SingleTon getInstance()
</pre>
<p>But are we safe here ? No. we can still create a clone of the object using,</p>
<pre class="brush: java">
SingleTon ston = (SingleTon)obj.clone();
</pre>
<p>We should override the clone method so that an attempt of cloning the object resulted in an exception , say CloneNotSupportedException Exception.</p>
<pre class="brush: java">
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
</pre>
<p>Full version of the SingleTon Class is ,</p>
<pre class="brush: java">
package com.etechguide.java.classtype;
public class SingleTon {
private SingleTon() {
// Not doing anything
}
static private SingleTon instance = null;
/**
* @return the unique instance.
*/
public static synchronized SingleTon getInstance() {
if (instance == null) {
instance = new SingleTon();
}
return instance;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
</pre>
<p>Single instantiation of the class can be done in the following way too,</p>
<pre class="brush: java">
public class SingleTon {

private static SingleTon instance = new SingleTon();
public static SingleTon getInstance() {
return instance;
}
private SingleTon() {
}
}
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?&amp;linkurl=http%3A%2F%2FetechGuide.in%2Fjava%2Fsingleton-what-it-is-and-why-is-singleton%2F&amp;linkname=Singleton%20%26%238211%3B%20What%20it%20is%20and%20why%20is%20Singleton%20%3F"><img src="http://etechGuide.in/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share/Save/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://etechGuide.in/java/singleton-what-it-is-and-why-is-singleton/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
