<?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 &#8211; Jitendra Zaa</title>
	<atom:link href="https://www.jitendrazaa.com/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.jitendrazaa.com/blog</link>
	<description>AI, Salesforce, ServiceNow &#38; Enterprise Tech Guides</description>
	<lastBuildDate>Thu, 13 Feb 2020 23:59:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<site xmlns="com-wordpress:feed-additions:1">87744916</site><atom:link rel="search" type="application/opensearchdescription+xml" title="Search Jitendra Zaa" href="https://www.jitendrazaa.com/blog/wp-json/opensearch/1.1/document" />	<item>
		<title>Create Excel File in Java using Apache POI Library</title>
		<link>https://www.jitendrazaa.com/blog/java/create-excel-file-in-java-using-apache-poi-library/</link>
					<comments>https://www.jitendrazaa.com/blog/java/create-excel-file-in-java-using-apache-poi-library/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Tue, 15 Oct 2013 07:02:19 +0000</pubDate>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Apache POI]]></category>
		<category><![CDATA[Excel]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=3556</guid>

					<description><![CDATA[Recently, I came across requirement to create ExcelSheet from thin Java Client used by Salesforce. So, I though to share my experience on Creating Excel Sheet in Java. As we know that Java is product of Oracle and Excel is product of Microsoft. Off-course, There will be no standard functionality available in Java to achieve [&#8230;]]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">Recently, I came across requirement to create ExcelSheet from thin Java Client used by Salesforce. So, I though to share my experience on Creating Excel Sheet in Java. As we know that Java is product of Oracle and Excel is product of Microsoft. Off-course, There will be no standard functionality available in Java to achieve our requirement of creating Excel Sheet. However thanks to <strong>Apache</strong> for their <strong>POI</strong> Library. POI Stands for &#8220;Poor Obfuscation Implementation&#8221; as the file formats created by this library is obfuscated poorly with help of reverse Engineering. Anyways, we don&#8217;t have to bother about it and thankful to them for providing such wonderful library.</p>
<p style="text-align: justify;">Apache POI library can be used to create Excel Sheet, Word Document and PowerPoint. In this post, we will be totally focusing on Excel Sheet using &#8220;<strong>XSSF (XML Spreadsheet Format)</strong>&#8221; component.</p>
<p><strong>Prerequisite :</strong><br />
Add all jar files downloaded from Apache POI download site in Java Program&#8217;s build path.<span id="more-3556"></span></p>
<p><strong>Demo Code :</strong></p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft;

import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**
* @author Jitendra Zaa
*
*/
public class CreateExcelSheet {

	static SXSSFWorkbook  wb ;
	static Sheet sh ;

	/**
	 * This method demonstrates how to Auto resize Excel column
	 */
	private static void autoResizeColumns()
	{
		for(int colIndex = 0; colIndex &lt; 10 ; colIndex++)
		{
			sh.autoSizeColumn(colIndex);
		}
	}

	/**
	 * This method will return Style of Header Cell
	 * @return
	 */
	private static CellStyle getHeaderStyle()
	{
		CellStyle style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

	    style.setBorderBottom(CellStyle.BORDER_THIN);
	    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
	    style.setBorderLeft(CellStyle.BORDER_THIN);
	    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
	    style.setBorderRight(CellStyle.BORDER_THIN);
	    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
	    style.setBorderTop(CellStyle.BORDER_THIN);
	    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
	    style.setAlignment(CellStyle.ALIGN_CENTER);

	    return style;
	}

	/**
	 * This method will return style for Normal Cell
	 * @return
	 */
	private static CellStyle getNormalStyle()
	{
		CellStyle style = wb.createCellStyle();

	    style.setBorderBottom(CellStyle.BORDER_THIN);
	    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
	    style.setBorderLeft(CellStyle.BORDER_THIN);
	    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
	    style.setBorderRight(CellStyle.BORDER_THIN);
	    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
	    style.setBorderTop(CellStyle.BORDER_THIN);
	    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
	    style.setAlignment(CellStyle.ALIGN_CENTER);

	    return style;
	}

	/**
	 * @param args
	 */
	public static void main(String&#x5B;] args) throws Exception {

		 wb =  new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
		sh = wb.createSheet(&quot;Sample sheet&quot;);

	    CellStyle headerStle= getHeaderStyle();
	    CellStyle normalStyle = getNormalStyle();

		 for(int rownum = 0; rownum &lt; 1000; rownum++){
	            Row row = sh.createRow(rownum);
	            for(int cellnum = 0; cellnum &lt; 10; cellnum++){

	                Cell cell = row.createCell(cellnum);
	                String address = new CellReference(cell).formatAsString();
	                cell.setCellValue(address);

	                if(rownum == 0)
	                {

	                	cell.setCellStyle(headerStle);
	                }
	                else
	                {
	                	cell.setCellStyle(normalStyle);
	                }
	            }

	        }

		 //Below code Shows how to merge Cell
		 sh.addMergedRegion(new CellRangeAddress(
		            0, //first row (0-based)
		            0, //last row  (0-based)
		            0, //first column (0-based)
		            5  //last column  (0-based)
		    ));

		 autoResizeColumns();

		 /**
		  * To Auto-resize Row, We have to follow two steps
		  * 1. Set WordWrap property in CellStyle to true
		  * 2. Set setHeightInPoints of row likw this :
		  *  	row.setHeightInPoints((totalHtmlLineBreak * sh.getDefaultRowHeightInPoints()));
		  *  	Where totalHtmlLineBreak is total lines for auto height
		  */

	        File f = new File(&quot;c:/DeleteThis/2/Example2.xlsx&quot;);

	        if(!f.exists())
	        {
	        	//If directories are not available then create it
	        	File parent_directory = f.getParentFile();
	        	if (null != parent_directory)
	        	{
	        	    parent_directory.mkdirs();
	        	}

	        	f.createNewFile();
	        }

	        FileOutputStream out = new FileOutputStream(f,false);
	        wb.write(out);
	        out.close();

	        // dispose of temporary files backing this workbook on disk
	        wb.dispose();
	        System.out.println(&quot;File is created&quot;);
	        //Launch Excel File Created
	        Desktop.getDesktop().open(f);
	}
}
</pre>
<p>Code Written above is very simple and self Explanatory. This is the Output of above code,</p>
<figure id="attachment_3561" aria-describedby="caption-attachment-3561" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/10/Create-Excel-File-in-Java.png?ssl=1"><img data-recalc-dims="1" decoding="async" class="size-medium wp-image-3561" alt="Create Excel File in Java" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/10/Create-Excel-File-in-Java-300x166.png?resize=300%2C166&#038;ssl=1" width="300" height="166" /></a><figcaption id="caption-attachment-3561" class="wp-caption-text">Create Excel File in Java</figcaption></figure>
<p><span style="line-height: 1.714285714; font-size: 1rem;">I have collected few common Questions asked on Apache POI, lets discuss it.</span></p>
<p><strong>1. How to Auto Re-size Column in Generated Excel Sheet?</strong><br />
<strong> Ans :</strong> We can use &#8220;autoSizeColumn(int ColumnNumber)&#8221; method of Sheet Object.</p>
<p><strong>2. How to add Styles in Cell or Column in Excel Sheet ?</strong><br />
<strong> Ans :</strong> As shown in above code, We have Object named &#8220;CellStyle&#8221; used in method &#8220;getHaderStyle()&#8221;. We can set Background Color as well and all other stuff.</p>
<p><strong>3. How to merge Columns in Excel ?</strong><br />
<strong> Ans :</strong> Using below code snippet</p>
<pre class="brush: java; title: ; notranslate">
//Below code Shows how to merge Cell
		 sh.addMergedRegion(new CellRangeAddress(
		            0, //first row (0-based)
		            0, //last row  (0-based)
		            0, //first column (0-based)
		            5  //last column  (0-based)
		    ));
</pre>
<p><strong>4. How to Auto &#8211; Re-size row in <strong>Generated </strong>Excel Sheet ?</strong><br />
<strong> Ans:</strong> To Auto-re-size row, we have to follow two steps:</p>
<ul>
<li>Set Word Wrap property to true in CellStyle</li>
<li>Call method setHeightInPoints on row object</li>
</ul>
<p><strong>Sample Code :</strong></p>
<pre class="brush: java; title: ; notranslate">
            /**
		  * To Auto-resize Row, We have to follow to steps
		  * 1. Set WordWrap property in CellStyle to true
		  * 2. Set setHeightInPoints of row likw this :
		*/
		    	row.setHeightInPoints((totalHtmlLineBreak * sh.getDefaultRowHeightInPoints()));
		  /**
		    *  	Where totalHtmlLineBreak is total lines for auto height
		  */
</pre>
<p>I am waiting for your feedback and suggestions on this post. Happy Coding !!! 🙂</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/create-excel-file-in-java-using-apache-poi-library/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3556</post-id>	</item>
		<item>
		<title>Creating First Application in Heroku using Eclipse</title>
		<link>https://www.jitendrazaa.com/blog/java/creating-first-application-in-heroku-using-eclipse/</link>
					<comments>https://www.jitendrazaa.com/blog/java/creating-first-application-in-heroku-using-eclipse/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Sun, 03 Mar 2013 07:48:40 +0000</pubDate>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[EGit]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Heroku]]></category>
		<category><![CDATA[Jetty]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=3231</guid>

					<description><![CDATA[Hello Readers, in this article we will see step by step procedure to deploy your first (Hello World) program in Heroku. There are two ways, first going through series of Commands of &#8220;Heroku&#8221; and &#8220;GIT&#8221; and other simple and smart way is to use Eclipse Capability with Heroku. To make things easier we will go [&#8230;]]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">Hello Readers, in this article we will see step by step procedure to deploy your first (Hello World) program in Heroku. There are two ways, first going through series of Commands of &#8220;Heroku&#8221; and &#8220;GIT&#8221; and other simple and smart way is to use Eclipse Capability with Heroku. To make things easier we will go by second method.</p>
<p><strong>!Deprecated!</strong></p>
<p>This tool / blog post is deprecated. Please follow <a href="https://devcenter.heroku.com/articles/deploying-java-applications-to-heroku-from-eclipse-or-intellij-idea">this guide</a> to deploying applications to Heroku from Eclipse. If you still want to follow this post, then download <a href="https://github.com/heroku/heroku-eclipse-plugin">Eclipse plugin for Heroku from here</a>.</p>
<p><strong>Prerequisites:</strong></p>
<ul>
<li>Heroku Account, you can sign up here &#8211; <a title="Create Heroku Account" href="https://api.heroku.com/signup/devcenter" rel="nofollow">https://api.heroku.com/signup/devcenter</a></li>
<li>Eclipse 3.7 or Higher</li>
<li>E-Git Plugin , more information on set up of E-Git &#8211; <a title="Egit and Git Tutorial by ShivaSoft" href="https://jitendrazaa.com/blog/salesforce/salesforce-git-eclipse-egit-better-and-distributed-source-control/">https://jitendrazaa.com/blog/salesforce/salesforce-git-eclipse-egit-better-and-distributed-source-control/</a></li>
</ul>
<p><strong>Installation and Set up:</strong><br />
First we will need to Install Heroku Plugin in Eclipse. To install it, Navigate to <strong>&#8220;Help | Install New Software&#8221;</strong> and click on <strong>&#8220;Add&#8221;</strong> button.</p>
<p>Give any name in website like &#8220;Heroku Plugin&#8221; and enter this URL in Location <a title="Install Heroku Plugin" href="https://eclipse-plugin.herokuapp.com/install" rel="nofollow">https://eclipse-plugin.herokuapp.com/install</a> and click on &#8220;Ok&#8221; and Finish Installation. It will install the Heroku Plugin required to start your first Plugin.</p>
<p>Next step is <strong>setting up your Credentials for Heroku :</strong></p>
<p style="text-align: justify;">Navigate to <strong>&#8220;Window | Preferences | Heroku&#8221;</strong>, Here either enter your UserName and Password of Heroku Account and click on &#8220;Login&#8221; or enter you API key, which you can find by logging into your Heroku Account.</p>
<figure id="attachment_3234" aria-describedby="caption-attachment-3234" style="width: 578px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Setting-up-Credentials-for-Heroku-in-Eclipse.png?ssl=1"><img data-recalc-dims="1" fetchpriority="high" decoding="async" class=" wp-image-3234 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Setting-up-Credentials-for-Heroku-in-Eclipse.png?resize=578%2C469&#038;ssl=1" alt="Setting up Credentials for Heroku in Eclipse" width="578" height="469" /></a><figcaption id="caption-attachment-3234" class="wp-caption-text">Setting up Credentials for Heroku in Eclipse</figcaption></figure>
<p><span id="more-3231"></span><br />
<strong>Creating SSH Key :</strong></p>
<p>Heroku uses Git to push and pull code from Heroku. For this you can use <a title="Egit Plugin" href="http://www.eclipse.org/egit" rel="nofollow">E-Git plugin</a> of Eclipse. You can also visit <a title="Egit Tutorial" href="https://jitendrazaa.com/blog/salesforce/salesforce-git-eclipse-egit-better-and-distributed-source-control/">this article for complete tutorial</a>. So, for communication between Heroku and Git we need SSH. Navigate to <strong>&#8220;Windows | Preferences |General | Network Connections | SSH2 &#8220;</strong>. Navigate to &#8220;<strong>Key Management</strong>&#8220; tab and click on <strong>&#8220;Generate RSA Key&#8221;</strong>. After Generation of key click on <strong>&#8220;Save Private Key&#8221;</strong>.</p>
<figure id="attachment_3236" aria-describedby="caption-attachment-3236" style="width: 578px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Generate-SSH-Key-in-Eclipse-for-Heroku.png?ssl=1"><img data-recalc-dims="1" decoding="async" class=" wp-image-3236 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Generate-SSH-Key-in-Eclipse-for-Heroku.png?resize=578%2C470&#038;ssl=1" alt="Generate SSH Key in Eclipse for Heroku" width="578" height="470" /></a><figcaption id="caption-attachment-3236" class="wp-caption-text">Generate SSH Key in Eclipse for Heroku</figcaption></figure>
<p>Now, after generation of RSA key Navigate to &#8220;Heroku&#8221; and click on <strong>&#8220;Load SSH Key&#8221;</strong> and select file which you have saved recently.</p>
<figure id="attachment_3237" aria-describedby="caption-attachment-3237" style="width: 576px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Load-SSH-Key-in-Heroku-using-Eclipse.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3237 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Load-SSH-Key-in-Heroku-using-Eclipse.png?resize=576%2C471&#038;ssl=1" alt="Load SSH Key in Heroku using Eclipse" width="576" height="471" /></a><figcaption id="caption-attachment-3237" class="wp-caption-text">Load SSH Key in Heroku using Eclipse</figcaption></figure>
<p style="text-align: justify;">Now, till this we have done all the configurations. Start with creating our first &#8220;Hello World&#8221; program from Template using <a title="Jetty" href="http://jetty.codehaus.org/jetty/" rel="nofollow">Jetty</a>.<br />
Navigate to <strong>&#8220;New | Project | Heroku | Create Heroku App from Template&#8221;</strong> and click on Next.</p>
<figure id="attachment_3239" aria-describedby="caption-attachment-3239" style="width: 522px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Select-Application-template-from-new-Heroku-Project.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-3239" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/03/Select-Application-template-from-new-Heroku-Project.png?resize=522%2C618&#038;ssl=1" alt="Select Application template from new Heroku Project" width="522" height="618" /></a><figcaption id="caption-attachment-3239" class="wp-caption-text">Select Application template from new Heroku Project</figcaption></figure>
<p style="text-align: justify;">On Next screen select <strong>&#8220;Embedded Jetty-Servlet application&#8221;</strong> and click on Finish. After creation of sample project, open &#8220;Main.java&#8221; file and run it.</p>
<p style="text-align: justify;">Now open browser with URL <a title="Run Localhost application of Jetty" href="http://localhost:8080/">http://localhost:8080/</a> and you should able to see Jetty Page. If you are able to see the Jetty Startup page, means everything is good. Now navigate to <a title="Run local Jetty Application" href="http://localhost:8080/hello">http://localhost:8080/hello</a> , you will see text &#8220;Hello Heroku&#8221; just like below screen.</p>
<figure id="attachment_3242" aria-describedby="caption-attachment-3242" style="width: 586px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Getting-Started-with-Embedded-Jetty-in-Heroku.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3242 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Getting-Started-with-Embedded-Jetty-in-Heroku.png?resize=586%2C298&#038;ssl=1" alt="Getting Started with Embedded Jetty in Heroku" width="586" height="298" /></a><figcaption id="caption-attachment-3242" class="wp-caption-text">Getting Started with Embedded Jetty in Heroku</figcaption></figure>
<p>You can make modifications in &#8220;HelloServlet.java&#8221; by replacing below line with some other Text.</p>
<pre class="brush: java; title: ; notranslate">&lt;br /&gt;out.write(&quot;Hello Heroku&quot;.getBytes());&lt;br /&gt;</pre>
<p><strong>Deploying Modifications to Heroku from Local System:</strong></p>
<p>Now, as we are done with making modifications in local code, commit the changes in Git by <strong>&#8220;Right Click on Project | Team | Commit&#8221;</strong>. You need to Enter Commit Message like this:</p>
<figure id="attachment_3243" aria-describedby="caption-attachment-3243" style="width: 527px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Commit-Changes-to-Git-Heroku.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3243 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Commit-Changes-to-Git-Heroku.png?resize=527%2C502&#038;ssl=1" alt="Commit Changes to Git - Heroku" width="527" height="502" /></a><figcaption id="caption-attachment-3243" class="wp-caption-text">Commit Changes to Git &#8211; Heroku</figcaption></figure>
<p>After Committing the Changes, Navigate to <strong>&#8220;Right Click on Project | Team | Push to Upstream&#8221;</strong>.</p>
<figure id="attachment_3244" aria-describedby="caption-attachment-3244" style="width: 564px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Push-to-UpStream-in-Git-for-Heroku.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3244 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Push-to-UpStream-in-Git-for-Heroku.png?resize=564%2C588&#038;ssl=1" alt="Push to UpStream in Git for Heroku" width="564" height="588" /></a><figcaption id="caption-attachment-3244" class="wp-caption-text">Push to UpStream in Git for Heroku</figcaption></figure>
<p>Now, if everything is good, Heroku will receive all you local Changes and build application again on its server.</p>
<figure id="attachment_3245" aria-describedby="caption-attachment-3245" style="width: 530px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Heroku-Build-Succeed.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3245 " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2013/04/Heroku-Build-Succeed.png?resize=530%2C366&#038;ssl=1" alt="Heroku Build Succeed" width="530" height="366" /></a><figcaption id="caption-attachment-3245" class="wp-caption-text">Heroku Build Succeed</figcaption></figure>
<p style="text-align: justify;">Now you can run this application by logging into Heroku and make modifications that&#8217;s suits you like Salesforce Integration or any other.</p>
<p style="text-align: justify;"><a title="Official Heroku Tutorial and Documentation" href="https://devcenter.heroku.com/articles/getting-started-with-heroku-eclipse" rel="nofollow">You can also visit this official Heroku tutorial</a>, which explains in very detail about Heroku Deployment using Eclipse and other important Configurations.</p>
<p style="text-align: justify;">If you are getting an error &#8220;<strong>eclipse SSH key is not matching the SSH key(s) that is associated with your Heroku account</strong>&#8220;, then <a title="Resolve Eclipse and Heroku Error" href="https://www.jitendrazaa.com/blog/others/tips/resolve-error-eclipse-ssh-key-is-not-matching-the-ssh-keys-that-is-associated-with-your-heroku-account/">follow this article to resolve this</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/creating-first-application-in-heroku-using-eclipse/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3231</post-id>	</item>
		<item>
		<title>Merge PDF in Salesforce Using Java, ITextPDF and OAuth 2</title>
		<link>https://www.jitendrazaa.com/blog/java/merge-pdf-in-salesforce-using-java-itextpdf-and-oauth-2/</link>
					<comments>https://www.jitendrazaa.com/blog/java/merge-pdf-in-salesforce-using-java-itextpdf-and-oauth-2/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Sun, 09 Dec 2012 16:33:39 +0000</pubDate>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Integration]]></category>
		<category><![CDATA[OAuth]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=3150</guid>

					<description><![CDATA[Its long time, since i wrote any article because of my busy schedule However this time i came with advance one. In this article we are going to use the J2EE (Servlet) to Merge PDF attachment inside salesforce with the help of OAuth and ITextPDF jar file. The reason of writing this article is that [&#8230;]]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">Its long time, since i wrote any article because of my busy schedule However this time i came with advance one. In this article we are going to use the J2EE (Servlet) to Merge PDF attachment inside salesforce with the help of <strong>OAuth</strong> and <strong>ITextPDF</strong> jar file. The reason of writing this article is that there is no native support by Apex to merge two attachments in Salesforce. Either we have to go for AppExchange product like CongaMerg or Drawloop or we can write our own code in any other language like Java and C# and with the help of REST API we can save get and save attachment in Salesforce.</p>
<p style="text-align: justify;">First we will need to setup the OAuth permission so that our local J2EE application can interact with Salesforce. For this login to Salesforce account and Navigate to &#8220;Set up | App Set up | Develop | Remote Access&#8221; and enter the information. Be careful about the &#8220;Callback URL&#8221;. It must match in your code. After creating the &#8220;Remote Access&#8221;, note &#8220;Consumer Key&#8221; and &#8220;Consumer Secret&#8221; which will be needed in your code.</p>
<p style="text-align: justify;">Update : &#8220;Remote Access&#8221; is renamed to Connected App. So throughout this article, if you see image of &#8220;Remote Access&#8221; then please consider it as Connected App.</p>
<figure id="attachment_3153" aria-describedby="caption-attachment-3153" style="width: 549px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/12/Create-Remote-Access-in-Salesforce.com_.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3153 " title="Create Remote Access in Salesforce.com for OAuth 2" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/12/Create-Remote-Access-in-Salesforce.com_.png?resize=549%2C378&#038;ssl=1" alt="Create Remote Access in Salesforce.com for OAuth 2" width="549" height="378" /></a><figcaption id="caption-attachment-3153" class="wp-caption-text">Create Remote Access in Salesforce.com for OAuth 2</figcaption></figure>
<p><span id="more-3150"></span></p>
<figure id="attachment_3154" aria-describedby="caption-attachment-3154" style="width: 563px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/12/Remote-Access-Consumer-key-and-Consumer-Secret-Salesforce.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class=" wp-image-3154 " title="Get Consumer key and Consumer Secret in Salesforce using Remote Access " src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/12/Remote-Access-Consumer-key-and-Consumer-Secret-Salesforce.png?resize=563%2C344&#038;ssl=1" alt="Get Consumer key and Consumer Secret in Salesforce using Remote Access " width="563" height="344" /></a><figcaption id="caption-attachment-3154" class="wp-caption-text">Get Consumer key and Consumer Secret in Salesforce using Remote Access</figcaption></figure>
<p>So, we will start with setting up the Log4j for our project. Copy below code in &#8220;log4j.properties&#8221; file. you will need Apache commons logging jar, which you can find in this article&#8217;s source code.</p>
<pre class="brush: bash; title: ; notranslate">
# A default log4j configuration for log4j users.
#
# To use this configuration, deploy it into your application's WEB-INF/classes
# directory.  You are also encouraged to edit it as you like.

# Configure the console as our one appender
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p &#x5B;%c] - %m%n

# tighten logging on the DataNucleus Categories
log4j.category.DataNucleus.JDO=WARN, A1
log4j.category.DataNucleus.Persistence=WARN, A1
log4j.category.DataNucleus.Cache=WARN, A1
log4j.category.DataNucleus.MetaData=WARN, A1
log4j.category.DataNucleus.General=WARN, A1
log4j.category.DataNucleus.Utility=WARN, A1
log4j.category.DataNucleus.Transaction=WARN, A1
log4j.category.DataNucleus.Datastore=WARN, A1
log4j.category.DataNucleus.ClassLoading=WARN, A1
log4j.category.DataNucleus.Plugin=WARN, A1
log4j.category.DataNucleus.ValueGeneration=WARN, A1
log4j.category.DataNucleus.Enhancer=WARN, A1
log4j.category.DataNucleus.SchemaTool=WARN, A1
</pre>
<p>Now, create a Servlet with name &#8220;StartServet&#8221; and following code:</p>
<pre class="brush: java; title: ; notranslate">
package com.sfdc.pdfmerge.sample;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
* Servlet implementation class TestOAuth
*/
public class StartServet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StartServet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public static final String ACCESS_TOKEN = &quot;ACCESS_TOKEN&quot;;
	public static final String INSTANCE_URL = &quot;INSTANCE_URL&quot;;
	String oauthURL = &quot;&quot;;

	private static final Logger log = Logger.getLogger(StartServet.class.getName());

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sfdcInstance = &quot;https://ap1.salesforce.com&quot;;

		String accessToken = (String) request.getSession().getAttribute(ACCESS_TOKEN);
		String code = request.getParameter(&quot;code&quot;);

		String consumerKey = &quot;3MVG9Y6d_Btp4xp7hZ1hn287sIMQ56.b_dOEBDrKHRbtwByFvFJz0A4ETmj_TbTuu4CsCkknL3ZgoWIzUTBnh&quot;;
		String consumerSecret = &quot;4972968186270851852&quot;;
		String redirectUri = &quot;https://localhost:8443/PDFMerge_J2EE/TestOAuth?isCallBack=1&quot;;

		oauthURL = sfdcInstance + &quot;/services/oauth2/authorize?response_type=code&amp;client_id=&quot; + consumerKey + &quot;&amp;redirect_uri=&quot;
				+ URLEncoder.encode(redirectUri, &quot;UTF-8&quot;);

		if (accessToken == null) {

			try {
				String isCallBack = request.getParameter(&quot;isCallBack&quot;);
					log.info(&quot;Starting OAuth&quot;);
					log.info(&quot;Is CallBack = &quot;+isCallBack);

					/**
					 * Initiate HTTP request to get the Authorization code
					 */
					DefaultHttpClient httpclient = new DefaultHttpClient();
					HttpPost httpPost = new HttpPost(oauthURL);
					HttpResponse response1 = httpclient.execute(httpPost);

					/**
					 * If HTTP status code is 302, means Salesforce trying to redirect to authorize the Local System
					 */
					if(response1.getStatusLine().getStatusCode() == 302 &amp;&amp; isCallBack == null)
					{
						httpclient.getConnectionManager().shutdown();
						log.info(&quot;Got 302 request from Salesforce so redirect it&quot;);
						response.sendRedirect(oauthURL);
						return;
					}
					else
					{
						log.info(&quot;Got Callback, Now get the Access Token&quot;);

						httpclient = new DefaultHttpClient();
						String tokenUrl = sfdcInstance + &quot;/services/oauth2/token&quot;;

						log.info(&quot;Code - &quot;+code);

						List qparams = new ArrayList();
						qparams.add(new BasicNameValuePair(&quot;code&quot;, code));
						qparams.add(new BasicNameValuePair(&quot;grant_type&quot;, &quot;authorization_code&quot;));
						qparams.add(new BasicNameValuePair(&quot;client_id&quot;, consumerKey));
						qparams.add(new BasicNameValuePair(&quot;client_secret&quot;, consumerSecret));
						qparams.add(new BasicNameValuePair(&quot;redirect_uri&quot;, redirectUri));

						HttpPost httpPost2 = new HttpPost(tokenUrl);
						httpPost2.setEntity(new UrlEncodedFormEntity(qparams));

						/**
						 * Always set this Header to explicitly to get Authrization code else following error will be raised
						 * unsupported_grant_type
						 */
						httpPost2.setHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);

						HttpResponse response2 = httpclient.execute(httpPost2);

						HttpEntity entity2 = response2.getEntity();
						System.out.println(entity2.getContent().toString());

						JSONObject authResponse = new JSONObject(new JSONTokener(new InputStreamReader(entity2.getContent())));
						System.out.println(authResponse.toString());
						accessToken = authResponse.getString(&quot;access_token&quot;);
						String instanceUrl = authResponse.getString(&quot;instance_url&quot;);

						request.getSession().setAttribute(ACCESS_TOKEN, accessToken);

						// We also get the instance URL from the OAuth response, so set it
						// in the session too
						request.getSession().setAttribute(INSTANCE_URL, instanceUrl);

						log.info(&quot;Response is : &quot;+authResponse);
						log.info(&quot;Got access token: &quot; + accessToken);

						/**
						In Below line of code, provide the attachment Ids to merge
						*/
						String pdfUrl = &quot;/PDFMerge_J2EE/pdfmerge?ids=00P900000038KTm&amp;parentId=00690000007GLNj&amp;mergedDocName=MergedDoc.pdf&quot;;
						response.sendRedirect(pdfUrl);
				}
			} catch (Exception e) {
					e.printStackTrace();
			} finally {
			}
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}
</pre>
<p style="text-align: justify;">Above servlet is starting/landing servlet and authenticate your application with Salesforce using Consumer Key and Consumer Secret. After Authentication using OAuth it will call another servlet to merge PDF and save back in Salesforce.</p>
<p style="text-align: justify;">Now, create a new Servlet which will actually read the attachment Ids from parameter and merge PDF using &#8220;iTextPDF&#8221; jar and save back again in Salesforce.</p>
<pre class="brush: java; title: ; notranslate">
package com.sfdc.pdfmerge.sample;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings(&quot;serial&quot;)
public class PDFMergeServlet extends HttpServlet {
	private String accessToken;
	private String instanceURL;

	private static final Logger log = Logger.getLogger(PDFMergeServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
	    log.severe(&quot;PDF Merge Servlet Called&quot;);
		String sfdcInstance = req.getParameter(&quot;instanceURL&quot;);

		accessToken = (String)req.getSession().getAttribute(StartServet.ACCESS_TOKEN);
		instanceURL = (String)req.getSession().getAttribute(StartServet.INSTANCE_URL);

		if (accessToken == null)
			return;

		String ids = req.getParameter(&quot;ids&quot;);
		String parentId = req.getParameter(&quot;parentId&quot;);
		String mergedDocName = req.getParameter(&quot;mergedDocName&quot;);

		List pdfs = new ArrayList();
		ByteArrayOutputStream o = null;
		if (accessToken != null &amp;&amp; ids != null &amp;&amp; parentId != null)
		{
			Salesforce sfdc = new Salesforce(instanceURL, accessToken);
			for (String id : ids.split(&quot;,&quot;))
			{
				pdfs.add(sfdc.getAttachment(id));
			}

			o = new ByteArrayOutputStream();
			MergePDF.concatPDFs(pdfs, o, false);

			sfdc.saveAttachment(parentId, mergedDocName, o, &quot;application/pdf&quot;);
		}

		try
		{
			if (o != null)
			{
				o.flush();
				o.close();
			}

			for (InputStream pdf : pdfs)
			{
				pdf.close();
			}
		}
		catch (Exception e){e.printStackTrace();}

		resp.setContentType(&quot;text/plain&quot;);
		resp.getWriter().println(&quot;Documents merged successfully&quot;);
	}

}
</pre>
<p>Create a utility Java Class &#8220;MergePDF&#8221; which is used in above servlet:</p>
<pre class="brush: java; title: ; notranslate">
package com.sfdc.pdfmerge.sample;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class MergePDF {

    public static void concatPDFs(List&lt;InputStream&gt; streamOfPDFFiles,
            OutputStream outputStream, boolean paginate) {

        Document document = new Document();
        try {
            List&lt;InputStream&gt; pdfs = streamOfPDFFiles;
            List&lt;PdfReader&gt; readers = new ArrayList&lt;PdfReader&gt;();
            int totalPages = 0;
            Iterator&lt;InputStream&gt; iteratorPDFs = pdfs.iterator();

            // Create Readers for the pdfs.
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
            }
            // Create a writer for the outputstream
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);

            document.open();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
            // data

            PdfImportedPage page;
            int currentPageNumber = 0;
            int pageOfCurrentReaderPDF = 0;
            Iterator&lt;PdfReader&gt; iteratorPDFReader = readers.iterator();

            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();

                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF &lt; pdfReader.getNumberOfPages()) {
                    document.newPage();
                    pageOfCurrentReaderPDF++;
                    currentPageNumber++;
                    page = writer.getImportedPage(pdfReader,
                            pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);

                    // Code for pagination.
                    if (paginate) {
                        cb.beginText();
                        cb.setFontAndSize(bf, 9);
                        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, &quot;&quot;
                                + currentPageNumber + &quot; of &quot; + totalPages, 520,
                                5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}
</pre>
<p style="text-align: justify;">you will also need to map the Servlet URL in <strong>&#8220;web.xml</strong>&#8221; file, which you can find in source code attached.<br />
To run above application, enter this URL in address bar &#8220;<span style="text-decoration: underline;">https://localhost:8443/PDFMerge_J2EE/</span>&#8220;.</p>
<p style="text-align: justify;">After running above code, first time it will ask you to enter the username and password of salesforce account to allow access to your local application and then it will get all the attachments specified in code and after merging it will again attach it to parent id passed in parameter.</p>
<p style="text-align: justify;">jar files needed to run above code:</p>
<ul>
<li>commons-codec-1.1.jar</li>
<li>commons-codec-1.6.jar</li>
<li>commons-lang3-3.1.jar</li>
<li>commons-lang3-3.1-javadoc.jar</li>
<li>commons-lang3-3.1-sources.jar</li>
<li>commons-lang3-3.1-tests.jar</li>
<li>commons-logging-1.1.1.jar</li>
<li>fluent-hc-4.2.1.jar</li>
<li>httpclient-4.2.1.jar</li>
<li>httpclient-cache-4.2.1.jar</li>
<li>httpcore-4.2.1.jar</li>
<li>httpmime-4.2.1.jar</li>
<li>itextpdf-5.1.0.jar</li>
</ul>
<p>Also, <strong>please note that Salesforce OAuth can be run only on &#8220;https&#8221; protocol</strong>. Below articles are also recommended to read :</p>
<p><a title="Simple guide to setup SSL in Tomcat" href="https://jitendrazaa.com/blog/java/simple-guide-to-setup-ssl-in-tomcat/">Simple guide to setup SSL in Tomcat</a><br />
<a title="Digging Deeper into OAuth 2.0 on Force.com" href="http://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com">Digging Deeper into OAuth 2.0 on Force.com</a></p>
<p><a href="https://jitendrazaa.com/blog/wp-content/uploads/2012/12/Generate-PDF-Using-ITextPDF-on-Salesforce.zip">Download Complete Source code for &#8211; Merging PDF Using ITextPDF and OAuth2 on Salesforce using Servlet</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/merge-pdf-in-salesforce-using-java-itextpdf-and-oauth-2/feed/</wfw:commentRss>
			<slash:comments>13</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3150</post-id>	</item>
		<item>
		<title>Simple guide to setup SSL in Tomcat</title>
		<link>https://www.jitendrazaa.com/blog/java/simple-guide-to-setup-ssl-in-tomcat/</link>
					<comments>https://www.jitendrazaa.com/blog/java/simple-guide-to-setup-ssl-in-tomcat/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Sat, 08 Sep 2012 19:31:49 +0000</pubDate>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Servlet]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[tomcat]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=3070</guid>

					<description><![CDATA[I have enabled SSL in tomcat many times however initially I struggled to get it in running condition. So I thought to share a simple approach I am following now days. Step 1: Run tool &#8220;Keytool&#8220; provided by the JRE to create a &#8220;keystore file&#8221;. The command to run tool is: keytool -genkey -alias tomcat [&#8230;]]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">I have enabled SSL in tomcat many times however initially I struggled to get it in running condition. So I thought to share a simple approach I am following now days.</p>
<p><strong>Step 1:</strong></p>
<p>Run tool &#8220;<strong>Keytool</strong>&#8220; provided by the JRE to create a &#8220;keystore file&#8221;.<br />
The command to run tool is:</p>
<blockquote><p>keytool -genkey -alias tomcat -keyalg RSA -keystore D:/.keyStore</p></blockquote>
<p>Where &#8220;D:/.keystore&#8221; is the path where file should be created.<br />
Instead of alias &#8220;tomcat&#8221; any other name can be used.<br />
After running above command, you will be asked many questions, so answer them correctly as shown in below image:</p>
<figure id="attachment_3071" aria-describedby="caption-attachment-3071" style="width: 627px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/09/Tomcat-SSL-keytool-to-create-keystore-file.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-3071" title="Tomcat SSL keytool to create keystore file" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/09/Tomcat-SSL-keytool-to-create-keystore-file.png?resize=627%2C319&#038;ssl=1" alt="Tomcat SSL keytool to create keystore file" width="627" height="319" /></a><figcaption id="caption-attachment-3071" class="wp-caption-text">Tomcat SSL keytool to create keystore file</figcaption></figure>
<p>Remember the password provided, as it will be needed in next step.<span id="more-3070"></span></p>
<p><strong>Step 2:</strong></p>
<p>Now, in next step go to &#8220;conf&#8221; folder of tomcat, and open file &#8220;server.xml&#8221;.<br />
There you will find lines of code something like:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 --&gt;
&lt;!--
&lt;Connector
           port=&quot;8443&quot; minProcessors=&quot;5&quot; maxProcessors=&quot;75&quot;
           enableLookups=&quot;true&quot; disableUploadTimeout=&quot;true&quot;
           acceptCount=&quot;100&quot; debug=&quot;0&quot; scheme=&quot;https&quot; secure=&quot;true&quot;;
           clientAuth=&quot;false&quot; sslProtocol=&quot;TLS&quot;/&gt;
--&gt;
</pre>
<p>So, to enable the SSL, uncomment above code and tweek like below:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Connector
	protocol=&quot;org.apache.coyote.http11.Http11Protocol&quot;
	port=&quot;8443&quot; maxHttpHeaderSize=&quot;8192&quot;
    maxThreads=&quot;150&quot; minSpareThreads=&quot;25&quot; maxSpareThreads=&quot;75&quot;
    enableLookups=&quot;true&quot; disableUploadTimeout=&quot;true&quot;
    acceptCount=&quot;100&quot; scheme=&quot;https&quot; secure=&quot;true&quot;
    clientAuth=&quot;false&quot; sslProtocol=&quot;TLS&quot;
	keystoreFile=&quot;F:eclipseFrameworksapache-tomcat-5.5.31 - SSL Configured.keyStore&quot;
	keystorePass=&quot;YOURpwd&quot;/&gt;
</pre>
<p>As you can see, I have added few more attributes like:</p>
<p style="text-align: justify;"><strong>Protocol :</strong> If the APR (<strong>Apache Portable Runtime</strong>) is enabled in tomcat (maximum time it is enabled by default), then this approach will not work. so configure tomcat that we want to use Java (JSSE) connector, regardless of whether the APR library is loaded or not.<br />
<strong>keystoreFile :</strong> Full path of the keystore file creates in step 1.<br />
<strong>keystorePass:</strong> Password used while creating file in step1.</p>
<p style="text-align: justify;">After these changes, save Server.xml and navigate to: https://localhost:8443/ , As you can see in below image, SSL is enabled.</p>
<figure id="attachment_3072" aria-describedby="caption-attachment-3072" style="width: 323px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/09/Https-protocol-in-Tomcat-SSL-ENabled.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-3072" title="Https protocol in Tomcat - SSL Enabled" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/09/Https-protocol-in-Tomcat-SSL-ENabled.png?resize=323%2C437&#038;ssl=1" alt="Https protocol in Tomcat - SSL Enabled" width="323" height="437" /></a><figcaption id="caption-attachment-3072" class="wp-caption-text">https protocol in Tomcat &#8211; SSL Enabled</figcaption></figure>
<p style="text-align: justify;">Now, as you can see, although we have created SSL certificate for local server, browser is showing that it is not secured.</p>
<p style="text-align: justify;">SSL verifies the authenticity of a site&#8217;s certificate by using something called a &#8220;chain of trust,&#8221; which basically means that during the handshake, SSL initiates an additional handshake with the Certificate Authority (CA) specified in your site&#8217;s certificate, to verify that you haven&#8217;t simply made up your own CA (Which actually we have done in our case <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ).</p>
<p style="text-align: justify;">If you want to remove error, you have to get certificate from some Certificate Authority so that during handshake, accuracy of your certificate can be validated.<br />
If you have valid certificates then please <a title="Enabling SSL certificates in Tomcat" href="http://www.mulesoft.com/tomcat-ssl ">read this article</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/simple-guide-to-setup-ssl-in-tomcat/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3070</post-id>	</item>
		<item>
		<title>Complete Salesforce Deployment Guide using Ant Migration Tool</title>
		<link>https://www.jitendrazaa.com/blog/salesforce/salesforce-migration-tool-ant/</link>
					<comments>https://www.jitendrazaa.com/blog/salesforce/salesforce-migration-tool-ant/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Tue, 05 Jun 2012 13:21:15 +0000</pubDate>
				<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[ANT]]></category>
		<category><![CDATA[ANT Migration Tool]]></category>
		<category><![CDATA[changeset]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Salesforce Migration]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=2892</guid>

					<description><![CDATA[Step by Step tutorial of Salesforce Migration using ANT tool with Proxy settings and retrieving content from Salesforce Organization. Also fix some common errors like java.lang.OutOfMemoryError or unable to find tools.jar]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">Following are the many tools available for Salesforce deployment like</p>
<ol>
<li>Change sets (From Salesforce site)</li>
<li>Eclipse (Using &#8220;Deploy to force.com server&#8221; option in Eclipse)</li>
<li>ANT (Java based tool)</li>
</ol>
<p>We are going to discuss the ANT based migration, step by step:</p>
<p><strong>Prerequisite:</strong><br />
JDK 1.5 or above</p>
<p><strong>Step 1:</strong><br />
Download ANT distribution from &#8211; &#8220;<a title="Download ANT" href="http://ant.apache.org/bindownload.cgi" target="_blank" rel="nofollow noopener">http://ant.apache.org/bindownload.cgi</a>&#8221;</p>
<p style="text-align: justify;"><strong>Step 2:</strong><br />
Set Environment variable &#8220;<em>ANT_HOME</em>&#8220;. The path should be of parent folder of &#8220;bin&#8221;. Also add the &#8220;bin&#8221; folder to your path.</p>
<p style="text-align: justify;"><strong>Step 3:</strong><br />
Check whether ANT is installed or not properly by running command &#8220;<em>ant -version</em>&#8220;. It might be possible that you receive message something like <strong>unable to find tools.jar</strong>. You can copy this jar from &#8220;JDK_HOME/lib/tools.jar&#8221; to &#8220;JRE/lib&#8221; folder.</p>
<p><span id="more-2892"></span></p>
<figure id="attachment_3579" aria-describedby="caption-attachment-3579" style="width: 624px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/06/Salesforce-Get-ANT-version-Original.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-3579" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/06/Salesforce-Get-ANT-version-Original.png?resize=624%2C318&#038;ssl=1" alt="Salesforce Get ANT version " width="624" height="318" /></a><figcaption id="caption-attachment-3579" class="wp-caption-text">Salesforce Get ANT version</figcaption></figure>
<p>In above screen you can see that before copying <strong>tools.jar</strong> I was getting warning.</p>
<p><strong>Step 4:</strong></p>
<p style="text-align: justify;">Login to salesforce and navigate to <strong>&#8220;Your Name |Setup | Develop | Tools&#8221;</strong> and download <strong>&#8220;Force.com Migration tool&#8221;</strong>.</p>
<p style="text-align: justify;">Unzip the downloaded file to the directory of your choice. Copy the <strong>&#8220;ant-salesforce.jar&#8221;</strong> file from the unzipped file into the ant lib directory.</p>
<p style="text-align: justify;">To start with deployment using ANT, we will need <strong>&#8220;build.xml&#8221;</strong> and<strong> &#8220;build.properties&#8221;</strong> file. As there is no need of &#8220;build.properties&#8221; however its good to have it so that the configuration related settings are in different file. You can copy both files from &#8220;sample&#8221; folder of unzipped content from salesforce. Following is the structure of &#8220;build.properties&#8221; file.</p>
<pre class="brush: bash; title: ; notranslate">
# build.properties
# Specify the login credentials for the desired Salesforce organization
sf.username = &amp;amp;amp;amp;lt;SFDCUserName&amp;amp;amp;amp;gt;
sf.password = &amp;amp;amp;amp;lt;SFDCPasswrd&amp;amp;amp;amp;gt;
#sf.pkgName = &amp;amp;amp;amp;lt;Insert comma separated package names to be retrieved&amp;amp;amp;amp;gt;
#sf.zipFile = &amp;amp;amp;amp;lt;Insert path of the zipfile to be retrieved&amp;amp;amp;amp;gt;
#sf.metadataType = &amp;amp;amp;amp;lt;Insert metadata type name for which listMetadata or bulkRetrieve operations are to be performed&amp;amp;amp;amp;gt;
# Use 'https://login.salesforce.com' for production or developer edition (the default if not specified).
# Use 'https://test.salesforce.com for sandbox.
sf.serverurl = https://test.salesforce.com
</pre>
<p style="text-align: justify;"><strong>Step 5:</strong><br />
Copy all folders with source code from source organization using eclipse. Lets say the root folder name is &#8220;test1&#8221;.<br />
Create <strong>&#8220;build.properties&#8221;</strong> from above code snippet or copy it from unzipped folder. Now create <strong>&#8220;build.xml&#8221;</strong> needed by ANT. Following is the example of build.xml file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;project name=&quot;Shivasoft ANT Tutorial&quot; default=&quot;deployCode&quot; basedir=&quot;.&quot; xmlns:sf=&quot;antlib:com.salesforce&quot;&gt;
    &lt;property file=&quot;build.properties&quot;/&gt;
    &lt;property environment=&quot;env&quot;/&gt;
    &lt;!-- Shows deploying code &amp;amp;amp;amp;amp; running tests for code in directory --&gt;
    &lt;target name=&quot;deployCode&quot; depends=&quot;proxy&quot;&gt;
      &lt;sf:deploy username=&quot;${sf.username}&quot; password=&quot;${sf.password}&quot; serverurl=&quot;${sf.serverurl}&quot; deployRoot=&quot;test1&quot;&gt;
        &lt;runTest&gt;TestClassName&lt;/runTest&gt;
      &lt;/sf:deploy&gt;
    &lt;/target&gt;
    &lt;!-- Shows removing code; only succeeds if done after deployCode --&gt;
    &lt;target name=&quot;undeployCode&quot;&gt;
      &lt;sf:deploy username=&quot;${sf.username}&quot; password=&quot;${sf.password}&quot; serverurl=&quot;${sf.serverurl}&quot; deployRoot=&quot;removecodepkg&quot;/&gt;
    &lt;/target&gt;
	&lt;target name=&quot;proxy&quot;&gt;
		&lt;property name=&quot;proxy.host&quot; value=&quot; ProxyURL &quot; /&gt;
		&lt;property name=&quot;proxy.port&quot; value=&quot;1234&quot; /&gt;
		&lt;property name=&quot;proxy.user&quot; value=&quot;UserName&quot; /&gt;
		&lt;property name=&quot;proxy.pwd&quot; value=&quot;Password&quot; /&gt;
		&lt;setproxy proxyhost=&quot;${proxy.host}&quot; proxyport=&quot;${proxy.port}&quot; proxyuser=&quot;${proxy.user}&quot; proxypassword=&quot;${proxy.pwd}&quot; /&gt;
	&lt;/target&gt;
&lt;/project&gt;
</pre>
<p style="text-align: justify;">Attribute &#8220;<strong>deployRoot</strong>&#8221; means the root folder from which the code should be copied and tag  means the testclasses which should run after the deployment. At last, go to the folder &#8220;test1&#8221; from command line and run command &#8220;ant deployCode&#8221;.</p>
<p>&nbsp;</p>
<figure id="attachment_3578" aria-describedby="caption-attachment-3578" style="width: 624px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/06/Salesforce-Migration-using-ANT-Original.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-3578" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/06/Salesforce-Migration-using-ANT-Original.png?resize=624%2C312&#038;ssl=1" alt="Salesforce Migration using-ANT " width="624" height="312" /></a><figcaption id="caption-attachment-3578" class="wp-caption-text">Salesforce Migration using-ANT</figcaption></figure>
<p><span style="text-decoration: underline;"><strong>Checking the status of the task:</strong></span><br />
To know the status of task you can run command:<br />
Ant <strong>targetName </strong>-Dsf.asyncRequestId=<strong>requestID </strong></p>
<p><span style="text-decoration: underline;"><strong>Using Proxy in ANT migration tool:</strong></span><br />
If your organization uses the proxy then add below target in &#8220;build.xml&#8221; and specify this target as dependent.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;target name=&quot;proxy&quot;&gt;
		&lt;property name=&quot;proxy.host&quot; value=&quot; ProxyURL &quot; /&gt;
		&lt;property name=&quot;proxy.port&quot; value=&quot;1234&quot; /&gt;
		&lt;property name=&quot;proxy.user&quot; value=&quot;UserName&quot; /&gt;
		&lt;property name=&quot;proxy.pwd&quot; value=&quot;Password&quot; /&gt;
		&lt;setproxy proxyhost=&quot;${proxy.host}&quot; proxyport=&quot;${proxy.port}&quot; proxyuser=&quot;${proxy.user}&quot; proxypassword=&quot;${proxy.pwd}&quot; /&gt;
	&lt;/target&gt;
</pre>
<p><span style="text-decoration: underline;"><strong>Retrieve content from Salesforce Organization:</strong></span><br />
create &#8220;package.xml&#8221; for the list of component to be retrieved and add following task in &#8220;build.xml&#8221;.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- Retrieve an unpackaged set of metadata from your org --&gt;
&lt;!-- The file unpackaged/package.xml lists what is to be retrieved --&gt;
&lt;target name=&quot;test&quot; depends=&quot;proxy&quot;&gt;
  &lt;mkdir dir=&quot;retrieveUnpackaged&quot;/&gt;
  &lt;!-- Retrieve the contents into another directory --&gt;
  &lt;sf:retrieve username=&quot;${sf.username}&quot; password=&quot;${sf.password}&quot; serverurl=&quot;${sf.serverurl}&quot; retrieveTarget=&quot;retrieveUnpackaged&quot; unpackaged=&quot;unpackaged/package.xml&quot; unzip=&quot;false&quot; /&gt;
&lt;/target&gt;
</pre>
<p style="text-align: justify;">&#8220;Unzip&#8221; attribute specifies that the code retrieved should be in Zip format or not. By default the value is true means it will not in zip format.</p>
<p style="text-align: justify;"><strong>Delete components from Salesforce Organization using &#8220;destructiveChanges.xml&#8221; :</strong><br />
In some cases, we may want to delete some components like Object or fields from Salesforce Organization. In this case, Only &#8220;package.xml&#8221; will not work. We need to create &#8220;destructiveChanges.xml&#8221; file also. Syntax for this file is exactly same as of &#8220;package.xml&#8221;, except that here we cannot define wildcards. So, to undeploy anything from Salesforce org, we need two xml files &#8211; &#8220;package.xml&#8221; and &#8220;<span style="text-decoration: underline;">destructiveChanges.xml</span>&#8220;.</p>
<p style="text-align: justify;">Below is complete code of build.xml, which includes retrieve, Undeploy and Deploy commands.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;project name=&quot;Shivasoft Demo Org&quot; default=&quot;deployCode&quot; basedir=&quot;.&quot; xmlns:sf=&quot;antlib:com.salesforce&quot;&gt;
	&lt;!-- Get all settings like Server Path, username and passwords from &quot;build.properties&quot; file --&gt;
    &lt;property file=&quot;build.properties&quot;/&gt;
    &lt;property environment=&quot;env&quot;/&gt;
	&lt;!-- Sequence 1 - Get All information from Source, Retrieve the contents into Src directory --&gt;
	&lt;target name=&quot;SFDCFetch&quot;&gt;
	  &lt;!-- --&gt;
	  &lt;sf:retrieve username=&quot;${sf.username}&quot; password=&quot;${sf.password}&quot; serverurl=&quot;${sf.serverurl}&quot; retrieveTarget=&quot;src&quot; unpackaged=&quot;package.xml&quot;/&gt;
	&lt;/target&gt;

	&lt;!-- Sequence 3 - Deploy to Target System, Package.xml is present in Src folder --&gt;
	&lt;target name=&quot;deploy&quot;&gt;
      &lt;sf:deploy username=&quot;${sf1.username}&quot; password=&quot;${sf1.password}&quot; serverurl=&quot;${sf.serverurl}&quot; deployroot=&quot;Src&quot;&gt;
      &lt;/sf:deploy&gt;
    &lt;/target&gt; 

	&lt;!-- Sequence 2 - If you want to remove some components, destructiveChanges.xml and Package.xml present in Delete Folder --&gt;
	&lt;target name=&quot;unDeploy&quot;&gt;
      &lt;sf:deploy username=&quot;${sf1.username}&quot; password=&quot;${sf1.password}&quot; serverurl=&quot;${sf.serverurl}&quot; deployroot=&quot;Delete&quot;&gt;
      &lt;/sf:deploy&gt;
    &lt;/target&gt;
&lt;/project&gt;
</pre>
<p><a title="You may also be interested to check how to automate daily Salesforce organization backup" href="https://www.jitendrazaa.com/blog/salesforce/automated-daily-backup-using-ant-migration-tool-and-git/">You may also be interested to check how to automate daily Salesforce backup</a>.</p>
<h3>How to Create Change set from Package.xml</h3>
<p><strong>Step 1 :</strong> Create Empty Changeset, lets say its name is changeset2<br />
<strong>Step 2 :</strong> add <strong>fullname</strong> tag in package.xml. Fullname needs to be the name of changeset created in Step 1</p>
<pre class="brush: xml; highlight: [3]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Package xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;
&lt;fullName&gt;Changeset2&lt;/fullName&gt;
    &lt;types&gt;
        &lt;members&gt;AdditionalQuestionTriggerHandler&lt;/members&gt;
...
...
&lt;/package&gt;
</pre>
<p><strong>Step 3 :</strong> src folder name which contains package.xml needs to have changeset name, in our case changeset2</p>
<h3>How to Create Package.xml from Change set</h3>
<p>Use below ANT script</p>
<pre class="brush: xml; highlight: [7]; title: ; notranslate">
&lt;target name=&quot;retrieveChangeset&quot;&gt;  
  &lt;sf:retrieve 
username=&quot;${sf.username}&quot; 
password=&quot;${sf.password}&quot; 
serverurl=&quot;${sf.serverurl}&quot; 
retrieveTarget=&quot;changesetfolder&quot; 
packageNames=&quot;changesetname&quot; /&gt; 
&lt;/target&gt;
</pre>
<p>&nbsp;</p>
<p>Update [03-Apr-2017]</p>
<p style="text-align: justify;"><strong><span style="text-decoration: underline;">Question</span> : Why Salesforce ANT Migration tool is giving wrong Username, Security token or password error, even when everything is correct ?</strong><br />
<strong>Ans :</strong> If your password contains &#8220;$&#8221;, then ANT tool ignores this characters. So, to correct this, we need to add one more &#8220;$&#8221;.</p>
<p><strong>Question : I am getting unable to find tools.jar files error. I don&#8217;t have access to server so cannot place tools.jar manually. Can I fix this error using build.xml by placing jar files in relative folder?</strong></p>
<p><strong>Ans :</strong> You can include any jar file to be in class path. Add below lines in build.xml. All jar files are placed in lib folder.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;path id=&quot;class.path&quot;&gt;
&lt;pathelement location=&quot;${build}&quot;/&gt;
&lt;fileset dir=&quot;./lib&quot;&gt;
&lt;include name=&quot;**/*.jar&quot; /&gt;
&lt;/fileset&gt;
&lt;/path&gt;

&lt;taskdef resource=&quot;com/salesforce/antlib.xml&quot; uri=&quot;antlib:com.salesforce&quot; classpathref=&quot;class.path&quot;/&gt;
</pre>
<p style="text-align: justify;"><strong>Question : Why I am getting error like java.lang.OutOfMemoryError: Java heap space while retrieving metadata from Salesforce. </strong></p>
<p style="text-align: justify;">Ans : It is possible that you are retrieving metadata of some big organization with lots of changes. In this case, Java JVM running on system needs more memory (RAM) in order to process it. It can be done in two ways</p>
<p>1. Before running ANT command, run below command which will set the RAM allocated for JVM to 1GB. If you are not a Windows user, then use export instead of set in below command.</p>
<pre class="brush: bash; title: ; notranslate">
set ANT_OPTS=-Xmx1g
</pre>
<p>2. Problem in above solution is that, you would need to execute set command every time before using ANT. For permanent solution, open <strong>ant.bat</strong> file in bin folder of ANT installation (Same installation folder referred in ANT_HOME). And, at very first line, write below command and save it.</p>
<pre class="brush: bash; title: ; notranslate">
set ANT_OPTS=-Xmx1g
</pre>
<p style="text-align: justify;">I hope this article will help newbie to learn ant migration tool.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/salesforce/salesforce-migration-tool-ant/feed/</wfw:commentRss>
			<slash:comments>33</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2892</post-id>	</item>
		<item>
		<title>Method Parameters &#8211; Pass by Value or Pass by Reference</title>
		<link>https://www.jitendrazaa.com/blog/java/pass-by-value-and-pass-by-reference/</link>
					<comments>https://www.jitendrazaa.com/blog/java/pass-by-value-and-pass-by-reference/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Fri, 25 May 2012 10:59:08 +0000</pubDate>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[JAVA]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=2868</guid>

					<description><![CDATA[Difference between pass by Value and pass by Reference in Salesforce and other Object Oriented Programming language]]></description>
										<content:encoded><![CDATA[
<p class="justify">This topic has always been part of discussion where the answer is not satisfactory and convinced to others. Using this article, I will try to explain the concept of parameter passing in Apex Method. This Complete topic is applicable for Java or other programming languages as well.</p>



<p class="justify">Before moving ahead let&#8217;s have a summary on what is <strong>pass by value</strong> and <strong>pass by reference</strong>.</p>



<p class="justify"><strong>Pass by value</strong> means when a method is called, a <strong>second copy</strong> of the parameter variable is made in memory, and this copy is passed to the method as a parameter. This copy can be modified in the method, but the original variable in the caller is <strong>unchanged</strong>, and the changes to the copy are lost upon return.</p>



<p class="justify"><strong>Pass by reference</strong> means when a method is called, that <strong>actual</strong> variable is passed to the method.</p>



<p class="justify"><strong>Million dollar question: </strong>parameters in method are passed by value or pass by reference?<br><strong>Most of answers:</strong> primitive data types like Integer, Double are pass by value and Objects are pass by reference.</p>



<p class="justify"><br><strong>However, the above statement is not 100% true.</strong> I know I just invited <strong>controversy</strong> on this post. Be Patient with me and I would prove with actual example, feel free to run these examples in your Developer Console. </p>



<p class="justify"><strong>Correct Answer:</strong> <strong>parameters</strong> are passed by value in Apex as well as in Java. Where, in case of object the copy of reference is first made and then passed, therefore we can change the fields of object inside method however we <strong>cannot change the Object itself</strong>.</p>



<blockquote class="wp-block-quote justify is-layout-flow wp-block-quote-is-layout-flow"><p>Take a pause here and think what I just said. I&#8217;m saying, new variable copy created which points to same Object. So, it seems reference but variable technically itself is storing value which is address or reference of object.</p></blockquote>



<p class="justify"><br>Let&#8217;s discuss this in more detail. I am going to explain two scenarios in which I will try to change the field value and in second example I will try to change Object itself.</p>



<h3 class="wp-block-heading">Example 1</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Account a = new Account(); 
a.Name = 'Shivasoft'; 
a.Website = 'www.JitendraZaa.com'; 
changeWebsite(a); 
System.debug('Website - '+a.Website); 

public void changeWebsite(Account b) { 
    b.Website = 'www.salesforce.com'; 
}  
</pre></div>


<p>Output of above code is </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Website - www.salesforce.com
</pre></div>


<h4 class="wp-block-heading">What just happened in Example 1 </h4>



<div class="wp-block-image"><figure class="aligncenter is-resized"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/05/Salesforce-Pass-by-Value-or-Pass-by-Reference-1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/05/Salesforce-Pass-by-Value-or-Pass-by-Reference-1-1024x328.png?resize=768%2C246&#038;ssl=1" alt="Salesforce Pass by Value or Pass by Reference - Scenario 1" class="wp-image-2869" width="768" height="246"/></a><figcaption>Salesforce Pass by Value or Pass by Reference &#8211; Scenario 1</figcaption></figure></div>



<p class="justify"><strong>Explanation:</strong><br>As per code snippet, the object <strong>a</strong>  is supplied in method <em>changeWebsite()</em>. The parameter is actually passed  <strong>by value</strong>, where the copy of value a  is passed to object b which is <strong>memory address (aka reference)</strong>.  As we can see that both variable have reference of same object and hence whatever changes done by variable <em> b</em> on that object it will be applicable for variable  <em>a</em> also.</p>



<p>If you are still not convinced and think I&#8217;m wrong, wait for example 2.</p>



<h2 class="wp-block-heading">Example 2</h2>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Account a = new Account(); 
a.Name = 'Shivasoft'; 
a.Website = 'www.JitendraZaa.com'; 
changeWebsite(a); 
System.debug('Website - '+a.Website); 

public void changeWebsite(Account b) { 
    //Create New Object and try to replace old 
    b = new Account();
    b.Website = 'www.salesforce.com'; 
}  
</pre></div>


<p class="justify">Before I go further and reveal answer, let&#8217;s think what would be output ?</p>



<p class="justify">If you assumed method parameters are passed by reference then output should be </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Website - www.salesforce.com
</pre></div>


<p>However actual output is </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Website - www.JitendraZaa.com
</pre></div>


<h2 class="wp-block-heading">What just happened in example 2 ?</h2>



<div class="wp-block-image"><figure class="aligncenter is-resized"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/05/Salesforce-Pass-by-Value-or-Pass-by-Reference-2.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/05/Salesforce-Pass-by-Value-or-Pass-by-Reference-2-1024x341.png?resize=768%2C256&#038;ssl=1" alt="Salesforce Pass by Value or Pass by Reference - Scenario 2" class="wp-image-2870" width="768" height="256"/></a><figcaption>Salesforce Pass by Value or Pass by Reference &#8211; Scenario 2</figcaption></figure></div>



<p class="justify"><strong>Explanation:</strong><br>As per code snippet, the object <em>a</em>  is supplied in method <em>changeWebsite()</em>. Like I said, the parameter itself is actually passed <strong>by value</strong>, where the copy of value <em>a</em> is passed to object <em>b</em> which was reference. As we can see that both variable had reference of same object initially. However, inside the method new object is created and reference assigned to <em>b</em> <strong>and just now important event occurred</strong>. Refer above image for clear explanation</p>



<p class="justify">Previously b was pointing to old object, if it was really reference then it should impact object a. However now <em>a</em> and <em>b</em> variables point to different object. Whatever the changes done inside method, it will not be reflected outside as object <em>a</em> still have old reference. And hence after method execution when we check the value of object <em>a</em>, it is not affected because of method execution.</p>


<p>Salesforce documentation says :</p>
<blockquote>
<p>&#8220;In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.<br>Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call, and can&#8217;t be changed to point to another object. However, the values of the object&#8217;s fields can be changed in the method.&#8221;</p>
</blockquote>


<h2 class="wp-block-heading">Time for Best Practice</h2>



<p class="justify">Because of behavior of parameters are passed as a value, it is always best practice to return object back to calling method. <strong>JUST DON&#8217;T ASSUME</strong> that object is passed by reference and whatever happened inside method will reflect calling method.</p>



<p>So code would become </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Account a = new Account(); 
a.Name = 'Shivasoft'; 
a.Website = 'www.JitendraZaa.com'; 
a = changeWebsite(a); 
System.debug('Website - '+a.Website); 

public Account changeWebsite(Account b) { 
    //Create New Object and try to replace old 
    b = new Account();
    b.Website = 'www.salesforce.com'; 
    return b ;
}  
</pre></div>]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/pass-by-value-and-pass-by-reference/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2868</post-id>	</item>
		<item>
		<title>How to create Immutable Class in Java</title>
		<link>https://www.jitendrazaa.com/blog/java/how-to-create-immutable-class-in-java/</link>
					<comments>https://www.jitendrazaa.com/blog/java/how-to-create-immutable-class-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Fri, 03 Feb 2012 12:34:46 +0000</pubDate>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[final]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=2700</guid>

					<description><![CDATA[creating the Immutable class in Java with simple source code example]]></description>
										<content:encoded><![CDATA[<p style="text-align: justify;">We have heard the word &#8220;<strong>Immutable class</strong>&#8221; lots of time in Java. The best example is class &#8220;<strong><a title="Immutable nature of string" href="https://jitendrazaa.com/blog/java/immutable-nature-of-string-java/" target="_blank">String</a></strong>&#8220;. Immutable class is the class whose value cannot be changed throughout the life cycle. We cannot change the content of String class, everytime new reference is created when we change the content, that is the basic difference between <strong>String</strong> and <strong>StringBuffer</strong> Class.<br />
In this article, i will explain the step by step process to create the custom Immutable class in Java.<br />
Our class should not able to derived and for that we will declare our class as final. The values cannot be change and thats why we will declare all the variables as final and we will provide only the getter methods as we cannot write setters because of final variables.<br />
So to summarize, following steps needs to be taken:<span id="more-2700"></span></p>
<ol>
<li><strong>declare class as final</strong></li>
<li><strong>declare all variables as final</strong></li>
<li><strong>provide constructor to set the values</strong></li>
<li><strong>provide getter</strong></li>
</ol>
<p>Source code:</p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft.demo;

final class Immutable
{
	private final int val1;
	private final String val2;

	public Immutable(int a, String s)
	{
		val1 = a;
		val2 = s;
	}
	public int getVal1()
	{
		return val1;
	}
	public String getVal2()
	{
		return val2;
	}
}

public class ImmutableClassDemo {
	public static void main(String&#x5B;] args) {
		Immutable obj = new Immutable(10, &quot;ShivaSoft ...the supreme solution&quot;);
		System.out.println(obj.getVal1());
		System.out.println(obj.getVal2());
	}
}
</pre>
<p>Output :</p>
<blockquote><p>10<br />
ShivaSoft &#8230;the supreme solution</p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/how-to-create-immutable-class-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2700</post-id>	</item>
		<item>
		<title>Create SOAP message using Java</title>
		<link>https://www.jitendrazaa.com/blog/java/create-soap-message-using-java/</link>
					<comments>https://www.jitendrazaa.com/blog/java/create-soap-message-using-java/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Thu, 02 Feb 2012 17:46:37 +0000</pubDate>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[XML]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=2691</guid>

					<description><![CDATA[Step by Step Example of creating SOAP Message using core Java API]]></description>
										<content:encoded><![CDATA[<p>In this article, i am going to create the <a title="What is SOAP in Webservice" href="http://en.wikipedia.org/wiki/SOAP" target="_blank">SOAP </a>Message by using core Java Only. SOAP Stands for &#8221; Simple Object Access Protocol&#8221;, which is used to exchange the structured information via <a title="What is Web Services" href="http://en.wikipedia.org/wiki/Web_Service" target="_blank">Webservices</a>.</p>
<p>SOAP Message consist of following three parts:</p>
<ol>
<li>SOAP-ENV:Envelope</li>
<li>SOAP-ENV:Header</li>
<li>SOAP-ENV:Body</li>
</ol>
<p><figure id="attachment_2694" aria-describedby="caption-attachment-2694" style="width: 220px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/02/SOAP.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2694" title="SOAP Message Format for Web Services" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/02/SOAP.png?resize=220%2C235&#038;ssl=1" alt="SOAP Message Format for Web Services" width="220" height="235" /></a><figcaption id="caption-attachment-2694" class="wp-caption-text">SOAP Message Format for Web Services</figcaption></figure></p>
<p><span id="more-2691"></span>To create the SOAP, first we will need to create the object of &#8220;<strong>javax.xml.soap.MessageFactory</strong>&#8220;, then create object of &#8220;<strong>javax.xml.soap.SOAPMessage</strong>&#8220;. This object of &#8220;SOAPMessage&#8221; will have all the messages inside it in &#8220;<strong>javax.xml.soap.SOAPEnvelope</strong>&#8221; object. Every &#8220;Envelope&#8221; will have the &#8220;Header&#8221; and &#8220;Body&#8221; as shown in below program:</p>
<pre class="brush: csharp; title: ; notranslate">
package com.service.SOAPMain;

import java.io.FileOutputStream;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

public class CreateSOAPMessage {

	/**
	 * @param args
	 */
	public static void main(String&#x5B;] args) {
		try{
			MessageFactory factory = MessageFactory.newInstance();
			SOAPMessage soapMsg = factory.createMessage();
			SOAPPart part = soapMsg.getSOAPPart();

			SOAPEnvelope envelope = part.getEnvelope();
			SOAPHeader header = envelope.getHeader();
			SOAPBody body = envelope.getBody();

			header.addTextNode(&quot;Training Details&quot;);

			SOAPBodyElement element = body.addBodyElement(envelope.createName(&quot;JAVA&quot;, &quot;training&quot;, &quot;https://jitendrazaa.com/blog&quot;));
			element.addChildElement(&quot;WS&quot;).addTextNode(&quot;Training on Web service&quot;);

			SOAPBodyElement element1 = body.addBodyElement(envelope.createName(&quot;JAVA&quot;, &quot;training&quot;, &quot;https://jitendrazaa.com/blog&quot;));
			element1.addChildElement(&quot;Spring&quot;).addTextNode(&quot;Training on Spring 3.0&quot;);

			soapMsg.writeTo(System.out);

			FileOutputStream fOut = new FileOutputStream(&quot;SoapMessage.xml&quot;);
			soapMsg.writeTo(fOut);

			System.out.println();
			System.out.println(&quot;SOAP msg created&quot;);

		}catch(Exception e){
			e.printStackTrace();
		}

	}

}
</pre>
<p>As the output, one xml file of named &#8220;SoapMessage.xml&#8221; will be created and also printed on the console.</p>
<p><figure id="attachment_2695" aria-describedby="caption-attachment-2695" style="width: 576px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/02/SOAP-Messsage-Output-Java.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2695" title="SOAP Messsage Output - Java" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2012/02/SOAP-Messsage-Output-Java.png?resize=576%2C173&#038;ssl=1" alt="SOAP Messsage Output - Java" width="576" height="173" /></a><figcaption id="caption-attachment-2695" class="wp-caption-text">SOAP Messsage Output - Java</figcaption></figure></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/create-soap-message-using-java/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2691</post-id>	</item>
		<item>
		<title>Quartz framework tutorial with example &#8211; Schedule job in Java</title>
		<link>https://www.jitendrazaa.com/blog/java/quartz-framework-tutorial-with-example-schedule-job-in-java/</link>
					<comments>https://www.jitendrazaa.com/blog/java/quartz-framework-tutorial-with-example-schedule-job-in-java/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Thu, 22 Sep 2011 13:44:17 +0000</pubDate>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Quartz]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=2422</guid>

					<description><![CDATA[Tutorial of the Quartz framework for Java. Schedule job without loosing the performance of the application]]></description>
										<content:encoded><![CDATA[<p><strong>What is Quartz?</strong></p>
<p style="text-align: justify;">Quartz is a job scheduling system that can be integrated with, or used along side virtually any other software system. The term &#8220;<strong>job scheduler</strong>&#8221; seems to conjure different ideas for different people. As you read this tutorial, you should be able to get a firm idea of what we mean when we use this term, but in short, a job scheduler is a system that is responsible for executing (or notifying) other software components when a pre-determined (scheduled) time arrives.<br />
Quartz is quite flexible, and contains multiple usage paradigms that can be used separately or together, in order to achieve your desired behavior, and enable you to write your code in the manner that seems most &#8216;natural&#8217; to your project.<br />
Quartz is very light-weight, and requires very little setup/configuration &#8211; it can actually be used &#8216;out-of-the-box&#8217; if your needs are relatively basic.<br />
Quartz is fault-tolerant, and can persist (&#8216;remember&#8217;) your scheduled jobs between system restarts.<br />
Although Quartz is extremely useful for simply running certain system processes on given schedules, the full potential of Quartz can be realized when you learn how to use it to drive the flow of your application&#8217;s business processes.</p>
<p><strong>Why not just use<a title="Timer and TimerTask" href="https://jitendrazaa.com/blog/java/java-thread-timertask/"> java.util.Timer</a>?</strong><br />
Since JDK 1.3, Java has &#8220;built-in&#8221; timer capabilities, through the java.util.Timer and java.util.TimerTask classes &#8211; why would someone use Quartz rather than these standard features?<br />
There are many reasons! Here are a few:</p>
<ol>
<li>Timers have no persistence mechanism.</li>
<li>Timers have inflexible scheduling (only able to set start-time &amp; repeat interval, nothing based on dates, time of day, etc.)</li>
<li>Timers don&#8217;t utilize a thread-pool (one thread per timer)</li>
<li>Timers have no real management schemes &#8211; you&#8217;d have to write your own mechanism for being able to remember, organize and retrieve your tasks by name, etc.</li>
</ol>
<p><a title="Download jar" href="http://www.quartz-scheduler.org/downloads/" rel="nofollow"><span id="more-2422"></span>Download the jar files for Quartz from here</a>.</p>
<p>jar files neede are:</p>
<blockquote><p>quartz-2.0.2.jar<br />
slfj-log4j12-1.6.1.jar<br />
sl4j-api-1.6.1.jar<br />
log4j-1.2.14.jar</p></blockquote>
<p>Example with Source code:</p>
<p><span style="text-decoration: underline;"><strong>DisplayCurrentTime.java</strong></span></p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft.quartz;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class DisplayCurrentTime implements Job {
	Calendar c;
	Date d;
	SimpleDateFormat sdf;

	public DisplayCurrentTime()
	{}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		c = new GregorianCalendar();
		d = c.getTime();
		sdf = new SimpleDateFormat(&quot;d MMMMM yyyy - HH:mm:ss aaa&quot;);
		String msg = String.format(&quot;Job Name - %s, Current Time - %s&quot;, context.getJobDetail().getKey(), sdf.format(d));
		System.out.println(msg);
	}
}
</pre>
<p style="text-align: justify;">Create a class which should be executed by the quartz scheduler. The class must implement the interface &#8220;<strong>Job</strong>&#8220;. The Job interface has only one method &#8220;<strong>execute()</strong>&#8220;. The logic which should be executed must be written in this method. There must be the default constructor in class, as scheduler will create the object of that class at runtime.</p>
<p><span style="text-decoration: underline;"><strong>SimpleQuartzDemo.java</strong></span></p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft.quartz;

import java.text.ParseException;
import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleQuartzDemo {

	/**
	 * @param args
	 */
	public static void main(String&#x5B;] args) {
		SimpleQuartzDemo obj = new SimpleQuartzDemo();
		obj.runDemo();
	}

	public void runDemo() {
		try {

			// First we must get a reference to a scheduler
	        SchedulerFactory sf = new StdSchedulerFactory();
	        Scheduler sched = sf.getScheduler();

	        /**
	         * Job 1 using Trigger
	         */
			JobDetail job1 = JobBuilder.newJob(DisplayCurrentTime.class)
					.withIdentity(&quot;currentTime-Job-1&quot;, &quot;group1&quot;)
					.build();

			//This trigger will run every minute in infinite loop
			Trigger trigger1 = TriggerBuilder.newTrigger()
					.withIdentity(&quot;everyMinuteTrigger&quot;, &quot;group1&quot;)
					.startAt(new Date(System.currentTimeMillis()))
					.withSchedule( CronScheduleBuilder.cronSchedule( &quot;0 0/1 * 1/1 * ? *&quot;))
					.build();

			Date ft = sched.scheduleJob(job1, trigger1);
			sched.start();

			System.out.println(job1.getKey() + &quot; has been scheduled to run at: &quot; + ft);

			/**
			 * Job 2 using SimpleTrigger
			 */
			JobDetail job2 = JobBuilder.newJob(DisplayCurrentTime.class)
			.withIdentity(&quot;currentTime-Job-2&quot;, &quot;group1&quot;)
			.build();

			// get a &quot;nice round&quot; time a few seconds in the future....
			Date startTime = DateBuilder.nextGivenSecondDate(null, 10);

			//This trigger will run every 10 sec for 4 times
			SimpleTrigger trigger2 = TriggerBuilder.newTrigger()
            .withIdentity(&quot;fourTimesTrigger&quot;, &quot;group1&quot;)
            .startAt(startTime)
            .withSchedule( SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(10)
                    .withRepeatCount(4))
            .build();

	ft = sched.scheduleJob(job2, trigger2);
	sched.start();

	System.out.println(job1.getKey() + &quot; has been scheduled to run at: &quot; + ft);

	/**
	* Job 3 Using CronTrigger
	*/
	JobDetail job3 = JobBuilder.newJob(DisplayCurrentTime.class)
		.withIdentity(&quot;currentTime-Job-3&quot;, &quot;newGroup&quot;)
		.build();

	//run every 20 seconds
	CronTrigger trigger3 = TriggerBuilder.newTrigger()
            .withIdentity(&quot;twentySec&quot;, &quot;group2&quot;)
            .withSchedule( CronScheduleBuilder.cronSchedule( &quot;0/20 * * * * ?&quot;))
            .build();

	ft = sched.scheduleJob(job3, trigger3);
	sched.start();

		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

</pre>
<p>As you can see in above program, we have created the object of &#8220;<strong>StdSchedulerFactory</strong>&#8220;, which will schedule the job.<br />
Then we have created the job and trigger to be executed by quartz framework.</p>
<p style="text-align: justify;">In above example we have created three jobs and triggers.<br />
While creating job, we specify that which class (implements interface Job) will be executed by framework. And the &#8220;JobName&#8221; and &#8220;Thread group&#8221; in which it will be executed.</p>
<p>We have used three types of trigger in above example:</p>
<ol>
<li>Trigger</li>
<li>SimpleTrigger</li>
<li>CronTrigger</li>
</ol>
<ul>
<li>First trigger will execute every minute in infinite loop.</li>
<li>Second trigger will execute in every 10 sec for 4 times.</li>
<li>Third trigger will execute every 20 sec in infinite loop.</li>
</ul>
<p>As you can observe, Trigger 1 and Trigger 3 are scheduled using &#8220;<strong>Cron Expressions</strong>&#8220;.<br />
<a title="Create Cron Expression online" href="http://www.cronmaker.com/" rel="nofollow"> To create the Cron Expression easily or explain the cron expression, please refer this website</a>.</p>
<p><a title="Wiki Cron Job" href=" http://en.wikipedia.org/wiki/CRON_expression#CRON_expression" rel="nofollow">Read more about Cron Expression at WIKI.</a></p>
<p>The output of the program will be like :</p>
<blockquote><p>group1.currentTime-Job-1 has been scheduled to run at: Thu Sep 22 18:35:00 IST 2011<br />
group1.currentTime-Job-1 has been scheduled to run at: Thu Sep 22 18:34:40 IST 2011<br />
Job Name &#8211; group1.currentTime-Job-2, Current Time &#8211; 22 September 2011 &#8211; 18:34:40 PM<br />
Job Name &#8211; newGroup.currentTime-Job-3, Current Time &#8211; 22 September 2011 &#8211; 18:34:40 PM<br />
Job Name &#8211; group1.currentTime-Job-2, Current Time &#8211; 22 September 2011 &#8211; 18:34:50 PM<br />
Job Name &#8211; group1.currentTime-Job-1, Current Time &#8211; 22 September 2011 &#8211; 18:35:00 PM<br />
Job Name &#8211; group1.currentTime-Job-2, Current Time &#8211; 22 September 2011 &#8211; 18:35:00 PM<br />
Job Name &#8211; newGroup.currentTime-Job-3, Current Time &#8211; 22 September 2011 &#8211; 18:35:00 PM<br />
Job Name &#8211; group1.currentTime-Job-2, Current Time &#8211; 22 September 2011 &#8211; 18:35:10 PM<br />
Job Name &#8211; group1.currentTime-Job-2, Current Time &#8211; 22 September 2011 &#8211; 18:35:20 PM<br />
Job Name &#8211; newGroup.currentTime-Job-3, Current Time &#8211; 22 September 2011 &#8211; 18:35:20 PM</p></blockquote>
<p><a href="https://jitendrazaa.com/blog/wp-content/uploads/2011/09/QuartzDemo.txt">Download Quartz Source code and change extension from txt to rar</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/quartz-framework-tutorial-with-example-schedule-job-in-java/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2422</post-id>	</item>
		<item>
		<title>Step By Step Hibernate Tutorial Using eclipse WTP</title>
		<link>https://www.jitendrazaa.com/blog/java/hibernate/step-by-step-hibernate-tutorial-using-eclipse-wtp/</link>
					<comments>https://www.jitendrazaa.com/blog/java/hibernate/step-by-step-hibernate-tutorial-using-eclipse-wtp/#comments</comments>
		
		<dc:creator><![CDATA[Jitendra]]></dc:creator>
		<pubDate>Mon, 08 Aug 2011 07:33:43 +0000</pubDate>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[My SQL]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[JAVA]]></category>
		<guid isPermaLink="false">http://JitendraZaa.com/blog/?p=2347</guid>

					<description><![CDATA[Step By Step Hibernate (ORM Tool) Tutorial Using eclipse WTP]]></description>
										<content:encoded><![CDATA[<p>Hibernate is the ORM tool widely used in java community to persist the java object using Object Relational Mapping (ORM) concept. ORM reduces number of lines to interact with database with optimized query language which is <strong>Hibernate Query language (HQL)</strong>.</p>
<p>In this example, we will create a simple login application using hibernate tool of eclipse. We will use <strong>eclipse WTP</strong> (Web Tools Platform), to install &#8220;Hibernate Tools&#8221;. Follow below steps :</p>
<p>In Eclipse IDE, menu bar, select <strong>&#8220;Help&#8221; &gt;&gt; &#8220;Install New Software &#8230;&#8221;</strong> put the Eclipse update site URL <em>&#8220;http://download.jboss.org/jbosstools/updates/stable/helios&#8221;</em></p>
<p><figure id="attachment_2348" aria-describedby="caption-attachment-2348" style="width: 437px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Eclipse-Install-New-Software-Hibernate.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2348 " title="Eclipse Install New Software - Hibernate" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Eclipse-Install-New-Software-Hibernate.jpg?resize=437%2C186&#038;ssl=1" alt="Eclipse Install New Software - Hibernate" width="437" height="186" /></a><figcaption id="caption-attachment-2348" class="wp-caption-text">Eclipse Install New Software - Hibernate</figcaption></figure></p>
<p><span id="more-2347"></span></p>
<p>Select the tool and click on &#8220;Next&#8221;. Do not select all the tools; it will install all the unnecessary tools. We just need hibernate tools.</p>
<p>After installation, restart the eclipse.</p>
<p>If you don&#8217;t have the internet connection and want the offline method to add hibernate tools in eclipse. To install the Hibernate Tools, extract the <code>HibernateTools-3.X.zip</code> file and move all the files inside the features folder into the features folder of the eclipse installation directory and move all the files inside the plugins folder into the plugins folder of the ecilpse installation directory.</p>
<p>After restart, Go to <strong>Window | Open Perspective | Other</strong>, the following dialog box appears, select Hibernate and click the Ok button.</p>
<p><figure id="attachment_2349" aria-describedby="caption-attachment-2349" style="width: 347px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Eclipse-Hibernate-Perspective.jpg?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2349" title="Eclipse Hibernate Perspective" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Eclipse-Hibernate-Perspective.jpg?resize=347%2C422&#038;ssl=1" alt="Eclipse Hibernate Perspective" width="347" height="422" /></a><figcaption id="caption-attachment-2349" class="wp-caption-text">Eclipse Hibernate Perspective</figcaption></figure></p>
<p>Now let&#8217;s see how to define the object/relational mapping using the XML document. This document has <strong>.hbm.xml</strong> extension. We will now create the mapping between table and object of entity &#8220;user&#8221; which hold the data from database. So create the package <code>"in.shivasoft.pojo"</code> in src folder.<br />
Right click on project folder and select &#8220;<span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">Hibernate XML Mapping file (hbm.xml)</span><span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">&#8220;.</span></p>
<p><figure id="attachment_2351" aria-describedby="caption-attachment-2351" style="width: 436px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-XML-Mapping-file-Menu-in-Hibernate-Tools-of-Eclipse.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2351 " title="Hibernate XML Mapping file Menu in Hibernate Tools of Eclipse" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-XML-Mapping-file-Menu-in-Hibernate-Tools-of-Eclipse.png?resize=436%2C106&#038;ssl=1" alt="Hibernate XML Mapping file Menu in Hibernate Tools of Eclipse" width="436" height="106" /></a><figcaption id="caption-attachment-2351" class="wp-caption-text">Hibernate XML Mapping file Menu in Hibernate Tools of Eclipse</figcaption></figure></p>
<p>Then one popup will appear, click on &#8220;Next&#8221;.</p>
<p><figure id="attachment_2352" aria-describedby="caption-attachment-2352" style="width: 421px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Create-Hibernate-XML-Mapping-files.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2352 " title="Create Hibernate XML Mapping file(s)" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Create-Hibernate-XML-Mapping-files.png?resize=421%2C453&#038;ssl=1" alt="Create Hibernate XML Mapping file(s)" width="421" height="453" /></a><figcaption id="caption-attachment-2352" class="wp-caption-text">Create Hibernate XML Mapping file(s)</figcaption></figure></p>
<p>Select the pojo folder and give name &#8220;Users.hbm.xml&#8221; and click on finish.</p>
<p><figure id="attachment_2353" aria-describedby="caption-attachment-2353" style="width: 423px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/New-Hibernate-XML-Mapping-files-hbm.xml_.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2353 " title="New Hibernate XML Mapping files (hbm.xml)" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/New-Hibernate-XML-Mapping-files-hbm.xml_.png?resize=423%2C450&#038;ssl=1" alt="New Hibernate XML Mapping files (hbm.xml)" width="423" height="450" /></a><figcaption id="caption-attachment-2353" class="wp-caption-text">New Hibernate XML Mapping files (hbm.xml)</figcaption></figure></p>
<p>Now, either you can configure the settings from the UI like below snap:</p>
<p><figure id="attachment_2355" aria-describedby="caption-attachment-2355" style="width: 436px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-3.0-XML-Editor.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2355 " title="Hibernate 3.0 XML Editor" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-3.0-XML-Editor.png?resize=436%2C174&#038;ssl=1" alt="Hibernate 3.0 XML Editor" width="436" height="174" /></a><figcaption id="caption-attachment-2355" class="wp-caption-text">Hibernate 3.0 XML Editor</figcaption></figure></p>
<p>Or, write below code :</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;
&lt;hibernate-mapping&gt;
 &lt;class entity-name=&quot;Users&quot; name=&quot;in.shivasoft.pojo.Users&quot; table=&quot;Users&quot;&gt;
  &lt;meta attribute=&quot;description&quot;&gt;This class is used to save the info about users&lt;/meta&gt;
  &lt;id column=&quot;UserId&quot; name=&quot;UserId&quot; type=&quot;long&quot;/&gt;
  &lt;property column=&quot;FName&quot; name=&quot;FName&quot; type=&quot;string&quot;/&gt;
  &lt;property column=&quot;LName&quot;  name=&quot;LName&quot; type=&quot;string&quot;/&gt;
  &lt;property column=&quot;UserTypeId&quot; name=&quot;UserTypeId&quot; type=&quot;long&quot;/&gt;
  &lt;property column=&quot;UserName&quot; name=&quot;UserName&quot; type=&quot;string&quot;/&gt;
  &lt;property column=&quot;Email&quot; name=&quot;Email&quot; type=&quot;string&quot;/&gt;
  &lt;property column=&quot;Pwd&quot; name=&quot;Pwd&quot; type=&quot;string&quot;/&gt;
  &lt;property column=&quot;Note&quot; name=&quot;Note&quot; type=&quot;string&quot;/&gt;
  &lt;property column=&quot;IsActive&quot; name=&quot;IsActive&quot; type=&quot;boolean&quot;/&gt;
 &lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
<p>Now right click and select &#8220;hibernate configuration file&#8221;. One window will open, there select the &#8220;src&#8221; folder and click on next.</p>
<p><figure id="attachment_2357" aria-describedby="caption-attachment-2357" style="width: 435px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Configuration-File-cfg.xml_.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2357  " title="Hibernate Configuration File (cfg.xml)" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Configuration-File-cfg.xml_.png?resize=435%2C382&#038;ssl=1" alt="Hibernate Configuration File (cfg.xml)" width="435" height="382" /></a><figcaption id="caption-attachment-2357" class="wp-caption-text">Hibernate Configuration File (cfg.xml)</figcaption></figure></p>
<p>Enter detail like below screen and click on finish button.</p>
<p><figure id="attachment_2359" aria-describedby="caption-attachment-2359" style="width: 437px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Configuration-File-cfg.xml-Wizard.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2359 " title="Hibernate Configuration File (cfg.xml) Wizard" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Configuration-File-cfg.xml-Wizard.png?resize=437%2C382&#038;ssl=1" alt="Hibernate Configuration File (cfg.xml) Wizard" width="437" height="382" /></a><figcaption id="caption-attachment-2359" class="wp-caption-text">Hibernate Configuration File (cfg.xml) Wizard</figcaption></figure></p>
<p>After this add the Users.hbm.xml file to the newly generated xml configuration.</p>
<pre class="brush: xml; highlight: [12]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
		&quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
		&quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;property name=&quot;hibernate.connection.driver_class&quot;&gt; org.gjt.mm.mysql.Driver &lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.password&quot;&gt; root &lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.url&quot;&gt; jdbc:mysql://localhost/test &lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.username&quot;&gt; root &lt;/property&gt;
        &lt;property name=&quot;hibernate.dialect&quot;&gt; org.hibernate.dialect.MySQL5InnoDBDialect &lt;/property&gt;
        &lt;mapping resource=&quot;in/shivasoft/pojo/Users.hbm.xml&quot;/&gt;
    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>After the entire configuration, in the toolbar you can select &#8220;hibernate code generation tool&#8221;.</p>
<p><figure id="attachment_2361" aria-describedby="caption-attachment-2361" style="width: 325px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Configurations.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2361" title="Hibernate Code Generation Configurations" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Configurations.png?resize=325%2C132&#038;ssl=1" alt="Hibernate Code Generation Configurations" width="325" height="132" /></a><figcaption id="caption-attachment-2361" class="wp-caption-text">Hibernate Code Generation Configurations</figcaption></figure></p>
<p><figure id="attachment_2362" aria-describedby="caption-attachment-2362" style="width: 436px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Wizard-in-Eclipse.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2362 " title="Hibernate Code Generation Wizard in Eclipse" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Wizard-in-Eclipse.png?resize=436%2C216&#038;ssl=1" alt="Hibernate Code Generation Wizard in Eclipse" width="436" height="216" /></a><figcaption id="caption-attachment-2362" class="wp-caption-text">Hibernate Code Generation Wizard in Eclipse</figcaption></figure></p>
<p>Now select the Exporters tab and select &#8220;Use Java 5 Syntax&#8221;.</p>
<p><figure id="attachment_2363" aria-describedby="caption-attachment-2363" style="width: 418px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Wizard-in-Eclipse-Exporters-Tab.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2363 " title="Hibernate Code Generation Wizard in Eclipse-Exporters Tab" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Wizard-in-Eclipse-Exporters-Tab.png?resize=418%2C269&#038;ssl=1" alt="Hibernate Code Generation Wizard in Eclipse-Exporters Tab" width="418" height="269" /></a><figcaption id="caption-attachment-2363" class="wp-caption-text">Hibernate Code Generation Wizard in Eclipse-Exporters Tab</figcaption></figure></p>
<p>In refresh tab, select &#8220;<span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">The Project containing the selected resource</span>&#8220;.</p>
<p><figure id="attachment_2364" aria-describedby="caption-attachment-2364" style="width: 436px" class="wp-caption aligncenter"><a href="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Wizard-in-Eclipse-Refresh-Tab.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" class="size-full wp-image-2364 " title="Hibernate Code Generation Wizard in Eclipse- Refresh Tab" src="https://i0.wp.com/jitendrazaa.com/blog/wp-content/uploads/2011/08/Hibernate-Code-Generation-Wizard-in-Eclipse-Refresh-Tab.png?resize=436%2C239&#038;ssl=1" alt="Hibernate Code Generation Wizard in Eclipse- Refresh Tab" width="436" height="239" /></a><figcaption id="caption-attachment-2364" class="wp-caption-text">Hibernate Code Generation Wizard in Eclipse- Refresh Tab</figcaption></figure></p>
<p>Now click the run button to finish java code generation. Following code will be generated:</p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft.pojo;

// Generated Aug 1, 2011 7:02:59 PM by Hibernate Tools 3.4.0.CR1

/**
 * Users generated by hbm2java
 */
public class Users implements java.io.Serializable {

	private long UserId;
	private String FName;
	private String LName;
	private long UserTypeId;
	private String UserName;
	private String Email;
	private String Pwd;
	private String Note;
	private boolean IsActive;

	public Users() {
	}

	public Users(long UserId) {
		this.UserId = UserId;
	}

	public Users(long UserId, String FName, String LName, long UserTypeId,
			String UserName, String Email, String Pwd, String Note,
			boolean IsActive) {
		this.UserId = UserId;
		this.FName = FName;
		this.LName = LName;
		this.UserTypeId = UserTypeId;
		this.UserName = UserName;
		this.Email = Email;
		this.Pwd = Pwd;
		this.Note = Note;
		this.IsActive = IsActive;
	}

	public long getUserId() {
		return this.UserId;
	}

	public void setUserId(long UserId) {
		this.UserId = UserId;
	}

	public String getFName() {
		return this.FName;
	}

	public void setFName(String FName) {
		this.FName = FName;
	}

	public String getLName() {
		return this.LName;
	}

	public void setLName(String LName) {
		this.LName = LName;
	}

	public long getUserTypeId() {
		return this.UserTypeId;
	}

	public void setUserTypeId(long UserTypeId) {
		this.UserTypeId = UserTypeId;
	}

	public String getUserName() {
		return this.UserName;
	}

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

	public String getEmail() {
		return this.Email;
	}

	public void setEmail(String Email) {
		this.Email = Email;
	}

	public String getPwd() {
		return this.Pwd;
	}

	public void setPwd(String Pwd) {
		this.Pwd = Pwd;
	}

	public String getNote() {
		return this.Note;
	}

	public void setNote(String Note) {
		this.Note = Note;
	}

	public boolean isIsActive() {
		return this.IsActive;
	}

	public void setIsActive(boolean IsActive) {
		this.IsActive = IsActive;
	}

}
</pre>
<p>Now create the</p>
<pre>HibernateUtil</pre>
<p>class. The HibernateUtil class helps in creating the <span class="Apple-style-span" style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px; white-space: pre;">SessionFactory </span>from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread. Here the static singleton pattern is used to instantiate the SessionFactory. The implementation of the HibernateUtil class is shown below.</p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft.util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;

	static {

		try {

			sessionFactory = new Configuration().configure()
			.buildSessionFactory();

		} catch (Throwable ex) {

			System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);

			throw new ExceptionInInitializerError(ex);

		}

	}

	public static SessionFactory getSessionFactory() {

		return sessionFactory;

	}
}
</pre>
<p>Now, create the test application having main method which will demonstrate that how data is saved:</p>
<pre class="brush: java; title: ; notranslate">
package in.shivasoft.test;

import in.shivasoft.pojo.Users;
import in.shivasoft.util.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class TestMain {

	/**
	 * @param args
	 */
	public static void main(String&#x5B;] args) {
		TestMain obj = new TestMain();
		//obj.saveRecord();
		obj.updateUser(12);
		obj.deleteUser(13);
		obj.getList();
	}

	public void saveRecord()
	{
		Users u = new Users(0, &quot;Jitendra&quot;, &quot;Zaa&quot;, 1, &quot;jitendra.zaa&quot;, &quot;jitendra.zaa@JitendraZaa.com&quot;, &quot;test&quot;, &quot;this is note&quot;, true);
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			session.save(u);
			transaction.commit();
			System.out.println(&quot;Data Saved&quot;);
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally{session.close();}

	}
	public void deleteUser(long UserId)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			Users u = (Users)session.get(Users.class,UserId);
			session.delete(u);
			transaction.commit();
			System.out.println(&quot;Data Deleted&quot;);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally{
			session.close();
		}
	}
	public void updateUser(long UserId)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			Users u = (Users)session.get(Users.class,UserId);
			u.setFName(&quot;ShivaSoft&quot;);
			transaction.commit();
			System.out.println(&quot;Data Updated&quot;);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally{
			session.close();
		}
	}

	public void getList()
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			List&lt;Users&gt; uList = session.createQuery(&quot;from Users&quot;).list();
			for(Users u : uList)
			{
				System.out.println(&quot;First Name - &quot;+u.getFName());
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally{
			session.close();
		}
	}
}
</pre>
<p>Needed jar files :</p>
<blockquote><p>antlr-2.7.6.jar<br />
commons-collections-3.1.jar<br />
dom4j-1.6.1.jar<br />
hibernate-core.3.3.1.GA.jar<br />
javassist-3.9.0.GA.jar<br />
jta-1.1.jar<br />
mysql-connector-java-5.1.1.17-bin.jar<br />
slf4j-api-1.6.1.jar<br />
slf4j-api-1.6.1-tests.jar<br />
slf4j-slf4j-simple-2.0.jar</p></blockquote>
]]></content:encoded>
					
					<wfw:commentRss>https://www.jitendrazaa.com/blog/java/hibernate/step-by-step-hibernate-tutorial-using-eclipse-wtp/feed/</wfw:commentRss>
			<slash:comments>31</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2347</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: www.jitendrazaa.com @ 2026-07-17 10:12:29 by W3 Total Cache
-->