<?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 Thinking &#187; Java</title>
	<atom:link href="http://www.javathinking.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javathinking.com</link>
	<description>Java and software development related thoughts</description>
	<lastBuildDate>Thu, 02 Feb 2012 12:16:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Could not complete schema update</title>
		<link>http://www.javathinking.com/2011/11/could-not-complete-schema-update/</link>
		<comments>http://www.javathinking.com/2011/11/could-not-complete-schema-update/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 02:34:42 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[view]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=598</guid>
		<description><![CDATA[I recently mapped a JPA entity to a view, and encountered this error while using hibernate to update the database schema:
ORA-01702: a view is not appropriate here
[SchemaUpdate.execute] could not complete schema update
I was using the Oracle JDBC drivers 10.1.3.3 &#8211; luckily, the solution was to upgrade the drivers &#8211; when using 11.2.0.2.0 it works fine.
Download [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I recently mapped a JPA entity to a view, and encountered this error while using hibernate to update the database schema:</p>
<blockquote><p>ORA-01702: a view is not appropriate here</p>
<p>[SchemaUpdate.execute] could not complete schema update</p></blockquote>
<p>I was using the Oracle JDBC drivers 10.1.3.3 &#8211; luckily, the solution was to upgrade the drivers &#8211; when using 11.2.0.2.0 it works fine.</p>
<div id="_mcePaste">Download ojdbc6.jar from here:</div>
<blockquote>
<div><a href="http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html " target="_blank"> http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html </a></div>
</blockquote>
<blockquote>
<div id="_mcePaste">ojdbc6.jar (2,152,051 bytes) &#8211; Classes for use with JDK 1.6. It contains the JDBC driver classes except classes for NLS support in Oracle Object and Collection types.</div>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2011/11/could-not-complete-schema-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On to some exciting stuff</title>
		<link>http://www.javathinking.com/2011/10/on-to-some-exciting-stuff/</link>
		<comments>http://www.javathinking.com/2011/10/on-to-some-exciting-stuff/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 11:17:05 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[wakaleo]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=592</guid>
		<description><![CDATA[I went to a Agile Sydney meetup recently &#8211; &#8220;Automated web tests as a team communication tool&#8221; &#8211; by John Smart of Wakaleo Consulting. It was great stuff, and the presentation is now online.
There is a  nice story here in that the project feature set is documented via
easily readable and executable tests, and the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I went to a <a href="http://www.meetup.com/Agile-Sydney/events/25570671/">Agile Sydney meetup</a> recently &#8211; &#8220;Automated web tests as a team communication tool&#8221; &#8211; by John Smart of <a href="http://www.wakaleo.com/">Wakaleo Consulting</a>. It was great stuff, and the presentation is now <a href="http://www.slideshare.net/wakaleo/completing-the-circle-automated-web-tests-as-a-team-communication-tool">online</a>.</p>
<p>There is a  nice story here in that the project feature set is documented via<br />
easily readable and executable tests, and the reporting shows which features are<br />
implemented and which aren&#8217;t.</p>
<p>More information on the the Thucydides tool he references can be found at:</p>
<ul>
<li><a href="https://github.com/thucydides-webtests/thucydides/wiki">https://github.com/thucydides-webtests/thucydides/wiki</a></li>
</ul>
<p>While reading that presentation online, I found more gold here in some of his other presentations:</p>
<ul>
<li><a href="http://www.slideshare.net/wakaleo/junit-kung-fu-getting-more-out-of-your-unit-tests">JUnit Kung Fu: Getting More Out of Your Unit Tests</a></li>
<li><a href="http://www.slideshare.net/wakaleo/introduction-toddd">Introduction to Domain Driven Design</a></li>
</ul>
<p>They are a great read and are great pointers in the right direction to improve your software development.</p>
<p>(If you haven&#8217;t seen them before, check out <a href="http://www.wakaleo.com/training">Wakaleo&#8217;s training courses</a>. I haven&#8217;t been on them, but based on the course content, they look to be the most relevant courses I&#8217;ve come across)</p>
<p>The last couple of projects I&#8217;ve been on I&#8217;ve been frustrated by a few things about the code base that I couldn&#8217;t quite put my finger on, and the DDD presentation hit a nerve.</p>
<p>I searched around for more about DDD and found some more excellent resources:</p>
<ul>
<li><a href="http://www.infoq.com/minibooks/domain-driven-design-quickly">Domain driven design quickly</a></li>
<li><a href="http://dddsample.sourceforge.net/index.html">DDD sample application</a></li>
<li><a href="http://sourceforge.net/projects/timeandmoney/">Time and Money</a></li>
</ul>
<p>I still have to absorb all of this material and try it out but I can instantly recognise that it addresses some if not most of the code problems that have frustrated me.</p>
<p>So, exciting times are ahead. Its always refreshing to find new tricks and efficient ways of improving software development!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2011/10/on-to-some-exciting-stuff/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Crystal Reports Java API to generate PDF</title>
		<link>http://www.javathinking.com/2011/09/using-the-crystal-reports-java-api-to-generate-pdf/</link>
		<comments>http://www.javathinking.com/2011/09/using-the-crystal-reports-java-api-to-generate-pdf/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 03:56:01 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[businessobjects]]></category>
		<category><![CDATA[crystal]]></category>
		<category><![CDATA[report]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=582</guid>
		<description><![CDATA[I recently had to investigate how to generate a PDF from a Crystal Report created by another team. Without knowing anything about Crystal Reports, I had to google around for information and piece it all together. It turns out to be really simple once you know how.
We were using Business Objects 4.0, and probably the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I recently had to investigate how to generate a PDF from a Crystal Report created by another team. Without knowing anything about Crystal Reports, I had to google around for information and piece it all together. It turns out to be really simple once you know how.</p>
<p>We were using Business Objects 4.0, and probably the most important thing was to get the Java library &#8211; download &#8216;SAP Crystal Reports for Java runtime components &#8211; Java Reporting Component (JRC)&#8217; from<br />
<a href="http://www.businessobjects.com/campaigns/forms/downloads/crystal/eclipse/datasave.asp">http://www.businessobjects.com/campaigns/forms/downloads/crystal/eclipse/datasave.asp</a></p>
<p>There are a lot of samples on the web to look at &#8211; you might find something to help here:<br />
<a href="http://wiki.sdn.sap.com/wiki/display/BOBJ/Java+Reporting+Component++SDK+Samples">http://wiki.sdn.sap.com/wiki/display/BOBJ/Java+Reporting+Component++SDK+Samples</a></p>
<p>A good example to start with is “JRC EXPORT REPORT”:<br />
<a href="http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/40d580ce-bd66-2b10-95b0-cc4d3f2dcaef">http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/40d580ce-bd66-2b10-95b0-cc4d3f2dcaef</a></p>
<p>If you have an RPT file, the java to generate the report is relatively simple &#8211; :</p>
<pre>
ReportClientDocument reportClientDoc = new ReportClientDocument();
reportClientDoc.open("My crystal report.rpt", 0);
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getPrintOutputController().export(ReportExportFormat.PDF);
reportClientDoc.close();
</pre>
<p>The report I dealt with was developed by another team, and expected a data source called ‘TESTDB’ to be available. Without that data source present, I would get the following error:</p>
<pre>com.crystaldecisions.sdk.occa.report.lib.ReportSDKException: Error finding JNDI name (TESTDB)---- Error code:-2147467259 Error code name:failed</pre>
<p>Setting a data source up in Tomcat is trivial, just by adding a resource to context.xml:</p>
<pre>
&lt;Context&gt;
    &lt;WatchedResource&gt;WEB-INF/web.xml&lt;/WatchedResource&gt;

    &lt;Resource name="jdbc/TESTDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="user" password="passwd" driverClassName="oracle.jdbc.OracleDriver"
               url="jdbc:oracle:thin:@dbserver:1521:db1"/&gt;
&lt;/Context&gt;
</pre>
<p>Now the data source is set up, there’s another problem &#8211; the report expects a parameter and we get this error:</p>
<pre>com.crystaldecisions.sdk.occa.report.lib.ReportSDKParameterFieldException: InternalFormatterException---- Error code:-2147217394 Error code name:missingParameterValueError</pre>
<p>Adding the report parameter is simple once you know how:</p>
<pre>
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","MyParamName","MyParamValue");
</pre>
<p>There’s probably a lot of subtle information and detail missing here, but it works &#8211; I can generate the PDF via java code so its now at a stage where it can be integrated into our application.</p>
<p>So, the final spike test code looks like:</p>
<pre>
&lt;%@page contentType="text/html"%&gt;
&lt;%@page pageEncoding="UTF-8"%&gt;

&lt;%//Crystal Java Reporting Component (JRC) imports.%&gt;
&lt;%@page import="com.crystaldecisions.reports.sdk.*" %&gt;
&lt;%@page import="com.crystaldecisions.sdk.occa.report.lib.*" %&gt;
&lt;%@page import="com.crystaldecisions.sdk.occa.report.exportoptions.*" %&gt;

&lt;%//Java imports. %&gt;
&lt;%@page import="java.io.*" %&gt;

&lt;%

try {

	//Open report.
	ReportClientDocument reportClientDoc = new ReportClientDocument();
	reportClientDoc.open("MyReport.rpt", 0);
	ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
	paramController.setCurrentValue("","MyParamName","MyParamValue");
	ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getPrintOutputController().export(ReportExportFormat.PDF);
	reportClientDoc.close();

	writeToBrowser(byteArrayInputStream, response, "application/pdf");

} catch(Exception ex) {
	out.println(ex);
}
%&gt;

&lt;%!
   /*
	* Utility method that demonstrates how to write an input stream to the server's local file system.
	*/
	private void writeToBrowser(ByteArrayInputStream byteArrayInputStream, HttpServletResponse response, String mimetype) throws Exception {

		//Create a byte[] the same size as the exported ByteArrayInputStream.
		byte[] buffer = new byte[byteArrayInputStream.available()];
		int bytesRead = 0;

		//Set response headers to indicate mime type and inline file.
		response.reset();
		response.setHeader("Content-disposition", "inline;filename=report.pdf");
		response.setContentType(mimetype);

		//Stream the byte array to the client.
		while((bytesRead = byteArrayInputStream.read(buffer)) != -1) {
			response.getOutputStream().write(buffer, 0, bytesRead);
		}

		//Flush and close the output stream.
		response.getOutputStream().flush();
		response.getOutputStream().close();

	}
%&gt;
</pre>
<p>Note, implementing this in a JSP was just a simple and quick shortcut to investigate the API. </p>
<p>I put a simple CRConfig.xml in WEB-INF/classes:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;CrystalReportEngine-configuration&gt;
    &lt;reportlocation&gt;..&lt;/reportlocation&gt;
    &lt;timeout&gt;0&lt;/timeout&gt;
    &lt;ExternalFunctionLibraryClassNames&gt;
    	&lt;classname&gt;&lt;/classname&gt;
    &lt;/ExternalFunctionLibraryClassNames&gt;
&lt;/CrystalReportEngine-configuration&gt;
</pre>
<p>Note that this specified a report location of .. which meant I had to put MyReport.rpt in the WEB-INF directory of my application (i.e. [web-root]/WEB-INF/classes/.. = [web-root]/WEB-INF) &#8211; contents of the WEB-INF directory should not be available for download.</p>
<p>If the rpt file cannot be found, you’ll see an error like:</p>
<pre>com.crystaldecisions.sdk.occa.report.lib.ReportSDKException: Report file /[path-to-webapps]/webapps/cr/WEB-INF/MyReport.rpt not found---- Error code:-2147215356 Error code name:fileNotOpened</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2011/09/using-the-crystal-reports-java-api-to-generate-pdf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easy classpaths with Java 6</title>
		<link>http://www.javathinking.com/2011/09/easy-classpaths-with-java-6/</link>
		<comments>http://www.javathinking.com/2011/09/easy-classpaths-with-java-6/#comments</comments>
		<pubDate>Sun, 11 Sep 2011 12:35:56 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[classpath]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=569</guid>
		<description><![CDATA[Back in the day it used to be a bit more difficult than it is now to dynamically generate your java application classpath &#8211; you&#8217;d have to write a script to loop over all the jar files in a directory, appending them to your classpath variable &#8211; like this.
Since Java 6 though, its been a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Back in the day it used to be a bit more difficult than it is now to dynamically generate your java application classpath &#8211; you&#8217;d have to write a script to loop over all the jar files in a directory, appending them to your classpath variable &#8211; like <a href="http://stackoverflow.com/questions/524081/bat-file-to-create-java-classpath">this</a>.</p>
<p>Since Java 6 though, its been a lot easier &#8211; you can use wildcards to specify all jars in a directory. See the &#8220;Understanding class path wildcards&#8221; in the <a href="http://download.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html">Java SE 6 documentation</a>.</p>
<p>Now its as simple as:</p>
<pre>
java -cp /my/lib/dir/* MyClass
</pre>
<p>Simple! As it should be!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2011/09/easy-classpaths-with-java-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Turning off JDK logging</title>
		<link>http://www.javathinking.com/2011/09/turning-off-jdk-logging/</link>
		<comments>http://www.javathinking.com/2011/09/turning-off-jdk-logging/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 00:12:38 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[logging]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=561</guid>
		<description><![CDATA[I&#8217;ve been developing a simple little command line application and one of the libraries I&#8217;m using seems to log debug information to the console. To clean up the console output, I had to turn off the JDK by using:


        LogManager.getLogManager().reset();

This seemed to do the trick for me, but [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve been developing a simple little command line application and one of the libraries I&#8217;m using seems to log debug information to the console. To clean up the console output, I had to turn off the JDK by using:</p>
<pre name="code" class="java">

        LogManager.getLogManager().reset();
</pre>
<p>This seemed to do the trick for me, but it sounds like in some cases you may need to go a bit further and turn off logging at the global logger level:</p>
<pre name="code" class="java">

        LogManager.getLogManager().reset();
        Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
        globalLogger.setLevel(java.util.logging.Level.OFF);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2011/09/turning-off-jdk-logging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JUnit parameterized test with Spring autowiring AND transactions</title>
		<link>http://www.javathinking.com/2011/09/junit-parameterized-test-with-spring-autowiring-and-transactions/</link>
		<comments>http://www.javathinking.com/2011/09/junit-parameterized-test-with-spring-autowiring-and-transactions/#comments</comments>
		<pubDate>Thu, 08 Sep 2011 02:32:13 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[transaction]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=551</guid>
		<description><![CDATA[I&#8217;ve been writing JUnit Parameterized tests (a nice intro here &#8211; also see Theories) to do some data driven API testing. Now, when introducing Spring into the mix there are a couple of extra things to do. I came unstuck though because I was trying to do Transactional tests &#8211; since I&#8217;m now using @RunWith(Parameterized.class) and [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;ve been writing JUnit Parameterized tests (a nice intro <a href="http://ourcraft.wordpress.com/2008/08/27/writing-a-parameterized-junit-test/" target="_blank">here</a> &#8211; also see <a href="http://blog.schauderhaft.de/2010/01/31/new-feature-of-junit-theories/" target="_blank">Theories</a>) to do some data driven API testing. Now, when introducing Spring into the mix there are a couple of <a href="http://bmocanu.ro/coding/320/combining-junit-theoriesparameterized-tests-with-spring/" target="_blank">extra things to do</a>. I came unstuck though because I was trying to do Transactional tests &#8211; since I&#8217;m now using @RunWith(Parameterized.class) and setting up my Spring TestContextManager manually the @Transaction annotations caused an exception:</p>
<pre>java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given</pre>
<p>I couldn&#8217;t find any built in solution, so I&#8217;ve gone with manual transaction management in my test, using doInTransaction:</p>
<pre>
@RunWith(Parameterized.class)
@ContextConfiguration(locations = "classpath*:/testContext.xml")
public class MyTest {

    @Autowired
    PlatformTransactionManager transactionManager;

    private TestContextManager testContextManager;

    public MyTest (... parameters for test) {
        // store parameters in instance variables
    }

    @Before
    public void setUpSpringContext() throws Exception {
        testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);
    }

    @Parameterized.Parameters
    public static Collection<Object[]> generateData() throws Exception {
        ArrayList list = new ArrayList();
        // add data for each test here
        return list;
    }

    @Test
    public void validDataShouldLoadFully() throws Exception {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
            public Object doInTransaction(TransactionStatus status) {
                status.setRollbackOnly();
                try {
                    ... do cool stuff here

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return null;
            }
        });

    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2011/09/junit-parameterized-test-with-spring-autowiring-and-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing JtSysMon</title>
		<link>http://www.javathinking.com/2010/05/introducing-jtsysmon/</link>
		<comments>http://www.javathinking.com/2010/05/introducing-jtsysmon/#comments</comments>
		<pubDate>Sat, 01 May 2010 06:23:08 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[monitor]]></category>
		<category><![CDATA[sysmon]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=460</guid>
		<description><![CDATA[JtSysMon is a very simple monitoring tool which will poll resources and time the response. The response time is logged to a database, and from there, you can see which resources are either slow or failing/erroring.
]]></description>
			<content:encoded><![CDATA[<p></p><p><em>I spend a lot of time on the train travelling to work. Working from home has not really taken off in this part of the world &#8211; so, what better to do with that time than practice my craft?</em> <em>Its not comfortable, its hard to concentrate, but progress can be made. I have successfully used this tool to observe real performance problems, and confirm they&#8217;ve been resolved.</em></p>
<p>JtSysMon is a very simple monitoring tool which will poll resources and time the response. The response time is logged to a database, and from there, you can see which resources are either slow or failing/erroring.</p>
<p>I wrote this because I needed a way to make sure that various resources were available and responsive during development, so that we could respond quickly (proactively) to problems and have them fixed before developers or testers noticed or wasted time fault finding.</p>
<p>Existing solutions (Nagios, Zenoss etc) seemed too complex for such a simple requirement, with too much of a learning curve and setup required for essentially what is polling HTTP and SQL (please correct me if I am wrong).</p>
<p><strong>Install</strong></p>
<p>Download from <a href="http://www.javathinking.com/downloads/">http://www.javathinking.com/downloads/</a>. Now extract the binary archive so that you have a directory structure like:</p>
<p>- jtsysmon<br />
|- bin<br />
|- conf<br />
|- lib</p>
<p>By default, an embedded instance of the DERBY database will be used to store the configuration and poll results. If you want, you can edit conf/database.properties to point to another database. If you do, you will have to add the database driver jar file to the lib dir.</p>
<p><strong>Configure</strong></p>
<p>JtSysMon currently comes with 2 monitor types &#8211; SqlMonitor and HttpMonitor.</p>
<p>To configure a monitor, specify the class, a name, and then properties of the class as required. Reflection is used to set the properties of the class:</p>
<blockquote><p>sh run.sh add name=sql1 class=com.javathinking.jtsysmon.core.monitor.SqlMonitor driverClass=org.hibernate.dialect.DerbyDialect connectionString=jdbc:derby://localhost:1527/jtsysmon &#8220;sql=select count(*) from APP.MONITORCONFIG&#8221;</p>
<p>sh run.sh add name=http1 class=com.javathinking.jtsysmon.core.monitor.HttpMonitor url=http://localhost/ checkFor=Hello</p></blockquote>
<p>To list the monitors, use:</p>
<blockquote><p>sh run.sh -list</p>
<p>Listing monitors</p>
<p>1048576 sql1<br />
class = class com.javathinking.jtsysmon.core.monitor.SqlMonitor<br />
connectionString = jdbc:derby://localhost:1527/jtsysmon<br />
driverClass = org.hibernate.dialect.DerbyDialect<br />
sql = select count(*) from APP.MONITORCONFIG</p></blockquote>
<p>To delete a monitor, use delete, with the ID of the monitor (shown in the listing above):</p>
<blockquote><p>sh run.sh -delete 1048576</p></blockquote>
<p>To start monitoring, use:</p>
<blockquote><p>sh run.sh -start</p></blockquote>
<p>Use CTRL-C to stop.</p>
<p>To view alarms (where the time taken to perform poll exceeds a specified value) or problems (where the poll failed or errored) use:</p>
<blockquote><p>sh run.sh -alarms -threshold 5 -period 20</p>
<p>Listing events over last 20 minutes</p>
<p>ALARMS (duration &gt; 5)</p>
<p>19:08:18 paul-laptop1 sql1 28ms SUCCESS</p>
<p>PROBLEMS (non-successful events)</p>
<p>19:08:21 paul-laptop1 http1 90ms  ERROR</p></blockquote>
<p><strong>Summary</strong></p>
<p>So there you have it &#8211; a bare bones way to check connectivity, response times, and availability of resources in your environment. This is meant only as a development tool, NOT for monitoring production resources.</p>
<p><strong>Futures</strong></p>
<p>If there is any interest from the community in using this tool, you could easily imagine:</p>
<ul>
<li>multiple agents logging to a central database</li>
<li>more monitors
<ul>
<li>snmp</li>
<li>ssh</li>
<li>scripts</li>
</ul>
</li>
<li>a web client
<ul>
<li>to display alarms and graphs of response times</li>
<li>to configure the monitors</li>
</ul>
</li>
<li>notifiers to alert users of problems</li>
</ul>
<p>For the latest information, see the source code (and README.TXT) at:</p>
<ul>
<li><a href="http://javathinking.googlecode.com/svn/trunk/javathinking-sysmon/">http://javathinking.googlecode.com/svn/trunk/javathinking-sysmon/</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2010/05/introducing-jtsysmon/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A simple task queue</title>
		<link>http://www.javathinking.com/2009/11/a-simple-task-queue/</link>
		<comments>http://www.javathinking.com/2009/11/a-simple-task-queue/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 11:15:13 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[task]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=413</guid>
		<description><![CDATA[I&#8217;m working on a little sample framework &#8211; really only to keep my sanity and practice my chosen craft &#8211; that allows you to string together tasks in a pipeline for processing. To exercise that framework &#8211; to flush out the pros and cons of the implementation &#8211; I&#8217;m writing a sample application.
The basic idea [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I&#8217;m working on a little sample framework &#8211; really only to keep my sanity and practice my chosen craft &#8211; that allows you to string together tasks in a pipeline for processing. To exercise that framework &#8211; to flush out the pros and cons of the implementation &#8211; I&#8217;m writing a sample application.</p>
<p>The basic idea is that each task is interested in an event. That event could be the arrival of a file, or the completion of another task etc. To string tasks together, I&#8217;ve created a simple database queue system &#8211; as a task completes, it writes to the queue and then other tasks which are interested will see that event and then begin. Tasks complete either successfully (by returning no errors) or unsuccessfully (by returning more than one error).</p>
<p>An important concept is to be able to add (or remove) tasks from the pipeline programmatically and without changing the database schema. So, quite simply, when a task completes, that event is written to the queue &#8211; but how do we find which events another task is interested in? And how do we do this in a way that won&#8217;t take longer over time?</p>
<p>So, lets assume Job2 is interested in the successful completion of Job1. We need to find all successful Job1 events which haven&#8217;t already been processed by Job2 (successfully or otherwise):</p>
<pre name="code" class="sql">

SELECT * FROM QUEUE where job=&#039;job1&#039; and result=&#039;SUCCEEDED&#039; and task not in (SELECT task FROM QUEUE where job=&#039;job2&#039; and result is not null)
</pre>
<p>I&#8217;m no SQL ninja, so this is my first simple solution. It works, but it doesn&#8217;t scale. With a thousand rows, it completes pretty quickly, but with tens of thousands of rows it takes way too long (nearly 8 minutes with 40000 rows running on my Dell Inspiron laptop).</p>
<p>Pragmatically, we can restrict the query based on time &#8211; we don&#8217;t need to search the whole table, just the more recent events:</p>
<pre name="code" class="sql">

SELECT * FROM QUEUE where tstamp &gt;= ? and job=&#039;job1&#039; and result=&#039;SUCCEEDED&#039; and task not in (SELECT task FROM QUEUE where tstamp &gt;= ? and  job=&#039;job2&#039; and result is not null)
</pre>
<p>You could easily just look over the events in the last hour if your tasks are short running and you get less than a thousand events an hour &#8211; it&#8217;d probably perform okay. To give an indication of performance I&#8217;ve written a little <a href="http://groovy.codehaus.org/">groovy</a> script to show some basic trends &#8211; included below.<br />
<code><br />
paul@paul-laptop:~$ groovy sqltest<br />
2005 rows took: 4<br />
4005 rows took: 5<br />
6005 rows took: 3<br />
8005 rows took: 3<br />
10005 rows took: 2<br />
12005 rows took: 3<br />
14005 rows took: 3<br />
16005 rows took: 4<br />
18005 rows took: 5<br />
20005 rows took: 3<br />
</code></p>
<p>Notice though, that this is a great example of where indexes really help &#8211; without the index times get larger as the rowcount gets larger:<br />
<code><br />
paul@paul-laptop:~$ groovy sqltest<br />
2005 rows took: 13<br />
4005 rows took: 34<br />
6005 rows took: 123<br />
8005 rows took: 134<br />
10005 rows took: 229<br />
12005 rows took: 237<br />
14005 rows took: 330<br />
16005 rows took: 342<br />
18005 rows took: 428<br />
20005 rows took: 442<br />
</code></p>
<p>Its a pity I have to worry about the time restriction, but it does make the solution workable and at least in my intended application, appropriate. I was hoping to use the <a href="http://www.techonthenet.com/sql/minus.php">SQL MINUS</a> function, but it appears <a href="http://dev.mysql.com/">MYSQL</a> doesn&#8217;t support it.</p>
<p>Here&#8217;s the groovy script I used to generate the results. The difference between using the time restriction and the index is so dramatic and obvious, it is a great example.</p>
<pre name="code" class="java">

import groovy.sql.Sql
import groovy.grape.Grape

Grape.grab(group:&#039;mysql&#039;, module:&#039;mysql-connector-java&#039;, version:&#039;5.1.10&#039;, classLoader: this.class.classLoader.rootLoader)

enum STATUS { SUCCEEDED, FAILED }

def go() {
	def sql = Sql.newInstance(&quot;jdbc:mysql://localhost:3306/spike&quot;, &quot;spike&quot;,&quot;password&quot;, &quot;com.mysql.jdbc.Driver&quot;)
	try {
	   sql.execute(&quot;drop table QUEUE&quot;)
	} catch(Exception e){}

	sql.execute(&quot;CREATE TABLE QUEUE (id INTEGER  NOT NULL,job varchar (20) NOT NULL,task varchar (20) NOT NULL,result VARCHAR (20) NOT NULL, tstamp timestamp, PRIMARY KEY (id)) ENGINE = MyISAM&quot;)
	sql.execute(&quot;create index idx1 on QUEUE(tstamp, job, result)&quot;)

	(1..10).each() {
		def d = createHistory(sql,1000*it)
		findJobsToProcess(sql, d)
	}
}

def findJobsToProcess(sql, d) {
	def rowcount = 0
	sql.eachRow(&quot;select count(*) from QUEUE&quot;) { row -&gt;
		rowcount = row[0]
	}

	long start, end

	start = System.currentTimeMillis()
	// now find the &#039;job1&#039; items that haven&#039;t been processed by &#039;job2&#039;
	sql.eachRow(&quot;SELECT * FROM QUEUE where tstamp &gt;= ? and job=&#039;job1&#039; and result=? and task not in (SELECT task FROM QUEUE where tstamp &gt;= ? and  job=&#039;job2&#039; and result is not null) order by tstamp asc&quot;, [d,STATUS.SUCCEEDED.name(),d]) {
//	    println &quot;${it.id} ${it.job} ${it.task} ${it.result} ${it.tstamp}&quot;
	}
	end = System.currentTimeMillis()
	println &quot;${rowcount} rows took: ${end-start}&quot;

}

def createHistory(sql, count) {
	sql.execute(&quot;truncate table QUEUE&quot;)
	int id = 1
	int task = 1
	// create a &quot;history&quot; of previous jobs
	STATUS.each() { status -&gt;
		(1..count/2).each() {
			sql.execute(&quot;insert into QUEUE (id,job,task,result,tstamp) values (?,?,?,?,?)&quot;, [id++,&#039;job1&#039;,task.toString(),status.name(), new Date()])
			sql.execute(&quot;insert into QUEUE (id,job,task,result,tstamp) values (?,?,?,?,?)&quot;, [id++,&#039;job2&#039;,task.toString(),status.name(), new Date()])
			task++
		}
	}
	sleep(1000)
	def d = new Date()
	// insert some successful &#039;job1&#039; items which &#039;job2&#039; hasn&#039;t processed
	(1..5).each() {
		sql.execute(&quot;insert into QUEUE (id,job,task,result,tstamp) values (?,?,?,?,?)&quot;, [id++,&#039;job1&#039;,task.toString(),STATUS.SUCCEEDED.name(), new Date()])
		task++
	}
	return  d
}

go()
</pre>
<p>In running this test, I used:</p>
<ul>
<li>Dell Inspiron 1525, Intel(R) Core(TM)2 Duo Processor T5550, 1.83 GHz, 2MB Cache, 667 MHz FSB, 2GB (2 X 1024MB) 667MHz Dual Channel DDR2 SDRAM, 160GB 7200RPM Performance Hard Drive</li>
<li>Ubuntu 9.10 32 bit desktop edition</li>
<li>Groovy Version: 1.6.5</li>
<li>JVM: 1.6.0_03</li>
<li>mysql  Ver 14.14 Distrib 5.1.37, for debian-linux-gnu (i486)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2009/11/a-simple-task-queue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Amazon web services via Grails</title>
		<link>http://www.javathinking.com/2009/10/amazon-web-services-via-grails/</link>
		<comments>http://www.javathinking.com/2009/10/amazon-web-services-via-grails/#comments</comments>
		<pubDate>Sat, 10 Oct 2009 04:15:21 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=388</guid>
		<description><![CDATA[I just recently noticed that Amazon have changed the way you invoke their Product Advertising API &#8211; you now need to sign requests as described in the Example REST Requests.
I obviously haven&#8217;t been reading my emails, since the first clue came when I saw:
&#60;Error&#62;&#60;Code&#62;MissingParameter&#60;/Code&#62;&#60;Message&#62;The request must contain the parameter Signature.&#60;/Message&#62;&#60;/Error&#62;
Luckily, they have a java example [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I just recently noticed that Amazon <a href="http://developer.amazonwebservices.com/connect/ann.jspa?annID=476">have changed the way you invoke their Product Advertising API</a> &#8211; you now need to sign requests as described in the <a href="http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?rest-signature.html">Example REST Requests</a>.</p>
<p>I obviously haven&#8217;t been reading my emails, since the first clue came when I saw:</p>
<p><code>&lt;Error&gt;&lt;Code&gt;MissingParameter&lt;/Code&gt;&lt;Message&gt;The request must contain the parameter Signature.&lt;/Message&gt;&lt;/Error&gt;</code></p>
<p>Luckily, they have a <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=2478&amp;categoryID=14">java example</a> demonstrating how to make an API request.</p>
<p>If you extract the source from this sample into your &lt;GRAILS_APP&gt;/src/java directory, then you can invoke the amazon api with code like:</p>
<pre name="code" class="java">

import org.codehaus.groovy.grails.commons.ConfigurationHolder
import com.amazon.advertising.api.sample.*

class AmazonService {
  private static final String ENDPOINT = &quot;ecs.amazonaws.com&quot;;
  private static final String AWS_SECRET_KEY = &quot;put your secret key here&quot;;
  private static final String AWS_ACCESS_KEY_ID = &quot;put your access key here&quot;;

  boolean transactional = false

  /**
   * Call amazon lookup api.
   * Returns xml document.
   */
  def getData(String asin) {
    SignedRequestsHelper helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);

    String requestUrl = null;
    String title = null;

    Map params = new HashMap();
    params.put(&quot;Service&quot;, &quot;AWSECommerceService&quot;);
    params.put(&quot;Version&quot;, &quot;2009-03-31&quot;);
    params.put(&quot;Operation&quot;, &quot;ItemLookup&quot;);
    params.put(&quot;ItemId&quot;, asin);
    params.put(&quot;ResponseGroup&quot;, &quot;Small,Medium&quot;);

    requestUrl = helper.sign(params);

    def xml = new URL(requestUrl).text
    return new XmlSlurper().parseText(xml)
  }
}
</pre>
<p>You could, of-course, define your access keys in the Config.groovy class if you prefer.</p>
<p>(To find your identifiers, see http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?ViewingCredentials.html)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2009/10/amazon-web-services-via-grails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>No Scope registered for scope request</title>
		<link>http://www.javathinking.com/2009/06/no-scope-registered-for-scope-request/</link>
		<comments>http://www.javathinking.com/2009/06/no-scope-registered-for-scope-request/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 11:52:14 +0000</pubDate>
		<dc:creator>paul</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.javathinking.com/?p=300</guid>
		<description><![CDATA[Recently I was working with some code which defined beans as request scope. Junit tests failed with the following exception while trying to initialize the application context:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: &#8230;; nested exception is java.lang.IllegalStateException: No Scope registered for scope &#8216;request&#8217;

I found the solution by searching around (unfortunately I didn&#8217;t record the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Recently I was working with some code which defined beans as request scope. Junit tests failed with the following exception while trying to initialize the application context:</p>
<blockquote><p>
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: &#8230;; nested exception is java.lang.IllegalStateException: No Scope registered for scope &#8216;request&#8217;
</p></blockquote>
<p>I found the solution by searching around (unfortunately I didn&#8217;t record the sources). Basically, you can register the required scopes as shown below:</p>
<pre name="code" class="java">

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestScope;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.SessionScope;

public class SampleTest extends AbstractDependencyInjectionSpringContextTests {

    @Override
    protected void prepareTestInstance() throws Exception {
        context.getBeanFactory().registerScope(&quot;session&quot;, new SessionScope());
        context.getBeanFactory().registerScope(&quot;request&quot;, new RequestScope());
        MockHttpServletRequest request = new MockHttpServletRequest();
        attributes = new ServletRequestAttributes(request);
        RequestContextHolder.setRequestAttributes(attributes);

        super.prepareTestInstance();
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.javathinking.com/2009/06/no-scope-registered-for-scope-request/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

