<?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>By Programmer For Programmer</title>
	<atom:link href="http://byprogrammerforprogrammer.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://byprogrammerforprogrammer.com</link>
	<description>Here I lay down the useful tips, tricks and utilities for programmers like myself.</description>
	<lastBuildDate>Thu, 15 Sep 2011 19:59:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Handy DWR ErrorHandler Callstack Function</title>
		<link>http://byprogrammerforprogrammer.com/2011/09/handy-dwr-errorhandler-callstack-function/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=handy-dwr-errorhandler-callstack-function</link>
		<comments>http://byprogrammerforprogrammer.com/2011/09/handy-dwr-errorhandler-callstack-function/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 19:49:41 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=121</guid>
		<description><![CDATA[Preamble I shared this with the DWR mailing list, and the guys thought it was useful, so I&#8217;m posting here to share with the world. Feel free to use this code under the Open Software License v. 3.0 (OSL-3.0). Background I wanted to have a &#8220;show technical details&#8221; link on our error popup that said [...]]]></description>
			<content:encoded><![CDATA[<h2>Preamble</h2>
<p>I shared this with the <a href="http://directwebremoting.org">DWR</a> <a href="http://dwr.2114559.n2.nabble.com/DWR-Users-f2114559.html">mailing list</a>, and the guys thought it was useful, so I&#8217;m posting here to share with the world.</p>
<p>Feel free to use this code under the <a href="http://www.opensource.org/licenses/OSL-3.0">Open Software License v. 3.0 (OSL-3.0)</a>.</p>
<h2>Background</h2>
<p>I wanted to have a &#8220;show technical details&#8221; link on our error popup that said what happened when an error occurred.</p>
<p>Environment:</p>
<ul>
<li>DWR 2.0.5</li>
<li>ExtJS 3.3.1</li>
</ul>
<div>Three classes:</div>
<div>
<ul>
<li><strong>BatchMapObtainer</strong> - This class retrieves the &#8220;batch map&#8221; from the current error handler callstack</li>
<li><strong>BatchMapWrapper</strong> - Wraps the &#8220;batch map&#8221; in order to wrap DWR-specific details</li>
<li><strong>ErrorHelper</strong> - Uses the above in order to construct a message for the user</li>
</ul>
</div>
<h2>The Code</h2>
<h5>FILE: BatchMapObtainer.js</h5>
<pre>Ext.ns('jx.core.dwr');

/**
 * @class jx.core.dwr.BatchMapObtainer
 * @static
 */
jx.core.dwr.BatchMapObtainer = function() {

	var isArgDwrBatch = function(arg) {
		return Ext.isDefined(arg.httpMethod) &amp;&amp; Ext.isDefined(arg.map);
	};

	var getDwrBatchFromArguments = function(args) {
		for (var i=0; i&lt;args.length; i++) {
			if (isArgDwrBatch(args[i])) {
				return args[i];
			}
		}
		return null;
	};

	var getBatchMapFromCallStack = function() {
		var currentFn = arguments.callee;
		var dwrBatch;
		var visitedFunctions = [];
		while (currentFn &amp;&amp; !dwrBatch) {
			dwrBatch = getDwrBatchFromArguments((currentFn.caller &amp;&amp; currentFn.caller.arguments) || []);
			if (visitedFunctions.indexOf(currentFn) !== -1) {
				currentFn = null;
			}
			else {
				visitedFunctions.push(currentFn);
				currentFn = currentFn.caller;
			}
		}
		return dwrBatch &amp;&amp; dwrBatch.map;
	};

	return {

		/**
                 * @method buildFromCallStack
                 * @static
		 * Tries to obtain a DWR batch map from the current call stack.
		 */
		obtainFromCallStack: function() {
			return getBatchMapFromCallStack();
		}

	};

}();</pre>
<h5></h5>
<h5>FILE: BatchMapWrapper.js</h5>
<pre>Ext.ns('jx.core.dwr');

/**
 * @class jx.core.dwr.BatchMapWrapper
 * @extends Object
 * Use to parse parameters from the DWR batch map.
 */
jx.core.dwr.BatchMapWrapper = Ext.extend(Object, {

	batchMap: null,

	constructor: function(batchMap) {
		this.batchMap = batchMap;
	},

	getBatchId: function() {
		return this.batchMap.batchId;
	},

	getBatchMap: function() {
		return this.batchMap;
	},

	/**
	 * @return Array of call details.  Each detail has "method" and "params" attributes
	 */
	getDwrCallDetails: function() {
		var callDetails = [];
		for (var i=0; this.hasCallDetailsFor(i); i++) {
			var params = [];
			for (var j=0; this.isParamDefined(i, j); j++) {
				params.push(this.getParamAt(i, j));
			}
			callDetails.push({
				method: this.getDwrCallNameFor(i),
				params: params
			});
		}
		return callDetails;
	},

	// private
	hasCallDetailsFor: function(callIndex) {
		return Ext.isDefined(this.batchMap['c' + callIndex + '-id']);
	},

	// private
	isParamDefined: function(callIndex, paramIndex) {
		return Ext.isDefined(this.getParamAt(callIndex, paramIndex));
	},

	// private
	getParamAt: function(callIndex, paramIndex) {
		return this.batchMap['c' + callIndex + '-param' + paramIndex];
	},

	// private
	getDwrCallNameFor: function(callIndex) {
		return this.getScripNameFor(callIndex) + '.' + this.getMethodNameFor(callIndex);
	},

	// private
	getScripNameFor: function(callIndex) {
		return this.batchMap['c' + callIndex + '-scriptName'];
	},

	// private
	getMethodNameFor: function(callIndex) {
		return this.batchMap['c' + callIndex + '-methodName'];
	}

});

/**
 * @method buildFromCallStack
 * @static
 * Tries to obtain a BatchMapWrapper wrapped around the "batch map" for the current call stack
 */
jx.core.dwr.BatchMapWrapper.buildFromCallStack = function() {
	var batchMap = jx.core.dwr.BatchMapObtainer.obtainFromCallStack();
	return batchMap ? new jx.core.dwr.BatchMapWrapper(batchMap) : null;
};</pre>
<h5></h5>
<h5>FILE: ErrorHelper.js</h5>
<pre>Ext.ns('jx.core.dwr');

/**
 * @class jx.core.dwr.ErrorHelper
 * @static
 * Helper to gain information about DWR calls.
 */
jx.core.dwr.ErrorHelper = function() {

	var getBaseDwrCallMessage = function(batchMapWrapper) {
		var message = '';
		var dwrCallDetails = batchMapWrapper.getDwrCallDetails();
		if (Ext.isArray(dwrCallDetails)) {
			for (var i=0; i&lt;dwrCallDetails.length; i++) {
				var details = dwrCallDetails[i];
				message += "DWR Call: " + details.method + "\nParams: " + Ext.util.JSON.encode(details.params);
			}
		}
		return message;
	};

	var getFullBatchMapMessage = function(batchMapWrapper) {
		var message = "Batch Map:";
		var batchMap = batchMapWrapper.getBatchMap();
		for (var key in batchMap) {
			if (!Ext.isFunction(batchMap[key])) {
				message += "\n   " + key + ": " + batchMap[key];
			}
		}
		return message;
	};

	return {

		getDwrCallDetailsFromCallStack: function() {
			var batchMapWrapper = jx.core.dwr.BatchMapWrapper.buildFromCallStack();
			return batchMapWrapper &amp;&amp; batchMapWrapper.getDwrCallDetails();
		},

		buildDwrCallDetailsMessageFromCallStack: function() {
			var message = '';
			var batchMapWrapper = jx.core.dwr.BatchMapWrapper.buildFromCallStack();
			if (batchMapWrapper) {
				message += getBaseDwrCallMessage(batchMapWrapper);
				message += "\n\n";
				message += getFullBatchMapMessage(batchMapWrapper);
				message += "\n\n";
			}
			return message;
		}

	};

}();</pre>
<h5></h5>
<h5>Example Usage:</h5>
<p>In DWR errorHandler, simply:</p>
<pre>var msg = jx.core.dwr.ErrorHelper.buildDwrCallDetailsMessageFromCallStack();
var id = Ext.id();
var html = '&lt;a href="" onclick="document.getElementById(\'' + id + '\').style.display=\'block\'; return false;"&gt;' +
	'Show Technical Details&lt;/a&gt;&lt;br /&gt;' +
	'&lt;div id="' + id + '" style="display: none;"&gt;&lt;textarea style="width: 100%; height: 150px;"&gt;' + msg +
	'&lt;/textarea&gt;&lt;/div&gt;';
Ext.Msg.alert("Error", html);</pre>
<p>Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2011/09/handy-dwr-errorhandler-callstack-function/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploy Eclipse Java changes to Tomcat without restarting (and other servers too)</title>
		<link>http://byprogrammerforprogrammer.com/2011/09/deploy-eclipse-java-changes-to-tomcat-without-restarting-and-other-servers-too/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=deploy-eclipse-java-changes-to-tomcat-without-restarting-and-other-servers-too</link>
		<comments>http://byprogrammerforprogrammer.com/2011/09/deploy-eclipse-java-changes-to-tomcat-without-restarting-and-other-servers-too/#comments</comments>
		<pubDate>Fri, 09 Sep 2011 22:21:35 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Recommendation]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=117</guid>
		<description><![CDATA[If you are like me, you work on a web application, and every time you edit Java classes, you need to restart your server to see the changes.  Sometimes it takes awhile to get back to where you were in the app to test, which makes this process especially painful and time-consuming. Well I just [...]]]></description>
			<content:encoded><![CDATA[<p>If you are like me, you work on a web application, and every time you edit Java classes, you need to restart your server to see the changes.  Sometimes it takes awhile to get back to where you were in the app to test, which makes this process especially painful and time-consuming.</p>
<p>Well I just stumbled across this amazing tool the other day called <a href="http://www.zeroturnaround.com/jrebel/">JRebel</a>.  Basically it let&#8217;s you setup your Eclipse environment so that when you save Java files (or more specifically, when it picks up on new compiled classes), it redeploys the changes to your environment, and they take affect immediately.</p>
<p>I was especially shocked when I changed one of my Spring XML files, and it rebuilt and redeployed my Spring config!</p>
<p>This has already saved me tons of time in the short while I&#8217;ve been using it.  You should really check it out.</p>
<p><a href="http://www.zeroturnaround.com/jrebel/">http://www.zeroturnaround.com/jrebel/</a></p>
<p>(PS: I don&#8217;t get anything for recommending JRebel&#8230; I was just really impressed by it)</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2011/09/deploy-eclipse-java-changes-to-tomcat-without-restarting-and-other-servers-too/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL, SQL Server, Oracle: UPDATE statement with JOIN</title>
		<link>http://byprogrammerforprogrammer.com/2011/08/mysql-sql-server-oracle-update-statement-with-join/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mysql-sql-server-oracle-update-statement-with-join</link>
		<comments>http://byprogrammerforprogrammer.com/2011/08/mysql-sql-server-oracle-update-statement-with-join/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 22:06:46 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Example Code]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=107</guid>
		<description><![CDATA[Background So at my current job at jamasoftware.com, our Contour application supports the three major databases MySQL, SQL Server, and Oracle (sorry PostgreSQL fans&#8230; maybe soon).  Recently I needed to run UPDATE statements with JOINs, and had to learn the different syntax for each of these databases.  I thought I would share all of them [...]]]></description>
			<content:encoded><![CDATA[<h5>Background</h5>
<p>So at my current job at <a title="Jama" href="http://jamasoftware.com" target="_blank">jamasoftware.com</a>, our Contour application supports the three major databases MySQL, SQL Server, and Oracle (sorry PostgreSQL fans&#8230; maybe soon).  Recently I needed to run UPDATE statements with JOINs, and had to learn the different syntax for each of these databases.  I thought I would share all of them side-by-side, so that you can easily see the differences:</p>
<h5>Our Simplified Schema:</h5>
<pre>Table: ORGANIZATION
id int primary key

Table: PROJECT
id int primary key
organizationId int foreign key ORGANIZATION(id)

Table: DOCUMENT
id int primary key
projectId int foreign key ORGANIZATION(id)
organizationId int null</pre>
<h5>The Task</h5>
<p>Update all DOCUMENT records with the organizationId of their corresponding project</p>
<h5>The Solution</h5>
<pre>MySQL:
UPDATE DOCUMENT d
    INNER JOIN PROJECT p ON d.projectId = p.id
SET d.organizationId = p.organizationId
WHERE d.organizationId IS NULL;

SQL Server:
UPDATE d
SET d.organizationId = p.organizationId
FROM DOCUMENT d
    INNER JOIN PROJECT p ON d.projectId = p.id
WHERE d.organizationId IS NULL

Oracle:
UPDATE (SELECT d.organizationId AS docOrgId, p.organizationId AS projectOrgId
        FROM DOCUMENT d
            INNER JOIN PROJECT p ON d.projectId = p.id
        WHERE d.organizationId IS NULL) v
set v.docOrgId = v.projectOrgId</pre>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2011/08/mysql-sql-server-oracle-update-statement-with-join/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Script to check MySQL long running transactions</title>
		<link>http://byprogrammerforprogrammer.com/2011/02/script-to-check-mysql-long-running-transactions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=script-to-check-mysql-long-running-transactions</link>
		<comments>http://byprogrammerforprogrammer.com/2011/02/script-to-check-mysql-long-running-transactions/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 17:51:29 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[cron]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=95</guid>
		<description><![CDATA[We had an issue at work recently where our MySQL transactions weren&#8217;t being properly rolled back or committed, and we ended up with transactions that would last several hours, locking tables, until we killed them manually. After fixing the true issue, I wrote this script to check MySQL InnoDB status every 15 minutes (with cron) [...]]]></description>
			<content:encoded><![CDATA[<p>We had an issue at work recently where our MySQL transactions weren&#8217;t being properly rolled back or committed, and we ended up with transactions that would last several hours, locking tables, until we killed them manually.  After fixing the true issue, I wrote this script to check MySQL InnoDB status every 15 minutes (with cron) and email us if there are any transactions lasting longer than 15 seconds.</p>
<p>For testing, you can also pass in as the first argument a file name that contains some example &#8220;show innodb status&#8221; output to make sure it works.</p>
<pre>#!/usr/bin/sh
DB_USER=root
DB_PASS=password
STATUS_FILE=/tmp/innodb_status.out
TMP_FILE=/tmp/long_tx_check.out
MAIL_TO="email1@asdf.com;email2@asdf.com"
TX_THRESH=15

if [ -z $1 ]
then
	mysql -u $DB_USER -p$DB_PASS -A -e "show innodb status\G" &gt; $STATUS_FILE
else
	STATUS_FILE=$1
fi

cat $STATUS_FILE | awk "/TRANSACTIONS/,/FILE I/ { t=1 } /ACTIVE/ { if (\$5 &gt; $TX_THRESH &amp;&amp; t == 1) { on=1 } else { on=0 } } /thread id/ { if (on==1) { print \$0 } }" &gt; $TMP_FILE

FIRSTLINE=""
read -r FIRSTLINE &lt; "$TMP_FILE"
if [ "$FIRSTLINE" != "" ]
then
	echo "LONG RUNNING TRANSACTION FOUND... SENDING EMAIL"
	mail -s "LONG RUNNING TRANSACTION!!" "$MAIL_TO" &lt; $TMP_FILE
else
	echo "No long running transactions found"
fi</pre>
<p>This code was based off code taken from <a href="http://www.facebook.com/note.php?note_id=172915805932">here</a>.  Always give credit where credit is due <img src='http://byprogrammerforprogrammer.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2011/02/script-to-check-mysql-long-running-transactions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hibernate: Execute INSERT immediately on save(), especially Oracle</title>
		<link>http://byprogrammerforprogrammer.com/2011/01/hibernate-execute-insert-immediately-on-save-especially-oracle/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hibernate-execute-insert-immediately-on-save-especially-oracle</link>
		<comments>http://byprogrammerforprogrammer.com/2011/01/hibernate-execute-insert-immediately-on-save-especially-oracle/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 22:50:40 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Example Code]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=89</guid>
		<description><![CDATA[Here&#8217;s the situation: Auto-flush is OFF (either FlushMode.COMMIT or FlushMode.MANUAL) You save() or saveOrUpdate() an object with Hibernate Your object is not using IDENTITY for its id Later (possible unrelated) code tries to get the saved object back by id If you found this post, you probably know that no object is returned with the [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the situation:</p>
<ul>
<li>Auto-flush is OFF (either FlushMode.COMMIT or FlushMode.MANUAL)</li>
<li>You save() or saveOrUpdate() an object with Hibernate</li>
<li>Your object is not using IDENTITY for its id</li>
<li>Later (possible unrelated) code tries to get the saved object back by id</li>
</ul>
<p>If you found this post, you probably know that no object is returned with the given id.  This is because the session has not been flushed.</p>
<p>So just flush the session before retrieval, right?  Well yes, but not so fast.  Most people, including myself, don&#8217;t want to have a big &#8220;session.flush()&#8221; in the middle of service layer code.</p>
<p>My solution was to register a &#8220;save&#8221; and &#8220;save-update&#8221; event listener with Hibernate, and process the insert immediately after.</p>
<p>Register lisenters (using Spring):</p>
<pre>&lt;bean id="sessionFactory"&gt;
    &lt;property name="eventListeners"&gt;
        &lt;map&gt;
            &lt;entry key="save"&gt;
                &lt;bean class="com.jamasoftware.contour.util.hibernate.ExecuteImmediateSaveEventListener"/&gt;
            &lt;/entry&gt;
            &lt;entry key="save-update"&gt;
                &lt;bean class="com.jamasoftware.contour.util.hibernate.ExecuteImmediateSaveOrUpdateEventListener"/&gt;
            &lt;/entry&gt;
        &lt;/map&gt;
    &lt;/property&gt;
&lt;/bean&gt;</pre>
<p>Listeners:</p>
<pre>
public class ExecuteImmediateSaveEventListener extends DefaultSaveEventListener {

	private static final long serialVersionUID = 1L;

	protected Serializable performSaveOrReplicate(
			Object entity,
			EntityKey key,
			EntityPersister persister,
			boolean useIdentityColumn,
			Object anything,
			EventSource source,
			boolean requiresImmediateIdAccess) {
		Serializable id = super.performSaveOrReplicate(
				entity,
				key,
				persister,
				useIdentityColumn,
				anything,
				source,
				requiresImmediateIdAccess);
		if (!useIdentityColumn) {
			immediatelyInsert(source);
		}
		return id;
	}

	private void immediatelyInsert(EventSource source) {
		source.getActionQueue().executeInserts();
	}

}
</pre>
<pre>
public class ExecuteImmediateSaveOrUpdateEventListener extends DefaultSaveOrUpdateEventListener {

	private static final long serialVersionUID = 1L;

	protected Serializable performSaveOrReplicate(
			Object entity,
			EntityKey key,
			EntityPersister persister,
			boolean useIdentityColumn,
			Object anything,
			EventSource source,
			boolean requiresImmediateIdAccess) {
		Serializable id = super.performSaveOrReplicate(
				entity,
				key,
				persister,
				useIdentityColumn,
				anything,
				source,
				requiresImmediateIdAccess);
		if (!useIdentityColumn) {
			immediatelyInsert(source);
		}
		return id;
	}

	private void immediatelyInsert(EventSource source) {
		source.getActionQueue().executeInserts();
	}

}
</pre>
<p>This code was tested with Hibernate 3.3.1.</p>
<p>This problem was especially annoying to me because I work with an application that can be deployed on many databases.  MySQL and SQL Server, for example, allow IDENTITY columns, which Hibernate will immediately execute INSERT statements for since it needs to in order to get their id.  But Oracle doesn&#8217;t work this way, and the execution of the INSERT statements goes onto the ActionQueue, since it uses a SEQUENCE.  What happens then, is that you end up with code that works for one database that doesn&#8217;t work for another.</p>
<p>Using the above listeners, my code now acts the same whether using IDENTITY columns or not.</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2011/01/hibernate-execute-insert-immediately-on-save-especially-oracle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JProfiler Helping Out With HTML4Java</title>
		<link>http://byprogrammerforprogrammer.com/2010/04/jprofiler-helping-out-with-html4java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jprofiler-helping-out-with-html4java</link>
		<comments>http://byprogrammerforprogrammer.com/2010/04/jprofiler-helping-out-with-html4java/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 16:57:00 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=86</guid>
		<description><![CDATA[Just wanted to give props real quick to the awesome profiler JProfiler (http://www.ej-technologies.com/products/jprofiler/overview.html) for providing me with an open-source license to profile my open-source project HTML4Java (https://sourceforge.net/projects/html4java/). The open-source community is so friendly .]]></description>
			<content:encoded><![CDATA[<p>Just wanted to give props real quick to the awesome profiler JProfiler (<a href="http://www.ej-technologies.com/products/jprofiler/overview.html">http://www.ej-technologies.com/products/jprofiler/overview.html</a>) for providing me with an open-source license to profile my open-source project HTML4Java (<a href="https://sourceforge.net/projects/html4java/">https://sourceforge.net/projects/html4java/</a>).  The open-source community is so friendly <img src='http://byprogrammerforprogrammer.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2010/04/jprofiler-helping-out-with-html4java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Nested Loops: break or continue</title>
		<link>http://byprogrammerforprogrammer.com/2010/03/java-nested-loops-break-or-continue/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-nested-loops-break-or-continue</link>
		<comments>http://byprogrammerforprogrammer.com/2010/03/java-nested-loops-break-or-continue/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 23:58:37 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=82</guid>
		<description><![CDATA[Ever wanted to continue from a doubly-nested for loop? How about break from a switch statement more than one level deep? Simple! First you have to label your loop, and then put that label name after the break or continue keyword. &#8220;continue&#8221; example: fooloop: for(foo: foos) { ... barloop: for(bar : bars) { ... for [...]]]></description>
			<content:encoded><![CDATA[<p>Ever wanted to <code>continue</code> from a doubly-nested <code>for</code> loop?  How about <code>break</code> from a <code>switch</code> statement more than one level deep?</p>
<p>Simple!  First you have to label your loop, and then put that label name after the <code>break</code> or <code>continue</code> keyword.</p>
<p>&#8220;continue&#8221; example:</p>
<pre>
fooloop: for(foo: foos) {
    ...
    barloop: for(bar : bars) {
        ...
        for (blotto : blottos) {
            ...
            if (next_innermost_loop)
                continue; //normal
            if (next_middle_loop)
                continue barloop; //goes to the next iteration of "barloop"
            if (next_outer_loop)
                continue fooloop; //goes to the next iteration of the outermost loop, "fooloop"
        }
    }
}
</pre>
<p>&#8220;break&#8221; example:</p>
<pre>
fooswitch: switch(foo) {
    case 1:
        ...
        break;
    case 2:
        ...
       switch(bar) {
            ...
            if (break_this_switch)
                break; //normal
            if (break_outer_switch)
                break fooswitch; // breaks out of the out switch, "fooswitch"
        }
}
</pre>
<p>While most might consider this bad practice, when writing some scratch code to do some one-off task that only you will ever use, sometimes it&#8217;s nice to use a shortcut <img src='http://byprogrammerforprogrammer.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2010/03/java-nested-loops-break-or-continue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Generics in Static Methods</title>
		<link>http://byprogrammerforprogrammer.com/2010/01/java-generics-in-static-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-generics-in-static-methods</link>
		<comments>http://byprogrammerforprogrammer.com/2010/01/java-generics-in-static-methods/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 00:24:44 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Example Code]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=76</guid>
		<description><![CDATA[Ever needed to use generics in a static method but didn't know you could?  Here's how...]]></description>
			<content:encoded><![CDATA[<p>Every time I feel like I know all the Java syntax there is, I learn something new <img src='http://byprogrammerforprogrammer.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Let&#8217;s say you have a class with a static constructor that returns a map, and that map is typed and does fancy things, but you still want to use generics from wherever you are using the Map.</p>
<pre>
public class MyClass {

    public static final &lt;K,V&gt; Map&lt;K,V&gt; createMyMap() {
        ...
        return map;
    }
}
</pre>
<p>If you are like me, you hate hate hate casting to generics, but you are forced to do that or have a big ugly <code>@SuppressWarnings("unchecked")</code> on the method that you access this method.</p>
<pre>
@SuppressWarnings("unchecked")
function Map&lt;String, Object&gt; getMyMap() {
    return MyClass.createMyMap();
}
</pre>
<p><strong>Well not anymore!</strong>.  Today I just learned (by looking through some Java source code) that you can assign generics on your static calls by using the following syntax.</p>
<pre>
function Map&lt;String, Object&gt; getMyMap() {
    return MyClass.&lt;String, Object&gt;createMyMap();
}
</pre>
<p>Just put the generics right after the period and before the method name.  Easy.</p>
<p>I learned this while trying to figure out why <code>java.util.Collections</code> has static fields <code>EMPTY_LIST</code>, <code>EMPTY_SET</code>, and <code>EMPTY_MAP</code>, and also static methods <code>emptyList()</code>, <code>emptySet</code>, and <code>emptyMap</code>.  It says right in the code, &#8220;Unlike this method, the field does not provide type safety&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2010/01/java-generics-in-static-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Eclipse/Tomcat publishing lockup: &#8220;Could not delete file&#8230; may be locked by another process&#8221;</title>
		<link>http://byprogrammerforprogrammer.com/2009/12/eclipsetomcat-publishing-lockup-could-not-delete-file-may-be-locked-by-another-process/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=eclipsetomcat-publishing-lockup-could-not-delete-file-may-be-locked-by-another-process</link>
		<comments>http://byprogrammerforprogrammer.com/2009/12/eclipsetomcat-publishing-lockup-could-not-delete-file-may-be-locked-by-another-process/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 21:47:28 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=74</guid>
		<description><![CDATA[I was getting the annoying error in Eclipse with Tomcat where it didn&#8217;t think it could publish an application since some files were locked, when they were locked by the javaw.exe process that eclipse.exe started. The fix for me was to not have &#8220;Use Tomcat installation&#8221; selected in my server configuration. When I switched back [...]]]></description>
			<content:encoded><![CDATA[<p>I was getting the annoying error in Eclipse with Tomcat where it didn&#8217;t think it could publish an application since some files were locked, when they were locked by the javaw.exe process that eclipse.exe started.  The fix for me was to not have &#8220;Use Tomcat installation&#8221; selected in my server configuration.  When I switched back to the default of &#8220;Use workspace metadata&#8221;, the error stopped happening.</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2009/12/eclipsetomcat-publishing-lockup-could-not-delete-file-may-be-locked-by-another-process/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java Web Service Annotations in Tomcat</title>
		<link>http://byprogrammerforprogrammer.com/2009/11/java-web-service-annotations-in-tomcat/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-web-service-annotations-in-tomcat</link>
		<comments>http://byprogrammerforprogrammer.com/2009/11/java-web-service-annotations-in-tomcat/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 19:56:06 +0000</pubDate>
		<dc:creator>Sean Adkinson</dc:creator>
				<category><![CDATA[Example Code]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[web services]]></category>

		<guid isPermaLink="false">http://byprogrammerforprogrammer.com/?p=43</guid>
		<description><![CDATA[Easy-to-follow instructions on how to go from java files with web service annotations (@WebService, @WebMethod, @WebParam, etc) to automatic generation of a WSDL in Tomcat.]]></description>
			<content:encoded><![CDATA[<p>So recently I had to build a web service, and had a really hard time finding documentation or instructions on how to make web services work in Tomcat using the web service annotations from <a href="http://jcp.org/en/jsr/summary?id=181" target="_blank">JSR 181</a> (@WebService, @WebMethod, @WebParam, etc).  So I created this post as a way to help someone else in the same situation.  I&#8217;m sure there are many ways to do this, but this is one way.</p>
<p>My goal was to create java files annotated with web service annotations and deploy the application to Tomcat, and just have everything magically work.  I didn&#8217;t want to use the wsgen tool.  I wanted it to work like it does in JBoss, Weblogic, and Glassfish, where you just deploy the application and the web service endpoints are created automatically.</p>
<h2>Environment</h2>
<p>Here is the environment that I was working with:</p>
<ul>
<li>Java 1.6.0_16</li>
<li>Tomcat 6.0.18</li>
<li>Eclipse 3.4</li>
<li>Building a WAR and dropping into webapps folder in Tomcat</li>
</ul>
<h2>Example Class</h2>
<p>MyWebService.java:</p>
<pre>
package com.example.webservice;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

/**
 * An example web service implementation
 * @author Sean Adkinson
 */
@WebService(targetNamespace = "http://com.example.webservice", name = "mywebservice")
public class MyWebService
{

    /**
     * Says hello to the given name
     * @param name A name
     * @return Hello, name
     */
    @WebMethod(operationName = "hello")
    @WebResult(name = "return")
    public String hello(@WebParam(name = "name") String name)
    {
        return "Hello, " + name;
    }

}
</pre>
<h2>Instructions</h2>
<p>Follow these instructions to create a web service from our example class above:</p>
<ol>
<li>Download Metro 1.5 binary (or latest point release) at https://metro.dev.java.net/1.5/</li>
<li>Run <code>java -jar metro-1_5.jar</code> to unpack the contents of the jar</li>
<li>Take all the lib/webservices-*.jar files from the expanded Metro installation, and copy them into your web application&#8217;s WEB-INF/lib folder.  Note that I chose to put these in my application&#8217;s library, but you can also put them in the server&#8217;s library at tomcat.home/lib.</li>
<li>Create a <strong>sun-jaxws.xml</strong> file right next to web.xml under WEB-INF.  This is where you specify where to find the classes that have your web service annotations.  Here is a sample file:<br />
<br />
sun-jaxws.xml:</p>
<pre>
&lt;endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'&gt;
    &lt;endpoint
        name='mywebservice'
        implementation='com.example.webservice.MyWebService'
        url-pattern='/mywebservice' /&gt;
&lt;/endpoints&gt;
</pre>
<p>Here, <strong>name</strong> can be anything, <strong>implementation</strong> is the classpath reference to the class with the web service annotations that should have a web service created from it, and <strong>url-pattern</strong> is the path after your web application&#8217;s URL that will hit this web service (so if your application is at http://localhost:8080/MyApplication, this web service will be available at http://localhost:8080/MyApplication/mywebservice).
</li>
<li>Edit your <strong>web.xml</strong> to map the URL pattern above to class <strong>com.sun.xml.ws.transport.http.servlet.WSServlet</strong>, and add a listener for class <strong>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</strong>.  Here is an example:
<pre>
&lt;listener&gt;
    &lt;listener-class&gt;com.sun.xml.ws.transport.http.servlet.WSServletContextListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;servlet&gt;
    &lt;servlet-name&gt;myws&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.sun.xml.ws.transport.http.servlet.WSServlet&lt;/servlet-class&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;myws&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/mywebservice&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
</li>
<li>Now deploy your webapp, start Tomcat, and go to http://localhost:8080/MyApplication/mywebservice, and you should see details about the endpoint that was created, with a link to the generated WSDL file.</li>
<li>From here you should be able point whatever client code generating utilities you have at the WSDL and talk with the web service from a client.  I use built-in Eclipse Axis2 code generation for this, but check out wsimport in the Metro /bin folder for another option.</li>
</ol>
<p>That&#8217;s it!  Hope this helps someone who had as hard a time as I did with getting this working in Tomcat.</p>
]]></content:encoded>
			<wfw:commentRss>http://byprogrammerforprogrammer.com/2009/11/java-web-service-annotations-in-tomcat/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

