<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java &#8211; J O H N R A . M E</title>
	<atom:link href="/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>/</link>
	<description>...yet another musings of a techie</description>
	<lastBuildDate>Thu, 11 Apr 2024 23:34:24 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.3</generator>
	<item>
		<title>Design Pattern: Chain of Responsibility</title>
		<link>/2014/05/06/design-pattern-chain-of-responsibility/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Tue, 06 May 2014 21:33:01 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Development]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=387</guid>

					<description><![CDATA[In my original Tetris code base, I started out with a simple RotationController class. As I recall, this was a trivial class with a single shape. However, as more shapes were added, it quickly became unwieldy. Looking back at this code, I want to cringe at my lack of discipline in following proper design principles. On the bright side, I have something to blog about. Chain of Responsibility The chain of responsibility design pattern is known as a behavioral pattern consisting of client objects and a series of handler objects. It provides more than one object the opportunity to handle a request by&#8230;]]></description>
										<content:encoded><![CDATA[<p>In my original <a href="https://github.com/johnra74/tetris">Tetris code base</a>, I started out with a simple <a href="https://github.com/johnra74/tetris/blob/82b3f058fbf62c036623a3b3eb16ca3bf2550f2d/tetris/tetris-core/src/main/java/com/jstrgames/tetris/core/controller/RotateController.java">RotationController class</a>. As I recall, this was a trivial class with a single shape. However, as more shapes were added, it quickly became unwieldy. Looking back at this code, I want to cringe at my lack of discipline in following proper design principles. On the bright side, I have something to blog about.</p>
<p><strong>Chain of Responsibility</strong></p>
<p><a href="/wp-content/uploads/2014/05/chain_of_resp_pattern.png"><img decoding="async" class="alignleft size-medium wp-image-399" src="/wp-content/uploads/2014/05/chain_of_resp_pattern-300x124.png" alt="chain_of_resp_pattern" width="300" height="124" /></a>The chain of responsibility design pattern is known as a behavioral pattern consisting of client objects and a series of handler objects. It provides more than one object the opportunity to handle a request by linking receivers together (see left UML diagram). Instead of having one monolithic class, as I have or coupling your code to each and every concrete class, with the chain of responsibility pattern, you can avoid both.</p>
<p><strong>Refactoring Rotation Controller</strong></p>
<p><a href="/wp-content/uploads/2014/05/action_controller_before.png"><img fetchpriority="high" decoding="async" class="alignright size-medium wp-image-394" src="/wp-content/uploads/2014/05/action_controller_before-300x240.png" alt="action_controller_before" width="300" height="240" /></a>On the right is the UML diagram for handling user inputs in my game. The ControlListener implements the Java AWT Event KeyListener. The ControlListener listens for various keyboard actions (UP_ARROW &#8211; rotate clockwise, DOWN_ARROW &#8211; drop, LEFT_ARROW &#8211; move left, RIGHT_ARROW &#8211; move right, Q &#8211; rotate counter-clockwise, and W &#8211; rotate clockwise). When user presses UP_ARROW, Q, or W, it will create an instance of RotateController class to handle the respective rotation action. On the original UML diagram, you can see the long list of private methods I&#8217;ve implemented to handle the rotation action for various tetris shapes.</p>
<p><a href="/wp-content/uploads/2014/05/action_controller_after.png"><img decoding="async" class="alignleft size-medium wp-image-404" src="/wp-content/uploads/2014/05/action_controller_after-300x242.png" alt="action_controller_after" width="300" height="242" /></a>On the left is the refactored UML diagram with the rotation logic implemented using the chain of responsibility design pattern. Gone are the many private methods created to handle every possible shapes. For each shape, we now have a respective handler class responsible for rotating the shape. The chain of these rotation handler will check if can handle the rotation request by inspecting the shape associated with the request.</p>
<p> </p>


<pre class="wp-block-code"><code>public Coordinate&#91;] executeRequest(RotateRequest request) {
  final Coordinate&#91;] coordinate;
  final IShape shape = request.getShape();
  final Rotate rotate = request.getRotate();

  if( shape.getShape() == this.getShape()) {
    coordinate = getTargetCoordinates(shape, rotate);
  } else {
    if(this.nextHandler == null) {
      throw new HandlerNotFoundException("No handler defined for " + shape.getShape());
    } else {
      coordinate = this.nextHandler.executeRequest(request);
    }
  }

  return coordinate;
}</code></pre>



<p>If it cannot handle the request, it will pass the request to the next handler. If it reaches the end of the chain and no handler is found, a runtime exception will be thrown. Feel free to browse the final code base on <a href="https://github.com/johnra74/tetris/tree/master/tetris/tetris-core/src/main/java/com/jstrgames/tetris/core/controller">GitHub</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Java-based Tetris Game</title>
		<link>/2014/04/06/java-based-tetris-game/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Sun, 06 Apr 2014 20:44:43 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=383</guid>

					<description><![CDATA[I&#8217;ve been planning to write some tutorials on design patterns. I just need to find some time and my day job at the corporate world has kept me busy. I plan to use this code base from a java tetris application I wrote a while back. I&#8217;ve done some clean ups &#8211; who&#8217;s not embarrassed by their old code. Don&#8217;t worry, I haven&#8217;t completely cleaned it up. After all, the plan is to write tutorials on design patterns that would help improve this code. My first topic, when I do get some time, will be Chain of Responsibility.]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve been planning to write some tutorials on design patterns. I just need to find some time and my day job at the corporate world has kept me busy. I plan to use <a href="https://github.com/johnra74/tetris">this code base</a> from a java tetris application I wrote a while back. I&#8217;ve done some clean ups &#8211; who&#8217;s not embarrassed by their old code. Don&#8217;t worry, I haven&#8217;t completely cleaned it up. After all, the plan is to write tutorials on design patterns that would help improve this code. My first topic, when I do get some time, will be <a href="/2014/05/06/design-pattern-chain-of-responsibility/">Chain of Responsibility</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Gradle Plug-in: WSDL to Java Code Generation</title>
		<link>/2014/03/08/gradle-plug-in-wsdl-to-java-code-generation/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Sat, 08 Mar 2014 14:39:38 +0000</pubDate>
				<category><![CDATA[Gradle]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Development]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=373</guid>

					<description><![CDATA[It didn&#8217;t take long for me to fall in love with Gradle. Once I was introduced to it, I never looked back. It was the same with Ant as I transitioned from Make. But, Gradle is different. I always felt building was necessary evil. It was often done way after first code was ever written. This isn&#8217;t true with Gradle. Before any code is written, I start every project by setting up my Gradle build. I actually look forward to adding more features to my build. How crazy is that?! WSDL to JavaRecently, I published one of my old SharePoint&#8230;]]></description>
										<content:encoded><![CDATA[<p>It didn&#8217;t take long for me to fall in love with <a href="http://www.gradle.org/">Gradle</a>. Once I was introduced to it, I never looked back. It was the same with <a href="http://ant.apache.org/">Ant</a> as I transitioned from <a href="https://www.gnu.org/software/make/">Make</a>. But, Gradle is different. I always felt building was necessary evil. It was often done way after first code was ever written. This isn&#8217;t true with Gradle. Before any code is written, I start every project by setting up my Gradle build. I actually look forward to adding more features to my build. How crazy is that?!</p>
<p><strong>WSDL to Java</strong><br />Recently, I published one of my old <a href="https://github.com/johnra74/sharepoint-api">SharePoint API</a> to GitHub. Originally, I had written the build script using Ant for this project. One of the task I had was to take the SharePoint List WSDL and generate the corresponding java soap client classes. This is fairly trivial task in Ant &#8211; in fact, axis already provides <a href="http://axis.apache.org/axis/java/ant/ant.html">an ant task</a>. Sure, I could google for Gradle plug-in for WSDL to Java but I wanted to use this opportunity to learn to write my own plug-in. I&#8217;ve also been looking to <a href="/2013/07/25/thats-groovy/">write more Groovy code</a>.</p>
<p><strong>Creating a Custom Gradle Task</strong><br /><a href="/wp-content/uploads/2014/03/gradle1.png"><img loading="lazy" decoding="async" class="alignright size-thumbnail wp-image-375" src="/wp-content/uploads/2014/03/gradle1-150x150.png" alt="gradle buildSrc" width="150" height="150" /></a>All custom Gradle tasks resides under buildSrc at the root of your project. If you are familiar with Gradle multiproject then you will notice that buildSrc is structured like a subproject. In fact, it is a subproject. Since I will be writing my custom task using Groovy, my source file will reside under src/main/groovy. If you wanted to write your custom task in Java, you would create it under src/main/java.</p>
<p>Since my custom task is merely a wrapper for Axis2 class org.apache.axis2.wsdl.WSDL2Java, the build.gradle file will contain the Axis2 dependencies. Note, if your custom task does not require any dependencies besides core java, then you do not need to define the build.gradle file. Here&#8217;s my build.gradle file:</p>


<pre class="wp-block-code"><code>repositories {
  mavenCentral()
}

dependencies {
  compile 'org.apache.axis2:axis2:1.6.2'
  compile 'org.apache.axis2:axis2-xmlbeans:1.6.2'
  compile 'org.apache.xmlbeans:xmlbeans:2.6.0'
}</code></pre>



<p>Once the build.gradle has been defined, I create my custom task in Groovy &#8211; WSDL2Java.groovy. The below Groovy class is a simple implementation. As you can see, there are no validation checks. It assumes all properties will be set.</p>



<pre class="wp-block-code"><code>import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
// since this groovy class has the same name as the axis2 class, alias axis2 class to CodeGen
import org.apache.axis2.wsdl.WSDL2Java as CodeGen

class WSDL2Java extends DefaultTask {
  // source location of the WSDL file
  String wsdlfilename
  // specify the binding type - xmlbeans, adb, or jibx
  String databindingName
  // target location where java classes should be created under
  String targetSourceFolderLocation
  // base package name
  String packageName

  @TaskAction
  def generateJava() {
    String&#91;] args =
      &#91;
        "-o", targetSourceFolderLocation,
        "-p", packageName,
        "-d", databindingName,
        "-or",
        "-uri", wsdlfilename
      ]
    CodeGen.main(args)
  }
}</code></pre>



<p>Here&#8217;s how this custom task is called within the project. First, I define a task called &#8220;genJavaFromWSDL&#8221; with type WSDL2Java &#8211; the Groovy class name. Within this custom task, I set all properties. Then, I update the dependency of java compile task to this custom task. This will ensure the java soap client is created before build is trigger.</p>



<pre class="wp-block-code"><code>// define the WSDL2Java task
task genJavaFromWSDL(type: WSDL2Java) {
  wsdlfilename= "$buildDir/../src/main/wsdl/Lists.SP2013.wsdl"
  databindingName='xmlbeans'
  targetSourceFolderLocation= "$buildDir/generated/wsdl/main"
  packageName='com.microsoft.sharepoint'
}

// add prior hook before compile
compileJava.dependsOn genJavaFromWSDL

// add generated wsdl java classes to source dir
sourceSets.main.java.srcDir "$buildDir/generated/wsdl/main/src"
sourceSets.main.java.srcDir "$buildDir/generated/wsdl/main/resources"</code></pre>



<div class="wp-block-image"><figure class="alignleft"><a href="/wp-content/uploads/2014/03/gradle2.png"><img decoding="async" src="/wp-content/uploads/2014/03/gradle2.png" alt="Gradle Project" class="wp-image-378"/></a></figure></div>



<p>Finally, I add the generated source and resources to the Groovy sourceSet so that the generated sources are properly compiled. It also allows them to appear under Eclipse.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Fluent Interface by Example</title>
		<link>/2014/03/01/fluent-interface-by-example/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Sat, 01 Mar 2014 22:30:17 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[SharePoint]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=364</guid>

					<description><![CDATA[Chances are you have seen Fluent Interface in action. I&#8217;ve seen it without realizing what they were until I stumbled across Martin Fowler&#8217;s blog. The aim is simple &#8211; to provide for a more readable code. SharePoint APISeveral years ago, I wrote a SharePoint API in Java to interact with its List Soap Service. This soap service had a feature to query the target list using Collaborative Application Markup Language (CAML). Here&#8217;s an example of CAML query to filter the task list where the TaskName is &#8220;Foo Bar&#8221; and the Status is &#8220;In Progress&#8221;. As part of this SharePoint API,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Chances are you have seen Fluent Interface in action. I&#8217;ve seen it without realizing what they were until I stumbled across <a href="http://martinfowler.com/bliki/FluentInterface.html">Martin Fowler&#8217;s blog</a>. The aim is simple &#8211; to provide for a more readable code.</p>



<p><strong>SharePoint API</strong><br>Several years ago, I wrote a SharePoint API in Java to interact with its List Soap Service. This soap service had a feature to query the target list using <a href="http://msdn.microsoft.com/en-us/library/office/ms467521(v=office.15).aspx">Collaborative Application Markup Language (CAML)</a>. Here&#8217;s an example of CAML query to filter the task list where the TaskName is &#8220;Foo Bar&#8221; and the Status is &#8220;In Progress&#8221;.</p>



<pre class="wp-block-code"><code>&lt;query&gt;
  &lt;where&gt;
    &lt;and&gt;
      &lt;eq&gt;
        &lt;fieldref name="TaskName"&gt;
        &lt;value type="Text"&gt;Foo Bar&lt;/value&gt;
      &lt;/fieldref&gt;&lt;/eq&gt;
      &lt;eq&gt;
        &lt;fieldref name="Status"&gt;
        &lt;value type="Text"&gt;In Progress&lt;/value&gt;
      &lt;/fieldref&gt;&lt;/eq&gt;
    &lt;/and&gt;
   &lt;/where&gt;
&lt;/query&gt;</code></pre>



<p>As part of this SharePoint API, I had written a corresponding set of Java classes &#8211; each node represented by a class. For trivial query like above, it would look like the following:</p>



<pre class="wp-block-code"><code>final Expression leftExpression = new Equals(new Field("TaskName", "Foo Bar"));
final Expression rightExpression = new Equals(new Field("Status", "In Progress"));
final Condition condition = new And(leftExpression, rightExpression);
final Where clause = new Where(condition);
final Query query = new Query(clause);</code></pre>



<p>As you can predict, for complicated scenarios, this would quickly become unreadable. By applying the concept of Fluent Interface, we can make it far more readable. For example, the above become the following:</p>



<pre class="wp-block-code"><code>final Where clause =
  new Where(
    and(eq("TaskName", "Foo Bar"),
        eq("Status", "In Progress")));</code></pre>



<p><strong>Applying Fluent Interface</strong><br>A good Fluent Interface takes a while to build. It should be built with the goal of readability and flow in mind. Return type should be chosen based on what you need to continue fluent action. Here&#8217;s the SharePoint API implementation. For the complete implementation, please see <a href="https://github.com/johnra74/sharepoint-api/blob/master/sharepoint/sharepoint-lib/src/main/java/com/jstrgames/sharepoint/query/Where.java">GitHub Source</a>.</p>



<pre class="wp-block-code"><code>.
.
.
public static Condition and(Expression left, Expression right) {
  return new And(left, right);
}

public static Condition and(Expression left, Condition right) {
  return new And(left, right);
}

public static Condition and(Condition left, Expression right) {
  return new And(left, right);
}

public static Condition and(Condition left, Condition right) {
  return new And(left, right);
}
.
.
.
public static Expression eq(Field field) {
  return new Equals(field);
}</code></pre>



<p>For complicated scenarios where you want to get all task assigned to John with status in &#8220;New&#8221; or &#8220;In Progress&#8221; and task created after Jan 1, 2014, the CAML would like the following.</p>



<pre class="wp-block-code"><code>&lt;query&gt;
  &lt;where&gt;
    &lt;and&gt;
      &lt;eq&gt;
        &lt;fieldref name="AssignedTo"&gt;
        &lt;value type="Text"&gt;John&lt;/value&gt;
      &lt;/fieldref&gt;&lt;/eq&gt;
      &lt;and&gt;
        &lt;or&gt;
          &lt;eq&gt;
            &lt;fieldref name="Status"&gt;
            &lt;value type="Text"&gt;New&lt;/value&gt;
          &lt;/fieldref&gt;&lt;/eq&gt;
          &lt;eq&gt;
            &lt;fieldref name="Status"&gt;
            &lt;value type="Text"&gt;In Progress&lt;/value&gt;
          &lt;/fieldref&gt;&lt;/eq&gt;
        &lt;/or&gt;
        &lt;gt&gt;
          &lt;fieldref name="CreateDate"&gt;
          &lt;value type="DateTime"&gt;2014-01-01T00:00:00Z&lt;/value&gt;
        &lt;/fieldref&gt;&lt;/gt&gt;
    &lt;/and&gt;
   &lt;/and&gt;&lt;/where&gt;
&lt;/query&gt;</code></pre>



<p>Here&#8217;s the same in Fluent Interface</p>



<pre class="wp-block-code"><code>final Where clause =
  new Where(
    and(eq("AssignedTo", "John"),
    and(
      or(eq("Status", "New"),
         eq("Status", "In Progress")),
      gt("CreateDate", "2014-01-01T00:00:00Z"))));</code></pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Application Health Monitor</title>
		<link>/2013/09/06/application-health-monitor/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Sat, 07 Sep 2013 00:57:13 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[HttpComponent]]></category>
		<category><![CDATA[Infrastructure]]></category>
		<category><![CDATA[Maintenance]]></category>
		<category><![CDATA[Productivity]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=341</guid>

					<description><![CDATA[I&#8217;ve been meaning to contribute to open source for some time. I really didn&#8217;t have anything particularly in mind to what I wanted to publish. However, I&#8217;ve been dealing with varying degree of integration complexityÂ to some of my application environments at the office. Inevitably, someone would scratch their head for several minutes trying to figure out why something failed only to realize that it was due to an external dependency. Needless to say, a simple tool that would provide a holistic view of the system could have saved them some pain. This could then be expanded to other environments: shared&#8230;]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ve been meaning to contribute to open source for some time. I really didn&#8217;t have anything particularly in mind to what I wanted to publish. However, I&#8217;ve been dealing with varying degree of integration complexityÂ to some of my application environments at the office. Inevitably, someone would scratch their head for several minutes trying to figure out why something failed only to realize that it was due to an external dependency. Needless to say, a simple tool that would provide a holistic view of the system could have saved them some pain. This could then be expanded to other environments: shared development, integration, UAT, QA, and Production. A single page that would provide an overview of the health of the specified environment would be very helpful.</p>
<p><strong>Application Monitoring</strong></p>
<p>There are several things to consider when monitoring an application. This is not meant as an exhaustive list but here are few items:</p>
<ul>
<li>application state</li>
<li>resource utilization</li>
<li>proactively report application errors</li>
<li>module/component status</li>
<li>external dependency status (databases, services, etc.)</li>
</ul>
<p>The monitor should be proactive and not reactive. It should provide early enough warning before something goes wrong. This includes monitoring dependencies and the application itself.Â There are tools that monitor logs and report when it detects various errors in the log file. Although this is better than nothing, it&#8217;s too reactive. If you&#8217;re lucky enough to have nagios in-house, this is better. However, in most cases, they are configured only for Production and, if lucky, QA. However, for other environments, it may be an overkill to use nagios.</p>
<p><strong>Health Monitoring</strong></p>
<p>The purpose of my <a href="https://github.com/johnra74/health-monitor">health monitor tool</a> is to provide a simple framework to quickly setup and actively check the overall health of any application.</p>
<p><a href="/wp-content/uploads/2013/09/healthmonitor.png"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-345" src="/wp-content/uploads/2013/09/healthmonitor.png" alt="healthmonitor" width="749" height="349" /></a></p>
<p>Health monitoring tool is built on the following open source frameworks:</p>
<ul>
<li><a href="http://quartz-scheduler.org/">quartz-scheduler</a> &#8211; used to schedule recurring checks to verify your site, components/modules, and dependencies</li>
<li><a href="http://hc.apache.org/">apache httpcomponents</a> &#8211; used to retrieve resources (JSON/HTML) from HTTP/HTTPS servers</li>
<li><a href="http://grizzly.java.net/">grizzly NIO framework</a> &#8211; used as embedded web container to host status page (see above screenshot)</li>
<li><a href="https://github.com/FasterXML/jackson">jackson</a> &#8211; used to parse JSON resources and configuration</li>
<li><a href="http://freemarker.org/">freemarker</a> &#8211; used for web/email template</li>
<li><a href="http://www.oracle.com/technetwork/java/javamail/index.html">javamail</a> &#8211; used to send failure notification</li>
</ul>
<p>It can proactively check your application and its dependencies with predefined service checks:</p>
<ul>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/svc/impl/HttpService.java">com.jstrgames.monitor.svc.impl.HttpService</a> &#8211; make non-SSL web call</li>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/svc/impl/HttpsService.java">com.jstrgames.monitor.svc.impl.HttpsService</a> &#8211; make SSL web call</li>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/svc/impl/SimpleJmxService.java">com.jstrgames.monitor.svc.impl.SimpleJmxService</a> &#8211; make simple remote JMX calls</li>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/svc/impl/SocketService.java">com.jstrgames.monitor.svc.impl.SocketService</a> &#8211; make a client socket call</li>
</ul>
<p>It can then verify these services with predefined rules:</p>
<ul>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/rule/HttpResponseCode.java">com.jstrgames.monitor.rule.HttpResponseCode</a> &#8211; check if expected status code returned</li>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/rule/HttpResponseBody.java">com.jstrgames.monitor.rule.HttpResponseBody</a> &#8211; check if body contains expected values</li>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/rule/JsonResponse.java">com.jstrgames.monitor.rule.JsonResponse</a> &#8211; check if specified JSON key has expected value</li>
<li><a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/main/java/com/jstrgames/monitor/rule/SimpleJmxResult.java">com.jstrgames.monitor.rule.SimpleJmxResult</a> &#8211; check if specified JMX attribute has expected value</li>
</ul>
<p>All can be configured on a simple <a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor/src/test/resources/demo.services.json">JSON format configuration file</a>.</p>
<p><strong>Example: Checking HTTPS site</strong></p>
<p>The use case is to verify that the text &#8220;Google Search&#8221; and &#8220;I&#8217;m Feeling Lucky&#8221; appears on the google.com page every 5 minutes:</p>


<pre class="wp-block-code"><code>&#91;{"servicename": "HTTPS Example (SSL)",
  "classname": "com.jstrgames.monitor.svc.impl.HttpsService",
  "schedule": "0 0/5 * * * ?",
  "hostname": "www.google.com",
  "port": 443,
  "uri": "/",
  "rules": &#91;{
    "classname": "com.jstrgames.monitor.rule.HttpResponseCode",
    "condition": "equals",
    "expected": 200
  },{
    "classname": "com.jstrgames.monitor.rule.HttpResponseBody",
    "condition": "contains",
    "expected": "Google Search"
  },{
    "classname": "com.jstrgames.monitor.rule.HttpResponseBody",
    "condition": "contains",
    "expected": "I'm Feeling Lucky"
  }]
}]</code></pre>



<p>Here, class com.jstrgames.monitor.svc.impl.HttpsService is used check www.google.com at port 443. Once the resource has been retrieved, 3 rules are executed:</p>



<ul><li>verify http response code is 200</li><li>verify http response body contains the phrase &#8220;Google Search&#8221;</li><li>verify http response body contains the phrase &#8220;I&#8217;m Feeling Lucky&#8221;</li></ul>



<p>If any of the above checks fails, service is considered to be in &#8220;FAIL&#8221; status. If it fails to connect to said service, it is in &#8220;ERROR&#8221; status. It will also send out a notification and user will see a similar content in their inbox, granted, not as pretty.</p>



<div class="wp-block-image"><figure class="aligncenter"><a href="/wp-content/uploads/2013/09/healthmonitor.email_.png"><img decoding="async" src="/wp-content/uploads/2013/09/healthmonitor.email_.png" alt="healthmonitor.email" class="wp-image-353"/></a></figure></div>



<p>For more details, please go to my <a href="https://github.com/johnra74/health-monitor/blob/master/health-monitor">github repository</a>. I will be updating its wiki page soon.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>That&#8217;s Groovy!</title>
		<link>/2013/07/25/thats-groovy/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Thu, 25 Jul 2013 21:51:45 +0000</pubDate>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Scripting]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=323</guid>

					<description><![CDATA[Ask me a month ago regarding my choice of scripting language, my answer would have been Perl or, if it&#8217;s a trivial use case, Bash. That&#8217;s no longer the case. Now, I am eager to flex my Groovy knowledge. Why Groovy? Consider the use case of executing a system command and redirecting the output to be processed by your program. With Perl, this is a trivial task: just use a backquote to perform your system command. Perl will assign the result of your standard out to the left-hand variable. In Groovy, it&#8217;s just as easy. Now, imagine having to perform&#8230;]]></description>
										<content:encoded><![CDATA[<p>Ask me a month ago regarding my choice of scripting language, my answer would have been Perl or, if it&#8217;s a trivial use case, Bash. That&#8217;s no longer the case. Now, I am eager to flex my Groovy knowledge.</p>
<p><strong>Why Groovy?</strong></p>
<p>Consider the use case of executing a system command and redirecting the output to be processed by your program. With Perl, this is a trivial task: just use a backquote to perform your system command. Perl will assign the result of your standard out to the left-hand variable.</p>


<pre class="wp-block-code"><code>$output = `ls -l`;
print $output, "\n";</code></pre>



<p>In Groovy, it&#8217;s just as easy.</p>



<pre class="wp-block-code"><code>def process = "ls -l".execute()
println "${process.text}"</code></pre>



<p>Now, imagine having to perform this in Java:</p>



<pre class="wp-block-code"><code>try {
  StringBuffer stdout = new StringBuffer();
  Process p = Runtime.getRuntime().exec( "ls -l" );

  BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()) );
  while ((line = in.readLine()) != null) {
    stdout.append(line);
  }
  in.close();
}
catch (Exception e) {
  // ...
}</code></pre>



<p>Did I get your attention? I hope so. Let&#8217;s consider list. I think Groovy is better at list than Perl. Take the use case of sorting a list of numbers. In Perl, it would look akin to this.</p>



<pre class="wp-block-code"><code>@list = (1, 23, 4, 6, 12, 5, 36);
@sortedlist = sort {$a &lt;=> $b} @list;
print "@sortedlist ";</code></pre>



<p>In Groovy, it&#8217;s even shorter</p>



<pre class="wp-block-code"><code>def list = &#91;1, 23, 4, 6, 12, 5, 26]
println list.sort()</code></pre>



<p>Lists are easier to work with in Groovy. If you want to print a sub-range, it&#8217;s &#8220;println list[1..3]&#8221;. If you want the last 3 items in the array in reverse order, it&#8217;s &#8220;println list[-3..-1]&#8221;. Negative index tell Groovy to retrieve the item from tail and work its way back.</p>



<p>If you&#8217;re a Java developer, how can you not love Groovy.</p>



<p><strong>Like Java, Love Groovy</strong></p>



<p>Groovy is built on Java. It brings dynamic typing and the benefits of dynamic language to the world of Java but still provides static typing when needed. Because it&#8217;s built on Java, Groovy has access to all the Java API available in your classpath. By default, the following classes are exposed to Groovy:</p>



<ul><li>java.io.*</li><li>java.lang.*</li><li>java.math.BigDecimal</li><li>java.math.BigInteger</li><li>java.net.*</li><li>java.util.*</li></ul>



<p>If you need a class not imported by default, if it&#8217;s in the classpath, Groovy can use them. You can import them in or use the fully qualifying classname:</p>



<pre class="wp-block-code"><code>println java.sql.Date.valueOf("2013-12-31").getTime()</code></pre>



<p>As stated earlier, all of Java libraries are at your disposal. Short of sounding like an infomercial, that&#8217;s not all! You can compile Groovy program and it will become accessible from Java. Consider having to write a simple POJO. Sure, you can use most IDEs to generate your getters and setters, but with Groovy, this can be simplified.</p>



<pre class="wp-block-code"><code>package com.jstrgames.groovy.example

class Book {
  String title
  String author

  String toString() { "${title} ${author}" }
}</code></pre>



<p>Once compiled by Groovy compiler, com.jstrgames.groovy.example.Book can be accessed from any Java program. It will also automatically create all your getters and setters for each property: getTitle(), setTitle(), getAuthor(), and setAuthor(). If you want to use this class in Groovy, you can directly access the properties:</p>



<pre class="wp-block-code"><code>def book = new Book( title: "Groovy by Action", author: "Dierk Koenig" )
println book

def myBook = new Book()
myBook.title = "Tech Genre"
myBook.author = "John Ra"
print myBook</code></pre>



<p>You can clearly see an increased productivity building modules/application/APIs with Groovy. If you want to learn more, I highly recommend reading <em>Groovy by Action</em> by Dierk Koenig.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Axis2 and NTLMv2</title>
		<link>/2012/08/23/axis2-ntlmv2/</link>
		
		<dc:creator><![CDATA[John Ra]]></dc:creator>
		<pubDate>Fri, 24 Aug 2012 02:30:56 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[.NET WebServices]]></category>
		<category><![CDATA[Axis2]]></category>
		<category><![CDATA[HttpComponent]]></category>
		<category><![CDATA[NTLMv2]]></category>
		<category><![CDATA[SharePoint]]></category>
		<guid isPermaLink="false">http://blog.jstrgames.com/?p=77</guid>

					<description><![CDATA[Every once in a while, an email thread is started by an individual wanting to know how to connect to&#160;SharePoint web services from java. The first time I came across this challenge was back in 2007 when I was building a Proof-of-Concept (PoC) workflow system for the business group I was supporting. One of the key requirements of this system was to retain an audit trail of all emails and documents associated with a given workflow. To put it bluntly, SharePoint wasn&#8217;t my first choice. I was very much aware of other&#160;document management systems which would have been a better&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Every once in a while, an email thread is started by an individual wanting to know how to connect to&nbsp;SharePoint web services from java. The first time I came across this challenge was back in 2007 when I was building a Proof-of-Concept (PoC) workflow system for the business group I was supporting. One of the key requirements of this system was to retain an audit trail of all emails and documents associated with a given workflow. To put it bluntly, SharePoint wasn&#8217;t my first choice. I was very much aware of other&nbsp;document management systems which would have been a better fit. Let&#8217;s just say that business politics plays a nasty role in hindering technology decisions. Since I needed to work with SharePoint, the technical problem was the same today as it was back then: Microsoft security protocol, specifically <a href="http://en.wikipedia.org/wiki/NTLM#NTLMv2">NTLMv2</a>. Given that my initial architecture was based on Java platform, I needed <a href="https://github.com/johnra74/sharepoint-api">Java to talk to SharePoint web services</a> that was protected behind NTLMv2.</p>



<p>It didn&#8217;t take long before&nbsp;I managed to stumble across a pure Java API from <a href="http://www.oaklandsoftware.com/product_http/overview.html">Oakland Software</a>. Oakland Software team&nbsp;managed to reverse engineer the NTLMv2 security protocol. With this API, I could plug-in an Oakland&#8217;s&nbsp;HttpClient agent&nbsp;into Apache Axis1 to seamlessly communicate with SharePoint.&nbsp;It worked perfectly. However, it was too risky to build a system that relied on a small unknown company that licensed this technology.&nbsp;Instead, I mitigate this risk by re-architecting&nbsp;the whole system&nbsp;on .NET platform. As anyone that has dealt with Microsoft knows, MS products always work better with other MS products.&nbsp;Since then, a lot has changed.&nbsp;Oakland has <a href="http://code.google.com/p/oakland-software-java-http-client/">open sourced</a> their API and Microsoft has made a <a href="http://www.microsoft.com/openspecifications/en/us/programs/wspp/wspp-patents/default.aspx">patent pledge</a> not to purse open-source developers. If you wanted to, you can still use Oakland API and Axis1 to communicate over NTLMv2. That&#8217;s one alternative. The other alternative, which I think is more forward thinking,&nbsp;is to use <a href="http://axis.apache.org/axis2/java/core/">Axis2</a> with <a href="http://hc.apache.org/httpcomponents-client-ga/">HttpComponents</a>, HttpClient v3 replacement.</p>



<p><strong>The Good, The Bad, and the Ugly</strong><br>You&#8217;re probably thinking, &#8220;thanks for the history lesson but I really just want to know how to get java to talk to services behind NTLMv2 security.&#8221; First, the good news is that Axis2 will be integrated to HttpClient v4, which happens to support NTLMv2.&nbsp;The bad news is that it won&#8217;t be available until Axis2 version 1.7 is released. Then comes the ugly news, as of Aug 22, their latest snapshot implementation doesn&#8217;t work. From looking at the source code, there&#8217;s a bug that causes Axis2 to still load HttpClient v3. This is due to <a href="http://svn.apache.org/viewvc/axis/axis2/java/core/trunk/modules/transport/http/src/org/apache/axis2/transport/http/CommonsHTTPTransportSender.java?revision=1354438&amp;view=markup">line&nbsp;376</a>:&nbsp;&#8220;sender = new HTTPSenderImpl();&#8221;. The base class is hardcoded to use httpclient v3. Below is a simple patch that I&#8217;ve written.</p>



<pre class="wp-block-code"><code>// Commenting out original code as it loads httpclient v3. This should really
// be refactored in an abstract method. For now, patching with simpler if condition
// sender = new HTTPSenderImpl();
if(this instanceof org.apache.axis2.transport.http.impl.httpclient4.HTTPClient4TransportSender) {
  sender = new org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl();
} else {
Â&nbsp;Â&nbsp;sender = new org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl();
}</code></pre>



<p>Ideally, this class should have an abstract&nbsp;method that will be over written by extended classes in httpclient3 package or httpclient4 package. For now, I&#8217;ve patched it to perform a simple instance check to identify the extended class and call the correct corresponding HTTPSenderImpl class. The following will provide step by step instructions on how to run Axis2 v1.7 + HttpComponent v4.1 to communicate to a .NET SOAP service sitting behind NTLMv2</p>



<p><strong>1. Setting up IIS with NTLMv4</strong><br>First, We&nbsp;need to setup&nbsp;test environment with NTLMv2 enabled. If you already have access to IIS with NTLMv2 enabled, you can skip to the next section. Otherwise, here are instructions on how to setup IIS 7 on Windows 7 Professional, Enterprise, or Ultimate: Go to your Control Panel and click Programs -&gt; &#8220;Turn Windows features on or off&#8221;.</p>



<figure class="wp-block-image"><a href="/wp-content/uploads/2012/08/NTLM_IIS7Install.png"><img decoding="async" src="/wp-content/uploads/2012/08/NTLM_IIS7Install-300x125.png" alt="" class="wp-image-81" title="NTLM_IIS7Install"/></a></figure>



<p>Expand &#8220;Internet Information Services&#8221; and&nbsp;check the following features:</p>



<ul>
<li>IIS Management Console</li>



<li>IIS Management Service</li>



<li>.NET Extensibility</li>



<li>ASP.NET</li>



<li>ISAPI Extensions</li>



<li>ISAPI Filters</li>



<li>Request Filtering</li>



<li>Windows Authentication</li>
</ul>



<p>Once installed, go to &#8220;Control Panel&#8221; -&gt; &#8220;System and Security&#8221; -&gt; &#8220;Administrative Tools&#8221; and&nbsp;open &#8220;Internet Information Service (IIS) Manager&#8221;.&nbsp;You can either perform the following steps at the server level or at individual site level. In either place, if you click on your server name or &#8220;Default Web Site&#8221;, you&#8217;ll have several options appear on right. Double-click on &#8220;Authentication&#8221; and disable all but Windows Authentication option.</p>



<figure class="wp-block-image"><a href="/wp-content/uploads/2012/08/NTLM_IIS7Setup.png"><img decoding="async" src="/wp-content/uploads/2012/08/NTLM_IIS7Setup.png" alt="" class="wp-image-83" title="NTLM_IIS7Setup"/></a></figure>



<p>This will enable NTLMv2 and protect you site. All requests to this site will challenge user for valid Windows credentials.</p>



<p><strong>2. Deploy Test Application</strong><br>Download my simple <a href="http://www.jstrgames.com/demo/NTLMWeb.zip">.NET TimeService</a> web application.&nbsp;Unzip and place the content anywhere on your computer. From IIS Manager, create a virtual application under Default Web Site and give the alias &#8220;TimeService&#8221;. The &#8220;Physical Path&#8221; should point to the location of the recently downloaded and&nbsp;unzipped .NET web application. If you open up App_Code\TimeService.cs file, you&#8217;ll see the following.</p>



<pre class="wp-block-code"><code>&#91;WebMethod]
public string Now(string name)
{
  return name + ", current time is " + DateTime.Now.ToShortTimeString();
}</code></pre>



<p>This is a simple .NET web service application that returns the current time for the specified parameter. If all works out,&nbsp;when you visit <a href="http://localhost/TimeService/TimeService.asmx?WSDL">http://localhost/TimeService/TimeService.asmx?WSDL</a>, assuming your site is running under port 80, you&#8217;ll be prompted to login with your windows credential. Once logged in, you&#8217;ll see the <a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language">WSDL</a> for this web service.</p>



<p><strong>3. Generating Axis2 Client</strong><br>If you&#8217;re familiar with Axis, you should know that it comes with a tool to generate Java client based on specified WSDL. If you&#8217;re not, now you know. Since the target WSDL is protected behind NTLMv2, the simplest way is to visit the site&nbsp;using your credentials and then save the WSDL to your file system. To generate the java client stubs, please visit <a href="http://axis.apache.org/axis2/java/core/docs/userguide-creatingclients.html">Axis2 website</a> for their instructions. It&#8217;s pretty thorough.&nbsp;You can also download my <a href="http://www.jstrgames.com/demo/Axis2NTLM.zip">Eclipse Projects</a> which has both the above Axis2 v1.7 patch and generated java stubs based on the TimeService WSDL.</p>


<div class="wp-block-image">
<figure class="alignleft"><a href="/wp-content/uploads/2012/08/NTLM_EclipseSetup.png"><img decoding="async" src="/wp-content/uploads/2012/08/NTLM_EclipseSetup-150x150.png" alt="" class="wp-image-87" title="NTLM_EclipseSetup"/></a></figure></div>

<div class="wp-block-image">
<figure class="alignright"><a href="/wp-content/uploads/2012/08/NTLM_EclipseRun.png"><img decoding="async" src="/wp-content/uploads/2012/08/NTLM_EclipseRun.png" alt="" class="wp-image-88" title="NTLM_EclipseRun"/></a></figure></div>


<p><strong>4. Running Java Client</strong><br>In Axis2NTLMClient project downloaded from prior step, locate the Client.java class which contains the main method. Prior to running this class, you must add a VM argument (&#8220;-Daxis2.xml=conf/axis2.xml&#8221;) under Run Configuration in Eclipse (see image left). This VM argument informs Axis2 to use the axis2.xml located in conf folder instead of the <a href="http://svn.apache.org/viewvc/axis/axis2/java/core/trunk/modules/kernel/conf/">default</a> that comes with axis2-kernel.jar. The version in config/axis.xml has&nbsp;been modified to inform Axis2 to use HTTPClient v4 Transporter (line 232). When you run this class, you will be prompted with a login screen. This is a custom login dialog that I&#8217;ve written as I&#8217;m not a fan of saving username and password in properties file or in code. This simple login dialog will capture your username, password, and domain.&nbsp;If all goes well, you should see the following message on your console screen: &#8220;John, current time is &lt;&lt;your current time&gt;&gt;&#8221;.</p>



<p><strong>Analysis</strong><br>When Client class is&nbsp;constructed, it will call the setupAuthentication() method. This method will construct the authenticator and will set the username, password, and domain entered by user.</p>



<pre class="wp-block-code"><code>private void setupAuthentication() {
  this.auth = new HttpTransportPropertiesImpl.Authenticator();
  try {
    showLoginDialog();
  } catch (java.awt.HeadlessException e) {
    log.fine("User does not have a desktop session! using console");
    showLoginConsole();
  }

  auth.setRealm(AuthScope.ANY_REALM);
  auth.setHost(this.host);// must MATCH target Host
  auth.setPort(this.port);// must MATCH target Port
}</code></pre>



<p>The HeadlessException catch logic is put in place in the event user does not have a windows/xsession available. It will use the default console to capture username, password, and domain. By default, I set the Realm to ANY_REALM. I haven&#8217;t played around enough with Realm to give you additional insight. As for host and port, it MUST match the target URL. For example, if you decided to connect to site via IP address (e.g. 127.0.0.1) instead of &#8220;localhost&#8221;, you must setHost() with IP address. For this reason, my Client class is constructed with host and port to ensure consistency.</p>



<pre class="wp-block-code"><code>public String getResponse(String param) {
  try {
    TimeServiceStub service = new TimeServiceStub(getServiceEndPoint());

    Options options = service._getServiceClient().getOptions();
    options.setProperty(HTTPConstants.AUTHENTICATE, this.auth);
    options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);

    Now req = new Now();
    req.setName(param);
    NowResponse resp = service.now(req);

    return resp.getNowResult();

  } catch (AxisFault e) {
    log.severe(e.getMessage());
  } catch (RemoteException e) {
    log.severe(e.getMessage());
  }
  return new String();
}</code></pre>



<p>Once the authenticator has been&nbsp;constructed,&nbsp;Axis2 generated java class TimeServiceStub is used to connect to the .NET SOAP service. The helper method &#8220;getServiceEndPoint()&#8221; will generate and return the location of the webservice end point. It then set the options for AUTHENTICATE to use the constructed authenticator and disables CHUNKED on the transport encoding. If you do not disable the CHUNKED transport encoding on .NET services, <a href="http://stackoverflow.com/questions/11694315/axis2-http-400-error-with-vs2010-development-server">it will break</a>. Request class Now is used to set the parameter and the result of the SOAP service is returned through NowResponse class.</p>



<p>As HttpComponent v4 has a pure Java implementation of NTLMv2, you can run this client from any OS. Here&#8217;s a screenshot from my Ubuntu Server.</p>



<figure class="wp-block-image"><a href="/wp-content/uploads/2012/08/NTLM_EclipseRunUbuntu.png"><img decoding="async" src="/wp-content/uploads/2012/08/NTLM_EclipseRunUbuntu.png" alt="" class="wp-image-90" title="NTLM_EclipseRunUbuntu"/></a></figure>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
