<?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 Joe</title>
	<atom:link href="http://josephkampf.com/javajoe/feed/" rel="self" type="application/rss+xml" />
	<link>http://josephkampf.com/javajoe</link>
	<description>Joseph Kampf&#039;s musings on Java, Technology and Business</description>
	<lastBuildDate>Wed, 02 May 2012 13:29:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>JBoss, JaxWS and a Reverse Proxy</title>
		<link>http://josephkampf.com/javajoe/2012/05/02/jboss-jaxws-and-a-reverse-proxy/</link>
		<comments>http://josephkampf.com/javajoe/2012/05/02/jboss-jaxws-and-a-reverse-proxy/#comments</comments>
		<pubDate>Wed, 02 May 2012 13:26:52 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Java Programing]]></category>
		<category><![CDATA[address]]></category>
		<category><![CDATA[jax-ws]]></category>
		<category><![CDATA[jaxws]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[port]]></category>
		<category><![CDATA[webservice]]></category>
		<category><![CDATA[webservicehost]]></category>
		<category><![CDATA[wsdl]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=122</guid>
		<description><![CDATA[I am doing some work in my job with Jax-WS using Spring on JBoss. Our servers all all behind an F5 Reverse Proxy. I give the WSDLaddress to the consumers of my Web Service. However when they get the WSDL, the Address Location in the WSDL contains the hostname and port of the server that [...]]]></description>
			<content:encoded><![CDATA[<p>I am doing some work in my job with Jax-WS using Spring on JBoss.  </p>
<p>Our servers all all behind an F5 Reverse Proxy.  I give the WSDLaddress to the consumers of my Web Service.  However when they get the WSDL, the Address Location in the WSDL contains the hostname and port of the server that served up the WSDL, not the hostname and port that the user used to get the WSDL.</p>
<p>After exhausting all my options at looking for Init-Params for my Web Service Dispatcher servlet, I found that you can set the Web Hostname for the server in the JMX Console.  I set this value, redeployed my Web Service and it worked.  I went searching to see where this JMX property was set.  While doing a Google serach I came across this post http://www.ejbca.org/installation.html which talks about a bug in JBoss EAP 5.1.x where you have to comment out the line with the property &#8220;webServiceHost&#8221; so that the WSDL gets the correct hostname and port in the address.</p>
<p>So you can just modify the following file:<br />
<code>$JBOSS_HOME/server/<server profile>/deployers/jbossws.deployer/META-INF/jboss-beans.xml</code><br />
And comment out the line:</p>
<p><code><br />
    property name="webServiceHost">${jboss.bind.address}</property<br />
 </code>
<p>This will make sure that your WSDL will return the correct address.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2012/05/02/jboss-jaxws-and-a-reverse-proxy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XPath in Oracle SQL</title>
		<link>http://josephkampf.com/javajoe/2011/04/28/xpath-in-oracle-sql/</link>
		<comments>http://josephkampf.com/javajoe/2011/04/28/xpath-in-oracle-sql/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 20:16:54 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Oracle]]></category>
		<category><![CDATA[oracle]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=109</guid>
		<description><![CDATA[Recently I have been recording XML content into CLOBs in an Oracle Database. I do this when I get an unrecoverable error in a fire and forget asynchronous process. I want to keep track of errors for later use. I will either resend these messages, providing reporting, or whatever else might come in handy. As [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have been recording XML content into CLOBs in an Oracle Database.  I do this when I get an unrecoverable error in a fire and forget asynchronous process.  I want to keep track of errors for later use.  I will either resend these messages, providing reporting, or whatever else might come in handy.</p>
<p>As I start to work with data in the wild, I find that I need to write queries to extract data from the XML content.  I don&#8217;t want to have to write a Java program that will connect to the DB, pull down the content and then parse the XML or execute some XPath expression and give me the results.</p>
<p>I knew that Oracle supports XML content but I had to do a couple of hours of digging to figure it out.</p>
<p>The first step is converting the CLOB or VARCHAR2, to an XML type.  Oracle has a nice built in type that does this for you:<br />
<code>XMLTYPE(xml_clob)</code></p>
<p>Once the String is in an XMLTYPE you can pass that XML to a host of XML Functions.  You can read up on them at http://psoug.org/reference/xml_functions.html</p>
<p>I am using the EXTRACT function, to pull data out of my <em>xml_clob</em>.  I use a where clause so that I only get out the data that I care about.</p>
<p>This select statement get the <em>ID</em> of the row, and then looks into the<em>xml_clob</em> column and pulls out the <em>AccountNumber</em> text from the XML.</p>
<p><code>select id, EXTRACT(XMLTYPE(xml_clob),'//*[local-name()="AccountNumber"]/text()') as AccountNumber from TABLE</code></p>
<p>On a side note, take a look at my XPath expression.  I am looking for all occurrences of the tag <em>AccountNumber</em>.  By using the <em>local-name()</em> in a query, I don&#8217;t need to worry about any XML Namespace issues.  I use the <em>//*</em> so I don&#8217;t need to worry about the XML hierarchy.</p>
<p>Also it is important to note the types of quotes that I use.  Since Oracle uses the single quote for the text of the XPath expression, I need to use the double quotes inside of the XPath expression.  Typically in Java I use the single quotes because it is easier than using the double quotes in Java code.  Also, I was unable to escape the single quote in the XPath expression.  Once I switched to single quotes it worked fine.</p>
<p>You can also use the XPath expression in the WHERE clause of your Select.</p>
<p>Here I get the <em>ID</em> of all rows where the XML contains the account number <em>&#8217;123456&#8242;</em>.</p>
<p><code>SELECT id FROM TABLE where EXTRACT(XMLTYPE(xml_clob),'//*[local-name()="AccountNumber"]/text()') like '123456'</code></p>
<p>Now on large sets of data I would need to narrow the focus a little bit more.  I&#8217;m not sure of the performance of this type of function.  I have to imagine that it is probably not the fastest query when you consider it has to convert the CLOB into an XMLTYPE and then run an XPath expression and then compare the results of the XPath expression with the given value.   So additional WHERE clauses, preferably ones that are indexed would be a better way to execute this type of query.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2011/04/28/xpath-in-oracle-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling Java in PL/SQL</title>
		<link>http://josephkampf.com/javajoe/2011/03/06/calling-java-in-plsql/</link>
		<comments>http://josephkampf.com/javajoe/2011/03/06/calling-java-in-plsql/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 00:07:11 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Java Programing]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jpub]]></category>
		<category><![CDATA[jpublisher]]></category>
		<category><![CDATA[loadjava]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[oracle]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/2011/03/06/calling-java-in-plsql/</guid>
		<description><![CDATA[I recently had a situation where I needed to execute the same exact business logic in PL/SQL as in a Java based service. The business logic had already been implemented in Java. The logic took a person’s full name and parsed it out into it’s components, first name, middle name, last name, salutation (Mr., Mrs., [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had a situation where I needed to execute the same exact business logic in PL/SQL as in a Java based service.  The business logic had already been implemented in Java.  The logic took a person’s full name and parsed it out into it’s components, first name, middle name, last name, salutation (Mr., Mrs., Ms., Dr., etc.) and suffix, (Sr., Jr., III, IV, Esq., etc.).</p>
<p>I knew that I could implement a PL/SQL function that was written in Java and import it into the database.  However an example was hard to find.  I found examples where the function returned a primitive or a String, but nothing that returned a more complex data structure.</p>
<p>I’ve done similar things with Java calling a Stored Procedure that accepted a PL/SQL structure or table.  To do this you define a PL/SQL type and then run JPublisher to create classes that represented the type in Java.  The type could then be used to bind to JDBC SQL statements that passed Objects.  I thought that perhaps the reverse would work as well.</p>
<p>The basic steps are as follows:</p>
<ol>
<li>Identify the existing Java code that will be needed.</li>
<li>Create the PL/SQL Interface.</li>
<li>Create Java code that implements the PL/SQL Interface.</li>
<li>Define the PL/SQL.</li>
<li>Load Java code into the Database.</li>
</ol>
<p><strong>Existing Java Code</strong></p>
<p>So let’s start with the Java code that implemented the business logic.  I’m not going to reproduce the name parsing code here.  I’ll simply define the interface.</p>
<pre><code>package com.company.nameparse;
public class NameParser {

	public static NameComponentsDTO parse(String rawName) { … }

}</code></pre>
<p>The DTO Object</p>
<pre><code>package com.company.nameparse;
public class NameComponentsDTO implements Serializable {
	private String salutation;
	private String firstName;
	private String middleInitialOrName;
	private String lastName;
	private String suffix;
	private String originalNameString;

// Getters and Setters for each of the private members.
// …
}</code></pre>
<p>You need to be careful as to what version of the JRE is running in your version of Oracle.  The target Oracle version I was working with is 10g (10.0.2).  This version used the 1.4.2 JRE.  So the Name Parsing class had to be stripped down of things like Annotations, Prototypes on collections and even some newer methods on java.lang.String.  I believe that 11g uses the JRE 1.5.  So any 1.6 features will not be available.</p>
<p>Well maybe you can upgrade the JRE?  Well I asked that question of Tom Kyte on AskTom.Oracle.com.  His <a href="http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:3130959400346743583">reply</a> was that you couldn’t change the JRE.  That Oracle uses it internally and it needs to have known behavior.</p>
<p><strong>PL/SQL Interface</strong></p>
<p>Now lets define what we want the PL/SQL Function to look like.  I like to define things in Packages.  So here is the package definition:</p>
<pre><code>CREATE OR REPLACE PACKAGE NAMEPARSEPACKAGE AS
	function nameparse( fullname VARCHAR2 ) return NAME_COMPONENT_STRUCT;
END NAMEPARSEPACKAGE;
/</code></pre>
<p>Notice the function returns a PL/SQL Structure.  Here the definition of the Structure.</p>
<pre><code>CREATE OR REPLACE TYPE NAME_COMPONENT_STRUCT AS object (
   firstName varchar2(40),
   lastname varchar2(40),
   middle varchar2(40),
   salutation varchar2(40),
   suffix varchar2(40),
   originalName varchar2(80)
);
/</code></pre>
<p><strong>Java Implementation</strong></p>
<p>Now for creating the Java code that implements this PL/SQL interface.  We need to create a Java class that implements the Structure that is returned by the function nameparse.  The easiest way to do this is to use the JPublish command line utility to create a Java class from the Struct.  The JPublish command line is included with the Oracle Companion CD.</p>
<p>First you need to make sure you define your JAVA_HOME. This JAVA_HOME must point to a JDK, not a JRE.</p>
<p>Then you need to make sure you have your CLASSPATH set properly for the JPublish command line.</p>
<pre><code>set CLASSPATH=%ORACLE_HOME%\sqlj\lib\translator.jar;%ORACLE_HOME%\sqlj\lib\runtime12.jar;%ORACLE_HOME%\jdbc\lib\ojdbc14.jar;%ORACLE_HOME%\sqlj\lib\dbwsa.jar;</code></pre>
<p>Then you can run JPublish.  You need to pass the user/id and TNSName as well as the SQL type you want to create.  You can optionally provide a Java package.</p>
<pre><code>jpub -user=scott/tiger@DEV -numbertypes=oracle -builtintypes=oracle -sql=NAME_COMPONENT_STRUCT -package=com.company.nameparser.oracle</code></pre>
<p>Your going to get 2 classes NAME_COMPONENT_STRUCT and NAME_COMPONENT_STRUCTRef.  In these classes, there are constants that define the schema name and Oracle type name.</p>
<pre><code>
public static final String _SQL_NAME = "SCOTT.NAME_COMPONENT_STRUCT";
public static final String _SQL_BASETYPE = "SCOTT.NAME_COMPONENT_STRUCT";</code></pre>
<p>You might want to hand modify these constants remove the schema name so this Java this code can call on schemas other than the schema you ran Jpublisher with.</p>
<p>The code to wrap the original Java code and return the Struct is very simple.  The method that implements the function must be public and static.</p>
<pre><code>
package com.company.nameparser.oracle;

import java.sql.SQLException;

import oracle.sql.CHAR;

import com. company.nameparse.NameComponentsDTO;
import com. company.nameparse.NameParser;

public class NameParserOracleWrapper {
	public static NAME_COMPONENT_STRUCT parse(String rawName) {
		NAME_COMPONENT_STRUCT struct = new NAME_COMPONENT_STRUCT();

		NameComponentsDTO dto = NameParser.parse(rawName);

		try {
			struct.setFirstname(new CHAR(dto.getFirstName(),
					CHAR.DEFAULT_CHARSET));
			struct.setLastname(new CHAR(dto.getLastName(), CHAR.DEFAULT_CHARSET));
			struct.setMiddle(new CHAR(dto.getMiddleInitialOrName(),
					CHAR.DEFAULT_CHARSET));
			struct.setSalutation(new CHAR(dto.getSalutation(),
					CHAR.DEFAULT_CHARSET));
			struct.setSuffix(new CHAR(dto.getSuffix(), CHAR.DEFAULT_CHARSET));
			struct.setOriginalname(new CHAR(dto.getOriginalNameString(),
					CHAR.DEFAULT_CHARSET));
		} catch (SQLException e) {
		}
		return struct;
	}
}</pre>
<p></code><strong><br />
PL/SQL Implementation</strong></p>
<p>Now to implement the PL/SQL Function.<br />
<code>
<pre>
CREATE OR REPLACE PACKAGE BODY NAMEPARSEPACKAGE IS
  function nameparse(fullname VARCHAR2)
  return NAME_COMPONENT_STRUCT as
  language java
    name 'com.company.nameparser.oracle.NameParserOracleWrapper.parse(java.lang.String) return com.company.nameparser.oracle.NAME_COMPONENT_STRUCT';
END NAMEPARSEPACKAGE;
/
</pre>
<p></code><strong><br />
Load the Java Code</strong></pre>
<p>The last thing to be done is to load the Java code into Oracle.  You need to make sure you have all of the classes necessary loaded.  There is a Maven plugin comes in handy in situations like this.  It is called the Shade plugin.  It pulls in all the classes from all of the dependencies for a Maven project.  Below is the pom.xml file that implements this.  Notice that Oracle is a provided dependency.  The Shade plugin will not include classes from this project.</p>
<pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;com.company.nameparse&lt;/groupId&gt;
	&lt;artifactId&gt;nameparse-oracle&lt;/artifactId&gt;
	&lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt;
	&lt;packaging&gt;jar&lt;/packaging&gt;
	&lt;name&gt;nameparse-oracle&lt;/name&gt;
	&lt;properties&gt;
		&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
		&lt;java.version&gt;1.4&lt;/java.version&gt;
	&lt;/properties&gt;
	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
				&lt;configuration&gt;
					&lt;source&gt;${java.version}&lt;/source&gt;
					&lt;target&gt;${java.version}&lt;/target&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
 			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;
				&lt;executions&gt;
					&lt;execution&gt;
						&lt;phase&gt;package&lt;/phase&gt;
						&lt;goals&gt;
							&lt;goal&gt;shade&lt;/goal&gt;
						&lt;/goals&gt;
					&lt;/execution&gt;
				&lt;/executions&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;
	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;ojdbc&lt;/groupId&gt;
			&lt;artifactId&gt;ojdbc&lt;/artifactId&gt;
			&lt;version&gt;14&lt;/version&gt;
			&lt;scope&gt;provided&lt;/scope&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;com.company.nameparse&lt;/groupId&gt;
			&lt;artifactId&gt;nameparse&lt;/artifactId&gt;
			&lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
&lt;/project&gt;
</code></pre>
<p>When you build this project you will get a Jar file nameparse-oracle-1.0.0-SNAPSHOT.jar</p>
<p>Now that you have the jar file you need to load it into Oracle.  Included in the Oracle client is the loadjava.  You can load the entire jar file with this tool.</p>
<pre><code>
loadjava -user=scott/tiger@DEV nameparse-oracle-1.0.0-SNAPSHOT.jar
</code></pre>
<p>You should not be able to run your PL/SQL function.</p>
<pre><code>
declare
   dto NAME_COMPONENT_STRUCT;
begin
   DBMS_OUTPUT.ENABLE;
   dto := NAMEPARSEPACKAGE.NAMEPARSE('Mr. Joseph E. Kampf Jr.');
   DBMS_OUTPUT.PUT_LINE(dto.originalName);
   DBMS_OUTPUT.PUT_LINE(dto.saluation);
   DBMS_OUTPUT.PUT_LINE(dto.firstname);
   DBMS_OUTPUT.PUT_LINE(dto.middle);
   DBMS_OUTPUT.PUT_LINE(dto.lastname);
   DBMS_OUTPUT.PUT_LINE(dto.suffix);
end;</code></pre>
<p>You should see the following DBMS_OUTPUT:</p>
<pre><code>
Mr. Joseph E. Kampf Jr.
Mr.
Joseph
E.
Kampf
Jr.
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2011/03/06/calling-java-in-plsql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mock Data Testing with Spring and HSQLDB part 2</title>
		<link>http://josephkampf.com/javajoe/2009/12/22/mock-data-testing-with-spring-and-hsqldb-part-2/</link>
		<comments>http://josephkampf.com/javajoe/2009/12/22/mock-data-testing-with-spring-and-hsqldb-part-2/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 20:39:30 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Java Programing]]></category>
		<category><![CDATA[hsqldb]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=51</guid>
		<description><![CDATA[This is my 2nd post about Mock Data Testing using Spring and HSQLDB.  If you missed my first post you can find it here. I know that this concept is not really bleeding edge. The whole purpose of these two posts are to share an approach that I have used in the past to help [...]]]></description>
			<content:encoded><![CDATA[<p>This is my 2nd post about Mock Data Testing using Spring and HSQLDB.  If you missed my first post you can find it <a href="http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/">here.</a></p>
<p>I know that this concept is not really bleeding edge.  The whole purpose of these two posts are to share an approach that I have used in the past to help me with my Test Driven Continuous development.  I have not tried it with Hibernate or any other ORM.  I have only used it with Spring JDBC Template and straight JDBC programing.</p>
<p>Architecture<br />
First let me explain the requirements for your architecture to be able to support this type of mock tests.  A good architecture allows components to be unit tested.  If you need an entire environment stack to be able to unit test your code then your architecture is just a big mess.  Business logic layer needs to be separate from your data access.  Your interface layer needs to be seperate from your business logic layer.   This is true if you are doing a MVC web application or even a back end SOA implementation.  I&#8217;m not just talking about encapsulating these different layers in different classes, but also have these layers be loosely coupled.</p>
<ol>
<li>Your Database queries should be externalized.  Do not hard code database queries or stored procedure calls.  I know that Hibernate allows you to annotate your code.  But can be a barrier to having your database access be portable.    However, you can get around this.  Configuration of your Database access should be loaded at run time.  Spring Beans do a nice job of handling this.  The Bean XML file gives you a great way to capture configuration information and load it at run time.  The Application Configuration allows you to load these files external to your actual business logic.</li>
<li>Your modules should be able to be run independent of any other infrastructure.  Make your modules Pojos.  Even if you plan to expose them as EJBs, MDBs or Web Services.  You can code your business logic as a Pojo.  This will allow simple clean unit tests that can run right out of the command line with no other application running.</li>
</ol>
<p>Unit Test Implementation<br />
So lets start with the Java code.. Below is an example of a simple Pojo that does some sort of business logic. (I left out the get/setters and import statements.)</p>
<pre>public class BusinessPojo {

    private String sql;

    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    public String doSomething(String id) {
	SqlRowSet rowset = getJdbcTemplate().queryForRowSet(getSql(), new Object[] { id });

	return rowset.getString("Field1");
    }
}</pre>
<p>This example defines 2 bean properties.  The first is the SQL string that is executed, the second is the JDBC Datasource that the SQL is being executed against.  The Pojo also uses the JDBC Template from the Spring framework.  This is only to hide a lot of the messy JDBC code.</p>
<p>This is a very simple example.  But it can easily be extended to take any number of input parameters and any number of returned values.<br />
Also, this approach can be used with any framework that you can pass a JDBC Datasource and a SQL statement to.</p>
<p>Now let&#8217;s look at our test class:</p>
<pre>package com.josephkampf.example;

import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Unit test for the BusinessPojo.
 *

 *
 * @author Joseph Kampf (me@josephkampf.com)
 */
public class BusinessPojoTest {

    private ApplicationContext ctx;

    @BeforeClass
    public void setup() throws Exception {
	setUpHSQLDB("BusinessPojoTest", "/TestBusinessPojoSchemaSetup.sql");
	setUpHSQLDB("BusinessPojoTest", "/TestBusinessPojoDataSetup.sql");
	this.ctx = new ClassPathXmlApplicationContext(
		"spring-TestBusinessPojo.xml");
    }

    /**
     * Sets up the in-memory HSQLDB using the database name and initial SQL
     * script to populate the database.
     */
    public void setUpHSQLDB(String databaseName, String initSqlScript)
	    throws Exception {

	Class.forName("org.hsqldb.jdbcDriver");

	final URL url = this.getClass().getResource(initSqlScript);
	final String sql = IOUtils.toString((InputStream) url.getContent());

	final Connection connection = DriverManager.getConnection(
		"jdbc:hsqldb:mem:" + databaseName, "sa", "");
	final Statement s = connection.createStatement();
	s.execute(sql);

	s.close();
	connection.close();

    }

    @Test
    public void testProcess() throws Exception {
	BusinessPojo pojo = (BusinessPojo) this.ctx.getBean("pojo");
	Assert.assertEquals(pojo.doSomething("ID1"), "Expected");
    }
}</pre>
<p>I use TestNG.  I Like TestNG because it is annotation driven. Let&#8217;s take a look at what is going on in this test outside of actually testing the Pojo.</p>
<p>Take a look at the setUpHSQLDB method.  This method takes a name and looks up via a JDBC URL an in memory HSQLDB instance.  If the instance does not exist, it is created.  So we can always reference this instance again by using the same JDBC URL.  We will see this later when we create our BusinessPojo Test Spring context file.  The method also executes some SQL scripts in the in Memory Database.  The first sets up the table structures.  The second addes the data.  I&#8217;m not going to go into the details of what is in these scripts.  I&#8217;ll leave some examples as an attachment to this posting.  I refer you to the HSQLDB online documentation for details.  But what is happening here is the database is being set up in a known state in the same JVM that our unit test is running in.  No extra processes are required.</p>
<p>Note that we could take the setUpHSQLDB method and create a Test Fixture.  This is actually how I have implemented it in my code.  However I leave it all in one class for convenience.  Another option would be to add the setUpHSQLDB method in your base class. (Not the way I would go.)</p>
<p>Now lets connect our Pojo to the HSQLDB instance we have created in our Unit Test.  Below is the Spring Configuration that is loaded by the Unit Test.</p>
<pre>spring config:
&lt;beans&gt;
 &lt;bean id="pojo" class="com.josephkampf.example.BusinessPojo"&gt;
   &lt;property name="dataSource"&gt;
     &lt;ref bean="dbcpDataSource" /&gt;
   &lt;/property&gt;
   &lt;property name="sql"&gt;
     &lt;value&gt;SELECT f1 as Field1 from sample_table where id = ?&lt;/value&gt;
   &lt;/property&gt;
 &lt;/bean&gt;

 &lt;bean id="dbcpDataSource" destroy-method="close"&gt;
   &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver" /&gt;
   &lt;property name="url" value="jdbc:hsqldb:mem:BusinessPojoTest" /&gt;
   &lt;property name="username" value="sa" /&gt;
   &lt;property name="password" value="" /&gt;
 &lt;/bean&gt;
&lt;/beans&gt;</pre>
<p>Notice the url of the DataSource.  It has the form of jdbc:hsqldb:mem:<strong>BusinessPojoTest</strong>.  Notice that this is the same JDBC URL we used in our Unit Test to load up the database.  So when the Spring template obtains a connection, it will be obtaining a connection to the in memory HSQLDB instance.</p>
<p>Non-Unit Test Implementation<br />
Now when you actually go to a non-unit test environment, you will need a diffrent Spring Application Context file.  Below is an example of an Application Context that defines this Pojo to connect to an Oracle Database.  This is an example of what you might use in an environment that is beyond Unit test.(Integration, QA, Stage, Production, etc.)</p>
<pre>&lt;beans&gt;
  &lt;bean id="processor" class="com.josephkampf.example.BusinessPojo"&gt;
    &lt;property name="dataSource"&gt;
      &lt;ref bean="oracleDataSource" /&gt;
    &lt;/property&gt;
    &lt;property name="sql"&gt;
      &lt;value&gt;SELECT oracleField1 as Field1 from oracle_sample_table where id = ?&lt;/value&gt;
    &lt;/property&gt;
  &lt;/bean&gt;

  &lt;bean id="oracleDataSource"&gt;
    &lt;!-- Insert Oracle datasource configuration here. --&gt;
  &lt;/bean&gt;
&lt;/beans&gt;</pre>
<p>Notice that the SQL has changed to conform to the Oracle database.  All that matters is that both SQL values have the same structure for the <em>Select</em> clause have the same fields by name and the <em>Where</em> clause have the same number and order of the bind variables.</p>
<p>Mock Data Testing is an important step to delivering on a Test driven and continuous development effort.  You really should not need a running external database to be able to run your Unit Tests.  Your Unit Tests should be using a known set of data so that you can do meaningful Assertions in your Unit Test code.  You also need to be able to spend less time coding that Mock Data.  Using SQL to define this test data is a more intuitive and faster mechanism than other solutions.  Spring allows you to separate your concerns so that you can create testable units.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2009/12/22/mock-data-testing-with-spring-and-hsqldb-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mock Data Testing with Spring and HSQLDB part 1</title>
		<link>http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/</link>
		<comments>http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 21:14:33 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Java Programing]]></category>
		<category><![CDATA[hsqldb]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=50</guid>
		<description><![CDATA[I wanted to share some interesting things that myself and my colleague Emil &#8220;Bud&#8221; Lefkof have done recently in the realm of Mock Testing using Spring and HSQLDB. I expect this to be the first of threetwo posts on this topic. First I&#8217;ll explain the problem that this approach solves. In the second post I&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to share some interesting things that myself and my colleague Emil &#8220;Bud&#8221; Lefkof have done recently in the realm of Mock Testing using Spring and HSQLDB.</p>
<p>I expect this to be the first of <del datetime="2009-12-22T20:37:53+00:00">three</del>two posts on this topic.  First I&#8217;ll explain the problem that this approach solves.  In the second post I&#8217;ll explain the approach.  In the last post I&#8217;ll discuss some additional concerns such as having to deal with Stored Procedures.</p>
<p>For an explanation of Mock Object Testing see <a title="Mock Object at Wikipedia" href="http://en.wikipedia.org/wiki/Mock_object" target="_blank">Wikipedia</a> who actually does a nice job of explaining what it is all about.  </p>
<p>The reason that Mock Testing is important is that Unit tests should be repeatable and automated.  Developers should be able to check out code and unit tests from a source control system and be able to run a script or command that builds and tests.  Unit tests shouldn&#8217;t need to rely on databases, or other external dependencies.  Plus the state of a database can become unknown.  When doing test driven development you need to be able to run a test over and over again.  You can&#8217;t worry about the data already being in the database.</p>
<p>I was first introduced to the concept of Mock Testing by my old friend and colleague Howard Spector during my time at FirstUSA/Bank One Card Services.  It was my first experience with Test Driven Development.  Back in those days we had our own Data Services Framework.  This was a framework that provided an interface that was an abstraction over Relational Database.</p>
<p>Because this framework was an interface we could use test implementations that would return mock data objects.  However it always felt clumsy.  Creating the test data was a manual time consuming task.  There were 2 ways to create the Mock Data objects.  </p>
<p>The first way is to hand code a factory that would set the values of the properties of data objects.</p>
<pre>
public List getDataPojos(String arg){
  List returnList = new LinkedList();

  DataPojo dataPojo1 = new DataPojo();
  dataPojo1.setString1("String 11");
  dataPojo1.setString2("String 12");
  returnList.add(dataPojo1);

  DataPojo dataPojo2 = new DataPojo();
  dataPojo2.setString1("String 21");
  dataPojo2.setString2("String 22");
  returnList.add(dataPojo2);

  return returnList;
}
</pre>
<p>Another option that has a little bit more flexibility is to parse a properties file or XML file.  </p>
<p>With either approach there needs to be some sort of translation from the source to the Mock Data object that is essentially throw away code.  This will cause the developer to spend more time writing code to create Mock Data objects than writing the actual tests or even the actual code.  </p>
<p>In my next <a href="http://josephkampf.com/javajoe/2009/12/22/mock-data-test…-hsqldb-part-2/">post</a> I&#8217;ll detail how we can solve the issue of spending too much time creating Mock Data objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2009/11/24/mock-data-testing-with-spring-and-hsqldb-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When do you leave a job?</title>
		<link>http://josephkampf.com/javajoe/2009/11/24/when-do-you-leave-a-job/</link>
		<comments>http://josephkampf.com/javajoe/2009/11/24/when-do-you-leave-a-job/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 18:46:27 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[employment]]></category>
		<category><![CDATA[consulting career employment]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=49</guid>
		<description><![CDATA[Long gone are the days that you work your entire career with one employer.  Long gone are the days that you would even spend more than a decade with the same employer.  I was told in college that as you are starting out in your career you should move around on average every 18 months.  [...]]]></description>
			<content:encoded><![CDATA[<p>Long gone are the days that you work your entire career with one employer.  Long gone are the days that you would even spend more than a decade with the same employer.  I was told in college that as you are starting out in your career you should move around on average every 18 months.  This was especially true during the tech bomb of the late 90&#8242;s.  For a while I did that.  By the time I was 6 years out of College, I was on my 4th company.</p>
<p>Has that changed at all?  Right now we here in the United States are facing unemployment like we have not seen since the great depression.  I feel lucky that I currently have skills that are in demand.  A lot of people I know are not that lucky.  But I wonder for even the software developers out there has this economy made you think twice about pursuing new opportunities.</p>
<p>I had a hard time making this decision about a year ago.  The market had already started it&#8217;s down turn.  I wasn&#8217;t getting assignments that were a fit for my skills and location.  I spent a great deal of time in 2008 sitting on the bench.  Granted I got paid.  But I was a draw on the company&#8217;s bottom line.  For me there was nothing worse than having to report to the office every day (even if it was an abbreviated day.) and not have work that someone counted on me producing.  I was given some bench assignments.  But there was little collaboration.  I&#8217;m one to thrive on the back and forth of the work day.</p>
<p>I loved my time with that old consulting company.  I had great friends there.  I had gone through some tough times while I was there in my personal life.  They were always great to me.  I felt like I was well respected.  But it was time to leave.  I have yet to regret a decision I have made in my career.  I don&#8217;t regret leaving.  Although I would not be opposed to working with them again in the future.</p>
<p>So what are the types of things that you look for when you decide to move on?</p>
<ul>
<li>Better Pay</li>
<li>More exciting work</li>
<li>Change in management</li>
<li>Change in direction of your company</li>
<li>More responsibility</li>
<li>Less responsibility</li>
<li>Work environment</li>
</ul>
<p>For me it was &#8220;More exciting work&#8221; and &#8220;different work environment.&#8221;</p>
<p>Right now I am working as a Contractor.  I see myself having to make these decisions a lot more in the future.  I also see these decisions being made for me as well.  My original contract was set to expire at the end of the year.  I&#8217;ve since been extended until April 30th.  I am grateful that I will have a contract through the lean months of November, December, January and start of February.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2009/11/24/when-do-you-leave-a-job/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hello World&#8230;again</title>
		<link>http://josephkampf.com/javajoe/2008/12/17/hello-worldagain/</link>
		<comments>http://josephkampf.com/javajoe/2008/12/17/hello-worldagain/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 23:38:38 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[Administrative]]></category>
		<category><![CDATA[helloworld]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/?p=44</guid>
		<description><![CDATA[Welcome to the Java Joe Blog hosted on the new JosephKampf.com. I&#8217;ve imported my posting from Joe&#8217;s JavaOne blog that was hosted on Blogger (or BlogSpot as it use to be called.) This Blog is going to be the place where I am going to be posting my thoughts on Java, Technology and Business in [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the Java Joe Blog hosted on the new JosephKampf.com.</p>
<p>I&#8217;ve imported my posting from Joe&#8217;s JavaOne blog that was hosted on Blogger (or BlogSpot as it use to be called.)</p>
<p>This Blog is going to be the place where I am going to be posting my thoughts on Java, Technology and Business in general.</p>
<p>I hope you enjoy it.</p>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2008/12/17/hello-worldagain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sun General Session Extreme Innovation</title>
		<link>http://josephkampf.com/javajoe/2008/05/09/sun-general-session-extreme-innovation/</link>
		<comments>http://josephkampf.com/javajoe/2008/05/09/sun-general-session-extreme-innovation/#comments</comments>
		<pubDate>Fri, 09 May 2008 17:38:00 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[JavaOne 2008]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/2008/05/09/sun-general-session-extreme-innovation/</guid>
		<description><![CDATA[James Gosling&#8217;s general session was rather interesting. He went through a few of the new innovations that Sun and other companies have been doing with Java. First two are very useful and I can see using them right away. First they showed off a Visual VM tool. This tool pulls together all of the metrics [...]]]></description>
			<content:encoded><![CDATA[<p>James Gosling&#8217;s general session was rather interesting.  He went through a few of the new innovations that Sun and other companies have been doing with Java.</p>
<p>First two are very useful and I can see using them right away.  First they showed off a Visual VM tool.  This tool pulls together all of the metrics about a JVM into one place.  This includes Heap Analysis, and Garbage Collection.  It also has an API that allows you to write your own modules.</p>
<p>The next innovation was put on by Tor Norbye of the Java Posse.  It was the Javascript integration with NetBeans.  It had code complete, and an interactive debugging in Firefox.  I think it might be time to give NetBeans a real look.</p>
<p>There was project Darkstar which is like an application server for online games.  Seems to have some really neat stuff and allow game developers to concentrate on developing games and not the plumbing that is nessisary to run an online game.</p>
<p>Sentilla is a company that makes JavaME sensors.  I wrote earlier in the week about how they have these sensors all over the convention hall tracking the movement of people.  THey did an interesgting demo by putting these sensors into beach balls, and having the crowd hit the beach balls around.  They displayed the location of the beach ball on the screen.  They used some of these Sentilla sensors that used signal strength to calculate the position.</p>
<p>Probably the most interesting piece of JavaME was the Pulse Live Scribe smart pen.  This is a pen that can record audio while you write and then replay it, store it on the computer, etc.  The pen also allows the development of applications that can run right in the pen.  They demoed a very cool piano application.  The user of the pen, drew the keys on paper, and then was able to play notes on the piano he drew.  God I wish I had one of these while I was in college.</p>
<p>There were also a couple of other demos having to do with Real Time Java.  Some industrial applications, an entry for the DARPA XPrize (Tommy Jr. the car was called.), and an application that helped render data from Mars to help them track down water on Mars.</p>
<div class="blogger-post-footer">The views and opinions expressed here the views and opinions of Joseph Kampf.  They are not the necessarily the views and the opinions of Anexinet or any other Anexinet employee.</div>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2008/05/09/sun-general-session-extreme-innovation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Public Health Alert</title>
		<link>http://josephkampf.com/javajoe/2008/05/09/public-health-alert/</link>
		<comments>http://josephkampf.com/javajoe/2008/05/09/public-health-alert/#comments</comments>
		<pubDate>Fri, 09 May 2008 13:38:00 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[JavaOne 2008]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/2008/05/09/public-health-alert/</guid>
		<description><![CDATA[I woke up this morning with this email in my in box. Subject: URGENT! PUBLIC HEALTH ADVISORY FROM JAVAONE TEAM The JavaOne conference team has been notified by the San Francisco Department of Public Health about an identified outbreak of a virus in the San Francisco area. Testing is still underway to identify the specific [...]]]></description>
			<content:encoded><![CDATA[<p>I woke up this morning with this email in my in box.</p>
<blockquote><p>Subject:  URGENT! PUBLIC HEALTH ADVISORY FROM JAVAONE TEAM</p>
<p>The JavaOne conference team has been notified by the San Francisco Department of Public Health about an identified outbreak of a virus in the San Francisco area. Testing is still underway to identify the specific virus in question, but they believe it to be the Norovirus, a common cause of the &#8220;stomach flu&#8221;, which can cause temporary flu-like symptoms for up to 48 hours. Part of the San Francisco area impacted includes the Moscone Center, the site of the JavaOne conference which is being held this week. We are working with the appropriate San Francisco Department of Public Health and Moscone representatives to mitigate the impact this will have on the conference and steps are being taken overnight to disinfect the facility. We have not received any indication that the show should end early, so will have the full schedule of events on Friday as planned. We hope to see you then.</p>
<p>Please see the attached notification from the Department of Public Health.</p>
<p>For further information, as well as Frequently Asked Questions related to the Norovirus, please visit the San Francisco Department of Public Health website at http://sfcdcp.org/norovirus.cfm</p></blockquote>
<p>Both of my former Colleagues who are here at Java One with me both got this bug.  I&#8217;v e been ok.  The only ill effects I have felt have been self inflicted.  I did notice that the lines in the mens rooms between sessions was very long.</p>
<div class="blogger-post-footer">The views and opinions expressed here the views and opinions of Joseph Kampf.  They are not the necessarily the views and the opinions of Anexinet or any other Anexinet employee.</div>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2008/05/09/public-health-alert/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Garbage-First Garbage Collector</title>
		<link>http://josephkampf.com/javajoe/2008/05/09/the-garbage-first-garbage-collector/</link>
		<comments>http://josephkampf.com/javajoe/2008/05/09/the-garbage-first-garbage-collector/#comments</comments>
		<pubDate>Fri, 09 May 2008 13:35:00 +0000</pubDate>
		<dc:creator>Joseph Kampf</dc:creator>
				<category><![CDATA[JavaOne 2008]]></category>

		<guid isPermaLink="false">http://josephkampf.com/javajoe/2008/05/09/the-garbage-first-garbage-collector/</guid>
		<description><![CDATA[A new Garbage Collector is coming to the Sun JVM. From what I have heard it is a lot like the Garbage Collector in JRocket. The current Garbage Collector is called CMS. (I have no idea what it stands for.) The new Garbage Collector G1, is a generational Garbage Collector much like CMS. However instead [...]]]></description>
			<content:encoded><![CDATA[<p>A new Garbage Collector is coming to the Sun JVM. From what I have heard it is a lot like the Garbage Collector in JRocket.</p>
<p>The current Garbage Collector is called CMS. (I have no idea what it stands for.)  The new Garbage Collector G1, is a generational Garbage Collector much like CMS.  However instead of the physical seperations between the Young and Old generations, it allocates 1 meg blocks of memory and designates on the fly the purpose of that block (Old or young.)</p>
<p>I&#8217;m suppose to do a presentation for NUGS on tuning Garbage Collectors next week.  I&#8217;m going to try to squeeze in some info on this new Garbage Collector, and even take a look at how the JRocket Garbage Collector work.</p>
<div class="blogger-post-footer">The views and opinions expressed here the views and opinions of Joseph Kampf.  They are not the necessarily the views and the opinions of Anexinet or any other Anexinet employee.</div>
]]></content:encoded>
			<wfw:commentRss>http://josephkampf.com/javajoe/2008/05/09/the-garbage-first-garbage-collector/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

