<?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>Andy Gibson</title>
	<atom:link href="http://www.andygibson.net/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Thu, 02 Sep 2021 22:14:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.8.13</generator>
	<item>
		<title>Creating a simple OSGI Bundle By Hand</title>
		<link>http://www.andygibson.net/blog/article/creating-a-simple-osgi-bundle-by-hand/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Thu, 02 Sep 2021 22:07:50 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Felix]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OSGI]]></category>
		<guid isPermaLink="false">https://www.andygibson.net/blog/?p=2563</guid>

					<description><![CDATA[As a bit of an experiment I tried to create an OSGI Bundle by hand and run it with Apache Felix. OSGI is a specification for building modular Java applications. Like many things Java it is based on a specification with multiple implementations. Equinox is the implementation that the Eclipse framework is built upon to [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>As a bit of an experiment I tried to create an OSGI Bundle by hand and run it with Apache Felix.</p>



<span id="more-2563"></span>



<p>OSGI is a specification for building modular Java applications. Like many things Java  it is based on a specification with multiple implementations. Equinox is the implementation that the Eclipse framework is built upon to provide an extensible IDE. Alternatively, there are other implementations such as <a href="https://felix.apache.org/" title="https://felix.apache.org/" target="_blank" rel="noreferrer noopener">Felix</a> and <a href="https://www.knopflerfish.org/" target="_blank" rel="noreferrer noopener" title="https://www.knopflerfish.org/">Knopflerfish</a>.</p>



<p>As of 2021, OSGI has been around for quite a while. However, my interest has been piqued over the last year since I&#8217;ve been working with Eclipse plugins. When working on Eclipse plugins it always felt like Eclipse is doing a lot of the background work. As a result, I thought I would throw out all the tooling and give it a try from scratch.</p>



<h2>The Project</h2>



<p>This project is meant as a light introduction to OSGI in which we are going to :</p>



<ul><li>Create a simple Activator class that is</li><li>Packaged into an OSGI bundle which is then </li><li>Loaded into an OSGI Container and then</li><li>Started and </li><li>Stopped and finally</li><li>Uninstalled</li></ul>



<p>If any of those terms seem strange, I&#8217;ll be explaining them as I go. Firstly, a bundle is just a special jar file that contains some additional content in the <code>MANIFEST.MF</code> file. This extra metadata allows OSGI containers to install the bundle, check that all dependencies are available and notify the activator that it has started. The activator is a class that implements the <a href="https://docs.osgi.org/javadoc/osgi.core/8.0.0/org/osgi/framework/BundleActivator.html" target="_blank" rel="noreferrer noopener" title="https://docs.osgi.org/javadoc/osgi.core/8.0.0/org/osgi/framework/BundleActivator.html">BundleActivator</a> interface and is called when the bundle is started and stopped. </p>



<p>First we will create a directory with our project in:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
mkdir osgiTest
cd osgiTest
mkdir -p uk/co/andygibson/osgi/helloworld/
mkdir META-INF
&amp;lt;edit&gt; uk/co/andygibson/osgi/helloworld/Activator.java
</pre></div>


<p>Substitute &lt;edit&gt; with the editor (atom, code, gedit, nano, notepad, vim  etc) of your choice to edit a new file called Activator.java. </p>



<p>Additionally, you should have the <code>java</code>, <code>jar</code> and <code>javac</code> tools on the command line path to be easily called.</p>



<h2>The Source</h2>



<p>Once you have the Activator.java file in an editor, add the following code:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
package uk.co.andygibson.osgi.helloworld;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

    public void start(BundleContext context) throws Exception {
        System.out.println(&quot;Starting my activator&quot;);
    }
    public void stop(BundleContext context) throws Exception {
        System.out.println(&quot;Stopping my activator&quot;);
    }
}
</pre></div>


<p>This is our activator completed. It is called by the OSGI container when our bundle is started and stopped. The activator is referenced from the <code>META-INF/MANIFEST.MF</code> file which we&#8217;ll edit next:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Bundle-Bundle-RequiredExecutionEnvironment: JavaSE-1.8	
Bundle-SymbolicName: uk.co.andygibson.osgi.helloworld
Bundle-Bundle-Version: 1.0.0
Bundle-Name: Hello World App
Bundle-ManifestVersion: 2
Bundle-Classpath: .
Bundle-Activator: uk.co.andygibson.osgi.helloworld.Activator
Export-Package: uk.co.andygibson.osgi.helloworld
Import-Package: org.osgi.framework;version=1.3.0
</pre></div>


<p>These attributes define our Bundle, the version of java it requires and any dependencies we need and also the location of our activator class.</p>



<h2>The Build</h2>



<p>We are going to use plain old command line tools to compile our Bundle &#8211; I did say it was OSGI by hand. We need to :</p>



<ul><li>Compile our activator</li><li>Package our activator into a jar file with our MANIFEST.MF</li></ul>



<p>In order to compile, we&#8217;ll need a copy of the <code>org.osgi.framework jar</code> dependency. There are a couple of ways of doing this, you can download it from somewhere, or search for a local copy. You might even have one in your local maven repository which is where I got mine. Once you have a copy, you can add it to the following line to compile your activator:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
javac -cp org.osgi.framework-1.9.0.jar uk/co/andygibson/osgi/helloworld/Activator.java

</pre></div>


<p>Once completed, we have class file in the <code>uk/co/andygibson/osgi/helloworld</code> folder. To jar it up use the jar command to create a jar file containing our class and the MANIFEST.MF file.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
jar cvfm uk.co.andygibson.osgi.helloworld.1.0.jar META-INF/MANIFEST.MF uk/co/andygibson/osgi/helloworld/Activator.class 
</pre></div>


<h2>The Execution</h2>



<p>In our directory , we have a jar file that contains our class and the MANIFEST.MF. This is now a bundle which can be loaded into an OSGI container. For this, we will use <a href="https://felix.apache.org/" target="_blank" rel="noreferrer noopener" title="https://felix.apache.org/">Felix</a>. Go to the <a href="https://felix.apache.org/documentation/downloads.html" target="_blank" rel="noreferrer noopener" title="https://felix.apache.org/documentation/downloads.html">Downloads</a> page and download a zipped version of the the framework. It should be at the top of the page under &#8220;Felix Framework Distribution&#8221;.  Download the zip binary, and unzip it in a folder. </p>



<p>Open a terminal and go to the folder containing Felix and start it by typing:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
java -jar bin/felix.jar
</pre></div>


<p>You should end up with a felix console that will let you query the OSGI container. Try typing <code>lb</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
g! lb
START LEVEL 1
   ID|State      |Level|Name
    0|Active     |    0|System Bundle (7.0.1)|7.0.1
    1|Active     |    1|jansi (1.18.0)|1.18.0
    2|Active     |    1|JLine Bundle (3.13.2)|3.13.2
    3|Active     |    1|Apache Felix Bundle Repository (2.0.10)|2.0.10
    4|Active     |    1|Apache Felix Gogo Command (1.1.2)|1.1.2
    5|Active     |    1|Apache Felix Gogo JLine Shell (1.1.8)|1.1.8
    6|Active     |    1|Apache Felix Gogo Runtime (1.1.4)|1.1.4
</pre></div>


<h3>Starting the Bundle</h3>



<p>Now lets install and start our bundle. In the Felix console, type the following:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
g! felix:install /home/andy/dev/projects/osgiTest/uk.co.andygibson.osgi.helloworld.1.0.jar
Bundle ID: 12
g! start 12
Starting my activator
</pre></div>


<p>Finally, we&#8217;ve installed the bundle, for which we received a bundle id (12). We then used that to start the bundle which caused the activator message to display.</p>



<p>If you type <code>lb</code> again, you will see the similar list of bundles, but our bundle will be included there now:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
START LEVEL 1
   ID|State      |Level|Name
    0|Active     |    0|System Bundle (7.0.1)|7.0.1
    1|Active     |    1|jansi (1.18.0)|1.18.0
    2|Active     |    1|JLine Bundle (3.13.2)|3.13.2
    3|Active     |    1|Apache Felix Bundle Repository (2.0.10)|2.0.10
    4|Active     |    1|Apache Felix Gogo Command (1.1.2)|1.1.2
    5|Active     |    1|Apache Felix Gogo JLine Shell (1.1.8)|1.1.8
    6|Active     |    1|Apache Felix Gogo Runtime (1.1.4)|1.1.4
   12|Active     |    1|Hello World App (0.0.0)|0.0.0

</pre></div>


<p>If you type <code>felix:stop 12</code> you will see the close message in the console. This is because it stops our bundle and causes the Activator stop method to be called.</p>



<p>You can start and stop the bundle as many times as you want. Additionally, you can even start and stop Felix and see that the start amd stop activator methods are called when we start and stop the container.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
g! exit 0
Stopping my activator
...
...
java -jar bin/felix.jar 
Starting my activator
____________________________
Welcome to Apache Felix Gogo

g!
</pre></div>


<h2>The Tooling</h2>



<p>Without a doubt, its easy to see why we use tooling to create our java apps. This is just a couple of files and is quite a task. Traditional tools like Maven or Gradle use repositories to supply us with dependencies on demand based on the contents of their source files, pom.xml for example.</p>



<p> However, if we were to use maven we would specify our dependencies in the pom file. At the same time,  it would mean we need to manually keep dependencies in the MANIFEST.MF file up to date. Unsurprisingly, this is where special tools like Tycho, BND and Eclipse plugin projects come in. They work with the manifest file and use that to provide the list of dependencies (so called Manifest first tools like Tycho or Eclipse). Others can build up the manifest file based on the configuration of the tool (i.e. BND) to build dependencies that way.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Inherited Jackson Serializers</title>
		<link>http://www.andygibson.net/blog/article/inherited-jackson-serializers/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Sun, 23 Feb 2020 21:02:34 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Jackson]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2434</guid>

					<description><![CDATA[Looking at the Jackson Serializer post, it does introduce a particular code smell as it uses if statements to check the type of object and take a different action based on that type. Normally, that is indicative of the need to implement the action in the class and/or subclasses. However, this is serialization and we [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Looking at the <a rel="noreferrer noopener" aria-label="Jackson Serializer (opens in a new tab)" href="http://www.andygibson.net/blog/article/introduction-to-jackson-serializers/" target="_blank">Jackson Serializer</a> post, it does introduce a particular code smell as it uses <code>if</code> statements to check the type of object and take a different action based on that type. Normally, that is indicative of the need to implement the action in the class and/or subclasses. However, this is serialization and we certainly don&#8217;t want to put any serialization code in the model classes themselves. This article looks at getting rid of that code smell using inheritance with serializers. The source code is available in my <a href="https://github.com/andygibson/blog-post-code/tree/master/java/inherited-jackson-serializers" target="_blank" rel="noreferrer noopener" aria-label="blog post code repository (opens in a new tab)">blog post code repository</a>.</p>



<p>We can create a class hierarchy of serializers that makes use of inheritance to replace a set of if/then statements based on the object type. In this post, we&#8217;ll implement serializers that are inherited for the different Pet types and ensure that the serialization of each Pet type of encapsulated in its own serializer.</p>



<p>One problem is that the execution of overridden implementations  is sequential, we would execute the implementation in the parent class, then the first subclass, and then any further subclasses. Since our top level implementation likely consists of :</p>



<ul><li>Start writing an object &#8220;{&#8220;</li><li>Write Object properties  &#8220;x = 1&#8221;</li><li>End writing an object &#8220;}&#8221;</li></ul>



<p>If we subclass the serializer and override the <code>serialize()</code> method and call the parent implementation, in JSON we will open the object, close it, and then write any subclass properties. We want to open the object, write all of the properties, including subclass properties, and then close the object.</p>



<h3>Template Method</h3>



<p>We can solve this problem using a <a rel="noreferrer noopener" aria-label="template method (opens in a new tab)" href="https://en.wikipedia.org/wiki/Template_method_pattern" target="_blank">template method</a> which is invoked during the execution of an algorithm, and provides options to extend the algorithm while maintaining the main structure of it.  This is a good technique to use when you want to maintain a rigid list of actions, but allow one of those actions to be overridden and extended.</p>



<p>We&#8217;ll create an <code>ObjectSerializer</code> class that is used as the base class for our serializers. This class expects subclasses to be used to serialize objects.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public abstract class ObjectSerializer&lt;T&gt; extends StdSerializer&lt;T&gt; {

  public ObjectSerializer(final Class&lt;T&gt; t) {
    super(t);
  }

  @Override
  public void serialize(final T value, final JsonGenerator gen, final SerializerProvider provider) throws IOException {
    gen.writeStartObject();
    doWriteProperties(value, gen, provider);
    gen.writeEndObject();
  }

  protected abstract void doWriteProperties(final T value, final JsonGenerator gen, final SerializerProvider provider);
}

</pre></div>


<p>Our <code>serialize</code> method starts a new object, invokes the call to write the object properties, and then ends the object. Any properties written in the <code>doWriteProperties</code> method will sit inside the JSON object.</p>



<p>Our PetSerializer won&#8217;t write any Pet, but could just write the common properties for the Pet object :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class PetSerializer&lt;T extends Pet&gt; extends ObjectSerializer&lt;T&gt; {
  public PetSerializer(final Class&lt;T&gt; clazz) {
    super(clazz);
  }

  @Override
  protected void doWriteProperties(final T value, final JsonGenerator gen, final SerializerProvider provider)
      throws IOException {
    // this could go in the subclass serializer if a more calculated value was needed.
    gen.writeStringField(&quot;type&quot;, value.getClass().getSimpleName());
    gen.writeStringField(&quot;name&quot;, value.getName());
  }
}

</pre></div>


<p>Here we override the <code>doWriteProperties</code> method to write the type and the name, the two common values of the Pet type that need serializing. Note that we also enhanced the generic type to ensure that we only use this on subtypes of <code>Pet</code>.</p>



<p>We can now subclass this serializer for each of our Pet types :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class DogSerializer extends PetSerializer&lt;Dog&gt; {
  public DogSerializer() {
    super(Dog.class);
  }
  @Override
  protected void doWriteProperties(final Dog value, final JsonGenerator gen, final SerializerProvider provider)
      throws IOException {
    super.doWriteProperties(value, gen, provider);
    gen.writeStringField(&quot;size&quot;, value.getSize().toString());
  }
}
</pre></div>


<p>and </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class SnakeSerializer extends PetSerializer&lt;Snake&gt; {

  public SnakeSerializer() {
    super(Snake.class);
  }

  @Override
  protected void doWriteProperties(final Snake value, final JsonGenerator gen, final SerializerProvider provider)
      throws IOException {
    super.doWriteProperties(value, gen, provider);
    gen.writeNumberField(&quot;length&quot;, value.getLength());
  }
}

</pre></div>


<p>We have implemented the PetSerializer for our two classes and override the <code>doWriteProperties</code> method to write properties specific to that Pet. </p>



<p>To use our new serializers, we just need to register them with the Jackson <code>Module</code> in our main code. Note that we no longer need to register the <code>Pet</code> serializer since it is never used directly, only from their subclasses. We do however have to register the serializers for the <code>Dog</code> and <code>Snake</code> classes.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class Main {

  public static void main(final String&#x5B;] args) throws JsonProcessingException {
    final ObjectMapper objectMapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule(&quot;mySerializers&quot;);
    module.addSerializer(new PersonSerializer());
    module.addSerializer(new DogSerializer());
    module.addSerializer(new SnakeSerializer());
    objectMapper.registerModule(module);
    ...
    ...
  }
}
</pre></div>


<p>The rest of the code to create the model and write it to JSON will now still work with the new serializers used to write the objects. While this does get rid of the code smell mentioned originally, technically, it is only moving it to a hidden location. Jackson still does some kind of lookup for the class to determine what serializer it should use instead of a set of <code>if</code> statements to locate the matching serializer.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Introduction to Jackson Serializers</title>
		<link>http://www.andygibson.net/blog/article/introduction-to-jackson-serializers/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Thu, 20 Feb 2020 23:43:51 +0000</pubDate>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Jackson]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2417</guid>

					<description><![CDATA[Jackson is a framework that provides the means to read and write objects to and from JSON. Typically, it tries to use built in support for common classes and simple types. It will also use a default serializer based on reflection to write the JSON, but will need some guidance for more complex custom objects. [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p><a href="https://github.com/FasterXML/jackson" target="_blank" rel="noreferrer noopener" aria-label="Jackson (opens in a new tab)">Jackson</a> is a framework that provides the means to read and write objects to and from JSON. Typically, it tries to use built in support for common classes and simple types. It will also use a default serializer based on reflection to write the JSON, but will need some guidance for more complex custom objects. You can do this using annotations, or alternatively, you can write custom serializers/deserializers. Here I&#8217;m going to look at Jackson serializers to save objects to a JSON file. </p>



<span id="more-2417"></span>



<p>Most people&#8217;s first introduction to Jackson is using the default serializer through reflection and then using annotations or mixins. Annotations can be great but they can clutter code, cause additional dependencies and the more complex your situation, the less likely annotations are going to be enough to meet your needs. This is especially the case when you have to adhere to another JSON schema and don&#8217;t want to mirror that schema in your model with annotations.</p>



<p>Serializers are classes which can be used to serialize your objects into JSON. The advantage of these is that you have absolute control over the JSON that is produced. It does this by literally adding each element to the JSON document you are writing. </p>



<h3>Benefits of Serializers</h3>



<p>If you rely on annotations or even the default reflection serializers, you run the risk of having new fields introduced into your json documents and causing errors elsewhere, especially if it is being consumed by something that is strict about the expected content. Serializers make adding fields a very deliberate task around which you can put tests to ensure you are getting the JSON you expect.</p>



<p>For a little more work, you get complete control over your content and don&#8217;t have to worry about the limitations of annotations which sooner or later, in any larger project will pay off. By incorporating good design practices you can also construct a rich set of serializers that makes extending them easy.</p>



<p>The source code for the sample project is available on the <a href="https://github.com/andygibson/blog-post-code/tree/master/java/intro-jackson-serializers" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">blog post code repository</a> Let&#8217;s look at a simple model for our serializer:</p>



<p> Let&#8217;s look at a simple model for our serializer:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
class Person {
  private String firstName;
  private String lastName;
  private List&lt;Pet&gt; pets;
}

class Pet {
  private String name;
}

class Dog extends Pet {
  public enum Size {SMALL, MEDIUM, LARGE};
  private Size size;
}

class Snake extends Pet {
  private int length;
}
//getters/setters and convenience methods ommitted.
</pre></div>


<p>Each person has a list of pets which can be of different types. Polymorphism is often a problem when writing JSON because the JSON itself doesn&#8217;t indicate the type of the object being written. You can ask Jackson to persist a field to indicate the type so it can be deserialized later on. However, if you are dealing with a custom schema, that may not be an option, or the type may be based on some other logic.</p>



<p>We extend <code>StdSerializer</code> and implement the single method <code>serialize</code>. We also create an empty constructor which calls the <code>super</code> constructor with the class of object we are serializing.</p>



<p>We&#8217;ll start with our <code>Person</code> first and we&#8217;ll start by writing out our fields.  </p>



<p><code>PersonSerializer.java</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class PersonSerializer extends StdSerializer&lt;Person&gt; {

  protected PersonSerializer() {
    super(Person.class);
  }

  @Override
  public void serialize(final Person value, final JsonGenerator gen, final SerializerProvider provider)
      throws IOException {
    gen.writeStartObject();
    //write string field and field name in one method
    gen.writeStringField(&quot;firstName&quot;, value.getFirstName());
    gen.writeStringField(&quot;lastName&quot;, value.getLastName());
    //write the field name and then the value
    gen.writeFieldName(&quot;pets&quot;);
    gen.writeObject(value.getPets());
    gen.writeEndObject();
  }
}
</pre></div>


<p>When persisting the object, we use methods on the <code>JsonGenerator</code> to create content. We start by indicating we want to start a new object, and then we write our fields manually. When we call <code>writeObject</code> to write our pets, we pass in the object and Jackson will figure out how to serialize it. Finally, we call the method end our pet object . </p>



<p>Jackson will try and persist the <code>Pet</code> as a simple object using reflection to pull the properties and write them. This is alright if you don&#8217;t care about the final schema and you aren&#8217;t worrying about reading the JSON back in. Ideally, we want another serializer to write the <code>Pet</code> class taking into account all the different Pet subclass types.</p>



<p>Now lets look at serializing our <code>Pet</code>. We could write one serializer per concrete type, but we have the option of writing just a common <code>PetSerializer</code> class and all subclasses will use that serializer</p>



<p>For the pet, we want to write a value to indicate the type of Pet we are writing. We will make it the same as the simple class name for now. We then write the <code>Pet</code> fields and then fields that are specific to subclasses. One great thing about serializers is that you can utilise inheritance to make reusable serializers, or use composition to invoke another type serializer as needed.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class PetSerializer extends StdSerializer&lt;Pet&gt; {

  public PetSerializer() {
    super(Pet.class);
  }

  @Override
  public void serialize(final Pet value, final JsonGenerator gen, final SerializerProvider provider)
      throws IOException {
    gen.writeStartObject();

    gen.writeStringField(&quot;type&quot;, value.getClass().getSimpleName());
    gen.writeStringField(&quot;name&quot;, value.getName());

    if (value instanceof Snake) {
      gen.writeNumberField(&quot;length&quot;, ((Snake) value).getLength());
    }
    if (value instanceof Dog) {
      gen.writeStringField(&quot;size&quot;, ((Dog) value).getSize().toString());
    }
    gen.writeEndObject();
  }
}

</pre></div>


<h3>Putting It Together</h3>



<p>To test this, we need to construct a Jackson <code>ObjectMapper</code> instance and add these serializers to it using a module. We can then use the object mapper to save any combination of <code>Person</code> and <code>Pet</code> instances and collections. Once registered, Jackson will use the serializer anytime it encounters an object of that type. </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
  public static void main(final String&#x5B;] args) throws JsonProcessingException {
  public static void main(final String&#x5B;] args) throws JsonProcessingException {
    //you can create this once and re-use it everywhere
    final ObjectMapper objectMapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule(&quot;mySerializers&quot;);
    module.addSerializer(new PersonSerializer());
    module.addSerializer(new PetSerializer());
    objectMapper.registerModule(module);

    // build our models
    final Person p1 = ...
    final Person p2 = ...

    final Collection&lt;Person&gt; people = new ArrayList&lt;&gt;();
    people.add(p1);
    people.add(p2);

    // now write the json
    System.out.println(&quot;people unformatted is:\n&quot; + objectMapper.writeValueAsString(people));

    // grab the pretty printer and store it
    final ObjectWriter prettyWriter = objectMapper.writerWithDefaultPrettyPrinter();

    // now write formatted json
    System.out.println(&quot;people are :\n&quot; + prettyWriter.writeValueAsString(people));
    System.out.println(&quot;p1 is :\n&quot; + prettyWriter.writeValueAsString(p1));
    System.out.println(&quot;p2 is :\n&quot; + prettyWriter.writeValueAsString(p2));
    System.out.println(&quot;p2.pet(0) is :\n&quot; + prettyWriter.writeValueAsString(p2.getPets().get(0)));
  }
}
</pre></div>


<p>Here we have Jackson write a collection of people, and individual Person, or an individual Pet and it will use the serializer.  We also switch between using the pretty printer for displayable json, and the default writer which removes formatting and condenses the content.</p>



<h3>Additional Thoughts</h3>



<p>We technically, could/should put try/except blocks around the object/array start/end blocks like so : </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
gen.writeStartObject();
try {
  ...write properties to JSON...
} finally {
  gen.writeEndObject();
}
</pre></div>


<p>This is so we will always put the enclosing brace &#8216;}&#8217; on our JSON object in the event that an exception is thrown while generating the content. Problem is that as soon as the exception is thrown, then you won&#8217;t write any more of the object to the document, and you could end up with a partial document and no exception thrown. For that reason, I think its better to throw the exception and terminate generating the document. However, your mileage may vary.</p>



<h4>Serialize the object without context</h4>



<p> When creating a serializer, you have to implement it is as a way of serializing the object only. Assume it knows nothing about the context it is being written in, whether its a &#8216;pet&#8217; property, an array or a single item. For example, our PetSerializer writes the value for a single pet wrapped in a json object. Don&#8217;t assume it is being written as a pet property of another class and write the property name. Leave it to the invoking class to handle any content around the object being written. The PersonSerializer writes the &#8220;pets&#8221; field name then passes in the collection to be written. Jackson takes responsibility for writing the array start/end brackets of the collection and defers to the PetSerializer to write the Pet content. By doing this, you create serializers that are consistent and reusable. Don&#8217;t write serializers for collections of objects, just the object itself.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Why C++ ?</title>
		<link>http://www.andygibson.net/blog/programming/why-c/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Thu, 13 Feb 2020 20:32:12 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Cpp]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Personal]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2413</guid>

					<description><![CDATA[I made mention of my venturing back into the world of C++, and was asked why I was interested in doing so given all the Java work I do. The best answer I can give is based on a comment which I think was made by Bjarne Stroustrup himself when asked about the advantages of [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>I made mention of my venturing back into the world of C++, and was asked why I was interested in doing so given all the Java work I do. The best answer I can give is based on a comment which I think was made by Bjarne Stroustrup himself when asked about the advantages of C++ or why people should learn it. He said (paraphrasing) that C++ is the best language to represent the machine and maps closest to the hardware. </p>



<p>The current trends are to write code or scripts that are whisked away into the cloud to be interpreted or executed remotely on a garbage collected virtual machine, often through virtual containers on some kind of virtual computing instance.</p>



<p>For me, computing has always been personal, writing code that runs on a box that sits on, or below your desk. Writing something in C++ takes me back to those times, and reminds me of the metal that all our code runs on eventually.</p>



<p>It&#8217;s like taking a stroll through woodlands and getting back to basics, while taking a break from the city.</p>



<p>Don&#8217;t get me wrong, all those high level abstractions have their place and purpose, especially when considering some of the gotchas of C++, but sometimes its nice to pack a bag, and go camp in the woods. It may be difficult, but it&#8217;s a pleasant challenge.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Simple C++ Project Setup With CMake</title>
		<link>http://www.andygibson.net/blog/programming/from-java-to-c-project-setup/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Wed, 12 Feb 2020 21:47:14 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[CMake]]></category>
		<category><![CDATA[Cpp]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2398</guid>

					<description><![CDATA[As a Java developer, I wanted to dabble with a C++ project, something I&#8217;ve not done for a while. I was looking into how to structure my project with a view to getting started quickly, but ensuring that if I wanted to expand the project, I wouldn&#8217;t have to restructure it in order to keep [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>As a Java developer, I wanted  to dabble with a C++ project, something I&#8217;ve not done for a while. I was looking into how to structure my project with a view to getting started quickly, but ensuring that if I wanted to expand the project, I wouldn&#8217;t have to restructure it in order to keep things organised. This post talks about that project and the <a href="https://github.com/andygibson/blog-post-code/tree/master/c/cmake-basic">source is available</a> from my blog post code repository.</p>



<span id="more-2398"></span>



<p>Coming from a Java background, we are pretty lucky that Java has had multiple build tools that can help manage Java projects such as organising class and test sources, handling dependencies, running tests and so on. It was not always this way, originally, there were IDE specific builders that put the source in their own structures and knew how to build them. This was problematic if you wanted to build outside of the IDE, and wouldn&#8217;t work in today&#8217;s world of continuous integration.  Ant came along and let us write build scripts that could take source code of any structure and produce class, source and javadoc jar files for them, and IDEs could take advantage of such scripts.</p>



<p>With Maven, and later Gradle, we were able to create projects with a predefined structure that could be compiled easily just adding a class or test class file in a specific directory. IDEs were able to provide plugins to support these frameworks creating a fairly rich environment where it is easy to get started with Java.</p>



<p>With C++ (and of course plain old C), we don&#8217;t have the same solutions, historically, tools like Make have provided Ant-like build systems where you can put your source code where you like and write a script to find and build it. C++ has many more options with regards to compilation for things like build types (Release, Debug etc), linking dynamic &amp; static libs and the target platform to name a few. Some of this complexity was been wrapped up in a tool called CMake which is a higher level abstraction of the build process. Technically, its not a build system, it creates a configuration from which the project can be built.</p>



<p>So I wanted to come up with a basic template for a C++ project that can be built with CMake, and used as the basis for other projects. I wanted to be able to compile and run from the command line and also be able to run from an IDE such as Eclipse and/or KDevelop. I also wanted it to be structured such that it wasn&#8217;t overly verbose for small projects but flexible enough that I can expand it later on and refactor as needed. Longer term I want to add testing in, but we&#8217;ll start without for now.</p>



<p>I went for a container project which contains sub projects for the main application, and a static linked library. The library could always be spun out as a dynamic library and moved into its own project. </p>



<h2>Sample Project</h2>



<p>Our project will have the following directory structure:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; gutter: false; title: ; notranslate">
Sample Project
     |
     | -- calcApp
     |
     | -- calcLib
</pre></div>


<p>CMake works by having <code>CMakeLists.txt</code> files in each folder of the project and sub projects. In the top level folder we put a <code>CMakeLists.txt</code> file that is for the project, and it includes the two subdirectories below it. CMake will drill down, find the <code>CMakeLists.txt</code> file in the subdirectories and build elements in those folders.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
cmake_minimum_required(VERSION 3.5)

project(someProject)

add_subdirectory(calcLib)
add_subdirectory(calcApp)
</pre></div>


<p>The first line defines the <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://cmake.org/cmake/help/latest/command/cmake_minimum_required.html" target="_blank">minimum version</a> of CMake required to build this project. The <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://cmake.org/cmake/help/latest/command/project.html" target="_blank">project</a>() definition defines the project name. We then add the two <a href="https://cmake.org/cmake/help/latest/command/add_subdirectory.html" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">subdirectories</a> for our sub-projects.</p>



<h3>calcLib</h3>



<p>Our next step is to implement the <code>calcLib</code> and set up the CMake files for it. We will have a simple <code>Calc</code> class that just has a couple of methods.</p>



<p>C++ often has header files and source files separately, the header defines the interface to a method or class while the source implements it. Our header will go in the include directory of the lib, and goes in a subdirectory so we can make include file names more unique. The following is the content of <code>calcLib/include/calc</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: cpp; title: ; notranslate">
#ifndef CALCLIB_INCLUDE_CALC_CALC_H_
#define CALCLIB_INCLUDE_CALC_CALC_H_

class Calc {
public:
	int add(int a,int b);
	int sub(int a,int b);
};

#endif /* CALCLIB_INCLUDE_CALC_CALC_H_ */
</pre></div>


<p>We can create an implementation of this in the <code>calcLib/src/Calc.cpp</code> file:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: cpp; title: ; notranslate">
#include &quot;calc/Calc.h&quot;

int Calc::add(int a, int b) {
	return a+b;
}

int Calc::sub(int a, int b) {
	return a-b;
}
</pre></div>


<p>We include our header file, and then proceed to complete the implementations of the interface defined in the header file. Note that we prefix our header file with <code>calc</code> from the <code>calc</code> subdirectory in our include directory.</p>



<p>Our last piece for the lib is the <code>calcLib/CMakeLists.txt</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
add_library(calcLib src/Calc.cpp)

message(&quot;CalcLib current source dir = ${CMAKE_CURRENT_SOURCE_DIR}&quot;)

target_include_directories( calcLib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
</pre></div>


<p>Since C++ lets us build executables or libraries we need to tell CMake what we want our target to be. <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://cmake.org/cmake/help/latest/command/add_library.html" target="_blank">add_library</a> is used to define a library target, give it a name, and define the source files for it. In this case, we are creating a library called <code>calcLib</code> and adding our <code>src/Calc.cpp</code> source file. </p>



<p>The <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://cmake.org/cmake/help/latest/command/message.html" target="_blank">message</a> command is used to log messages back to the user. CMake internal or user defined variables can be used inside the string to log them as part of the message.  This isn&#8217;t needed, I just included to show you how to create output.</p>



<p><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://cmake.org/cmake/help/latest/command/target_include_directories.html" target="_blank">target_include_directories</a> is used to define the include directory for this lib. Note that we use the target name <code>calcLib</code> to attach the include directory to the target. Because of the nature of C++ with regards to libraries and linking there are a few options on this command to define the visibility of the includes. We have defined ours as PUBLIC for now.</p>



<h3>calcApp</h3>



<p>Now we have our library all completed, we can work on our main app in the calcApp directory. This is a simple <code>main.cpp</code> class which prints a message and invokes our calculator to show it is all hooked up. </p>



<p><code>calcApp/main.cpp</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;
#include &quot;calc/Calc.h&quot;

int main() {
	Calc calc;
	std::cout &lt;&lt; &quot;Hello World 12+7 = &quot; &lt;&lt; calc.add(12,7) &lt;&lt; &quot;\n&quot;;
}
</pre></div>


<p>Pretty simple stuff. We need to also add a CMakeLists.txt file which will define the executable and pull in our library. </p>



<p><code>calcApp/CMakeLists.txt</code> </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
add_executable(calcApp main.cpp)

target_link_libraries(calcApp calcLib)
</pre></div>


<p><a rel="noreferrer noopener" aria-label="add_executable (opens in a new tab)" href="https://cmake.org/cmake/help/latest/command/add_executable.html" target="_blank">add_executable</a> is like add_library, it lets us define an executable we want to create, gives it a target name and lets us specify the source files to be added to it.</p>



<p><a href="https://cmake.org/cmake/help/latest/command/target_link_libraries.html">target_link_libraries</a> lets us link our library into the executable when it gets built. In this case we are doing a static link and the library will be pulled into the executable.</p>



<h3>Building It All</h3>



<p>That should be everything, and we should be able to build and run our app. You can build the project by opening a command line, going to the project root folder and typing: </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
mkdir build
cd build
cmake ..
make
</pre></div>


<p>That should build the project for you, and you can run the executable from <code>calcApp/calApp</code></p>



<p>That about wraps it up, you can get the source code from my blog post code git repository under <a href="https://github.com/andygibson/blog-post-code/tree/master/c/cmake-basic">cmake-basic</a>. </p>



<p>There are a lot of knobs to play with with regards to building C++ projects, and how they are structured. With Java, while we have the option of adding jars to executables at runtime through the class path, its often the case that we just build a jar containing all the code we need. Similarly, we could bind java libraries at run time, but often choose not to. With C++ here we have a basic outline of a project that should cover simple cases. </p>



<p>Next I&#8217;m going to be looking at incorporating a test framework to give us a real base project to work with.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Procedural Terrain Update</title>
		<link>http://www.andygibson.net/blog/personal/procedural-terrain-update/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Mon, 10 Feb 2020 22:51:38 +0000</pubDate>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Cpp]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2404</guid>

					<description><![CDATA[So I started a series before Christmas on generating and rendering procedural terrain at runtime. Between one thing and another, including ending up in hospital having surgery for appendicitis, I haven&#8217;t taken it any further. As the purpose of doing those articles then was to suit my Christmas mood, with it being nearly Spring, this [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>So I started a series before Christmas on generating and rendering procedural terrain at runtime. Between one thing and another, including ending up in hospital having surgery for appendicitis, I haven&#8217;t taken it any further. As the purpose of doing those articles then was to suit my Christmas mood, with it being nearly Spring, this is no longer the case. I&#8217;ve put the rest of that series on the back burner and am looking at a few other post ideas, particularly in C++.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Procedural Terrain With Java – part 2</title>
		<link>http://www.andygibson.net/blog/programming/procedural-terrain-with-java-part-2/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Fri, 22 Nov 2019 22:33:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JME]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2386</guid>

					<description><![CDATA[So last time we got our Java application up and running with a scene displayed using the JMonkeyEngine (JME) game engine. This time, we&#8217;re going to extend that to generate some procedural terrain. We are going to start with a HeightProvider class that is used to provide us with heights of the terrain at a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>So last time we got our Java application up and running with a scene displayed using the JMonkeyEngine (JME) game engine. This time, we&#8217;re going to extend that to generate some procedural terrain.</p>



<p>We are going to start with a <code>HeightProvider</code> class that is used to provide us with heights of the terrain at a given point. Now, bear in mind we are aiming to ultimately have an infinite terrain to fly over, so we want our <code>HeightProvider</code> to account for that. </p>



<p>In is simplest form, the <code>HeightProvider</code> is an interface that has one method.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public interface HeightProvider {

  public float getHeight(float x, float y);
}
</pre></div>


<p>A quick note here, I am using floats as that is the preferred type for JME, most likely since that is the preferred type of OpenGL.</p>



<p>So for this code, I&#8217;m going to create some little util methods on the interface so we can chain the implementations and create some useful features.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public interface HeightProvider {

  /**
   * Return the height of the map at a given x,y point.
   */
  public float getHeight(float x, float y);

  /**
   * Scale out the x,y co-ords, i.e. spread the map out further
   */
  public default HeightProvider scale(float scale) {
    return (x, y) -&gt; this.getHeight(x * scale, y * scale);
  }

  /**
   * Multiply the height so we get taller points 
   */
  public default HeightProvider mul(float mul) {
    return (x, y) -&gt; this.getHeight(x, y) * mul;
  }

  /**
   * Create a height provider based on the JME noise functions.
   */
  public static HeightProvider noise() {
    return (x, y) -&gt; ImprovedNoise.noise(x, y, 87);
  }
}
</pre></div>


<p>This gives us a <code>HeightProvider</code> instance on which we can call the <code>getHeight()</code> method repeatedly and we should get the same value back. This is essential. We aren&#8217;t just returning random numbers, we are generating some pseudo random numbers, usually based on <a href="https://en.wikipedia.org/wiki/Perlin_noise" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">noise</a>.</p>



<p>JME comes with some classes to help with specifying terrain using height map and terrain classes. You can see more about them <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://wiki.jmonkeyengine.org/jme3/beginner/hello_terrain.html" target="_blank">here.</a> We will use the <code>TerrainQuad</code> class for now to help us get up and running.</p>



<p>We&#8217;re going to add one more method to our <code>HeightProvider</code> to get it to produce an array of float heights for our map. This will allow us to use our <code>HeightProvider</code> to generate he values for the <code>TerrainQuad</code>.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public interface HeightProvider {
...
  public default float&#x5B;] toFloats(float x, float y, int size) {
    final float&#x5B;] heightData = new float&#x5B;size * size];
    for (int ix = 0; ix &lt; size; ix++) {
      for (int iy = 0; iy &lt; size; iy++) {
        heightData&#x5B;(ix * size) + iy] = getHeight(x + ix, y + iy);
      }
    }
    return heightData;
  }
...
}
</pre></div>


<p>We are assuming a square terrain tile is being used. The x and y coordinates that we pass in indicate the start point of the tile. Remember, this terrain could go on for miles. We plug this coordinate into the height provider to give us a height for that point which we store in the array.</p>



<p>Now we have our height provider in place, lets add some code to our main class to use it!</p>



<p>From our first example, we will keep our code to move the camera, add the light, and create the material. We will change the code to create the geometry and we may tweak the position of the camera a bit:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
  private static final int MAP_SIZE = 513;
  private static final int TILE_SIZE = 65;

  @Override
  public void simpleInitApp() {

    // set how fast WASD keys move us over the landscape.
    flyCam.setMoveSpeed(10);

    // move up, to the side and look at the origin
    getCamera().setLocation(new Vector3f(0, 12, 30));
    getCamera().lookAt(Vector3f.ZERO, Vector3f.UNIT_Y);

    // lets put some light in
    final DirectionalLight sun = new DirectionalLight(new Vector3f(0.2f, -0.6f, -0.5f).normalize());
    sun.setColor(ColorRGBA.White);
    rootNode.addLight(sun);

    final Material mat = new Material(assetManager, &quot;Common/MatDefs/Light/Lighting.j3md&quot;);
}
</pre></div>


<p>So far so good, not too much different from before. Since we might have some hills, the camera has been moved up a bit, and pushed back through the screen so when we look at the origin we aren&#8217;t looking straight down. We also set the fly cam speed so we can move through our scene at a fairly fast pace.</p>



<p>Now to add the geometry. We want to create a new <code>TerrainQuad </code> and assign it the float values from our height provider. For now we will keep it simple and not worry about tiling and LOD.  I&#8217;ve added a couple of constants at the top to indicate the tile size and heightmap size we are using. These must be (2^n)+1 values (9,17,33,65,129,257,513) with the tile size usually being less. Again, JME docs on the <code>TerrainQuad</code> can tell you all about that. On to the code!</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
    final HeightProvider provider = HeightProvider.noise();
    final float&#x5B;] data = provider.toFloats(0, 0, MAP_SIZE);
    final TerrainQuad q = new TerrainQuad(&quot;terrain&quot;, TILE_SIZE, MAP_SIZE, data);
</pre></div>


<p>If you run this now, you are probably going to be pretty disappointed. No rolling hills and sweeping valleys, it just looks like the plains of Hoth:</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="640" height="510" src="https://www.andygibson.net/blog/wp-content/uploads/2019/11/hoth-1.png" alt="" class="wp-image-2388" srcset="http://www.andygibson.net/blog/wp-content/uploads/2019/11/hoth-1.png 640w, http://www.andygibson.net/blog/wp-content/uploads/2019/11/hoth-1-300x239.png 300w" sizes="(max-width: 640px) 100vw, 640px" /><figcaption>Hoth&#8230;. In Space</figcaption></figure></div>



<p>So whats going on here, then. Well, 2 things are wrong with this. Our height provider is asked for values on integer steps, coordinates are requested of the form (0,0), (0,1), (0,2)&#8230;.(1,0), (1,1), (1,2).</p>



<p>For this implementation, and I believe every Perlin Noise implementation, at the integer boundaries, the value is always zero. The other problem is that noise returns small values between -1 and 1 which is a  really small height in our landscape.</p>



<p>However, those nice helper functions can fix this for us. We want to take our provider, then scale down the co-ordinates so rather than range from 0-513, they range from 0 a smaller number with interpolations in between. Change the provider constructor to the following:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
final HeightProvider provider = HeightProvider.noise().scale(0.2f).mul(10);
</pre></div>


<p>This creates our noise provider, and then the scale method creates a new one based on that, which scales the values going into it, so if we called this provider with (47,24), those values would get scaled down to (2.35, 1.2) and those values would be passed into the noise function. Since they are not on integer boundaries, the noise function will return a non-zero value. Hurrah! However, this is still a really small value, and while you will see some hills, they will be very small. So, we want to multiply the returned height to create bigger peaks which we can do with the <code>mul</code> method. That returns a provider that takes the value from the previous one and multiplies the value by 10. What do you get now?</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="640" height="510" src="https://www.andygibson.net/blog/wp-content/uploads/2019/11/hills.png" alt="" class="wp-image-2389" srcset="http://www.andygibson.net/blog/wp-content/uploads/2019/11/hills.png 640w, http://www.andygibson.net/blog/wp-content/uploads/2019/11/hills-300x239.png 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure></div>



<p>I&#8217;ll wait here while you fly around for half an hour&#8230;..</p>



<p>You can play around with the <code>scale</code> and <code>mul</code> parameters, keeping them in the same proportion generates a similar landscape, it will just be scaled up or down proportionally. If you decrease just the scale it stretches the map out and the hills look shorter. Increase the <code>mul</code> parameter and the hills will grow taller and shorter. </p>



<p>Also, as you ramp the values up and down, you find you go through your landscape faster or slower. You can change the flyCam speed to fix that. </p>



<p>Note that you only have 513 X 513 quads in this scene, so you can&#8217;t stretch the map out forever as the number of quads in the geometry will decrease and your hills will just end up a sharp triangle. You can always increase the MAP_SIZE, just remember to keep it as multiples of (2^n)+1.</p>



<p>In part 3, we will look at producing a better landscape using  more complex height provider implementation and layered noise.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Procedural Terrain With Java &#8211; part 1</title>
		<link>http://www.andygibson.net/blog/programming/procedural-terrain-with-java-part-1/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Mon, 18 Nov 2019 23:35:13 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JME]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2375</guid>

					<description><![CDATA[Every year, around Christmas time I always get a hankering to write some 3D terrain rendering code. Not so much the actual rendering engine, that part has already been done with 3D APIs such as OpenGL and Direct X. Its more about rendering a 3D terrain generated by code, more specifically pseudo-random numbers, enabling a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Every year, around Christmas time I always get a hankering to write some 3D terrain rendering code. Not so much the actual rendering engine, that part has already been done with 3D APIs such as OpenGL and Direct X. Its more about rendering a 3D terrain generated by code, more specifically pseudo-random numbers, enabling a continuous never ending terrain. </p>



<span id="more-2375"></span>



<p>This year I&#8217;m getting a head start, and to celebrate that, I&#8217;m going to blog it as I go.  I&#8217;m going to be using Java with JMonkeyEngine APIs on top of the LWJGL OpenGL libs. I quite like JMonkeyEngine as it puts more control into your code giving with the power of the Java language. Being Java based means it is flexible enough to use some good design patterns and code structure without too much rigidity and I can unit test my logic too!</p>



<p>So, with that, I&#8217;m going to create a Maven project which will pull in the JMonkeyEngine libs and create a very simple, cube lit by a sun. I&#8217;m going to be using Java 13 and the latest JMonkeyEngine version (3.2.4 -stable). If you&#8217;ve looked at JME before, this probably isn&#8217;t going to be anything earth shattering, but serves as a solid ground for part II.</p>



<p>Start by creating a new simple Maven project and add the following content in the <code>pom.xml</code> file.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
	&lt;properties&gt;
		&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
		&lt;maven.compiler.source&gt;13&lt;/maven.compiler.source&gt;
		&lt;maven.compiler.target&gt;13&lt;/maven.compiler.target&gt;
		&lt;jme-version&gt;3.2.4-stable&lt;/jme-version&gt;
	&lt;/properties&gt;

	&lt;repositories&gt;
		&lt;repository&gt;
			&lt;id&gt;JCenter&lt;/id&gt;
			&lt;url&gt;https://jcenter.bintray.com/&lt;/url&gt;
		&lt;/repository&gt;
	&lt;/repositories&gt;

	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.jmonkeyengine&lt;/groupId&gt;
			&lt;artifactId&gt;jme3-core&lt;/artifactId&gt;
			&lt;version&gt;${jme-version}&lt;/version&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.jmonkeyengine&lt;/groupId&gt;
			&lt;artifactId&gt;jme3-terrain&lt;/artifactId&gt;
			&lt;version&gt;${jme-version}&lt;/version&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.jmonkeyengine&lt;/groupId&gt;
			&lt;artifactId&gt;jme3-plugins&lt;/artifactId&gt;
			&lt;version&gt;${jme-version}&lt;/version&gt;
		&lt;/dependency&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.jmonkeyengine&lt;/groupId&gt;
			&lt;artifactId&gt;jme3-lwjgl&lt;/artifactId&gt;
			&lt;version&gt;${jme-version}&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
				&lt;version&gt;3.8.0&lt;/version&gt;
				&lt;configuration&gt;
					&lt;source&gt;${maven.compiler.source}&lt;/source&gt;
					&lt;target&gt;${maven.compiler.target}&lt;/target&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;
&lt;/project&gt;
</pre></div>


<p>Now at some point, you will have to download the JMonkeyEngine SDK to get the binary libraries to use with JME. For now, we just need one, which is <code>liblwjgl64.so</code>. Your filename may be different depending on the platform and 32/64 bit.  This is the lib for supporting the LWJGL and for now, can go in the root of the project folder, next to the <code>pom.xml</code> file.</p>



<p>Our next step it to write a piece of code which will get us displaying some graphics in a page. We&#8217;ll create a main class which inherited from the <code>SimpleApplication</code> class in the JME library.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import com.jme3.app.SimpleApplication;

public class Main extends SimpleApplication {

  public static void main(final String&#x5B;] args) {
    final Main app = new Main();
    app.start();
  }

  @Override
  public void simpleInitApp() {

  }
}
</pre></div>


<p>Run that and you should get the JMonkeyEngine splash screen where you can pick your settings, and upon clicking OK, you should see a big black screen with some debug information on it:</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="640" height="510" src="https://www.andygibson.net/blog/wp-content/uploads/2019/11/Screenshot-from-2019-11-18-22-48-41.png" alt="" class="wp-image-2378" srcset="http://www.andygibson.net/blog/wp-content/uploads/2019/11/Screenshot-from-2019-11-18-22-48-41.png 640w, http://www.andygibson.net/blog/wp-content/uploads/2019/11/Screenshot-from-2019-11-18-22-48-41-300x239.png 300w" sizes="(max-width: 640px) 100vw, 640px" /><figcaption>My new space game</figcaption></figure></div>



<p>Not much is going on here, just some debug information including our FPS rate. Of course, we haven&#8217;t added anything to the display yet. So we need to add some  light and an object. We&#8217;ll also position the camera from where we are generating the image so we can get a good view. We&#8217;ll do this in the <code>simpleInitApp</code> method that is used to initialise the content.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
  @Override
  public void simpleInitApp() {

    // move up, to the side and look at the origin
    getCamera().setLocation(new Vector3f(-4, 5, 10));
    getCamera().lookAt(Vector3f.ZERO, Vector3f.UNIT_Y);

    // lets put some light in
    final DirectionalLight sun = new DirectionalLight(new Vector3f(0.2f, -0.6f, -0.5f).normalize());
    sun.setColor(ColorRGBA.White);
    rootNode.addLight(sun);

    // create a simple box
    final Box b = new Box(1, 1, 1);
    final Geometry geom = new Geometry(&quot;Box&quot;, b);

    // create a very plain lit material
    final Material mat = new Material(assetManager, &quot;Common/MatDefs/Light/Lighting.j3md&quot;);

    // assign this material to the box geometry.
    geom.setMaterial(mat);

    // add the geometry to the scene and we are good to go
    rootNode.attachChild(geom);
  }

</pre></div>


<p>This article isn&#8217;t meant to be  primer on 3D graphics, or JMonkeyEngine in particular, but this is a simple application that will get you up and running with a simple lit scene in JME with Java.</p>



<p>We move the camera and look at the box so we can see all 3 sides and get an idea of how they are shaded. The directional light has no position so its only influence on shading depends solely on the angle between the box face and the direction of the light that was specified in the constructor. The material we have used is a simple lit material using the default parameters. </p>



<p>If you run this, you will see a simple scene with a lit box that you can use the mouse to look around with and the WASD keys to move around in. </p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="640" height="510" src="https://www.andygibson.net/blog/wp-content/uploads/2019/11/cube.png" alt="" class="wp-image-2381" srcset="http://www.andygibson.net/blog/wp-content/uploads/2019/11/cube.png 640w, http://www.andygibson.net/blog/wp-content/uploads/2019/11/cube-300x239.png 300w" sizes="(max-width: 640px) 100vw, 640px" /><figcaption>A Cube In Space</figcaption></figure></div>



<p>This gets us up and running with JME. Next time we&#8217;ll look at creating a simple terrain using code, in particular the JME noise functions to create terrain.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>New Look Java Magazine</title>
		<link>http://www.andygibson.net/blog/news/new-look-java-magazine/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Thu, 29 Aug 2019 07:30:35 +0000</pubDate>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2365</guid>

					<description><![CDATA[The official Java magazine from Oracle has received a new look in the form of switching from a heavy PDF based production to a more responsive single page HTML publication. This is fantastic news for the many mobile readers from both a data usage and presentation perspective. As per their issue archives page, it seems [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>The official <a href="https://blogs.oracle.com/javamagazine">Java magazine</a> from Oracle has received a new look in the form of switching from a heavy PDF based production to a more  responsive single page HTML publication. This is fantastic news for the many mobile readers from both a data usage and presentation perspective. </p>



<p>As per their <a href="https://blogs.oracle.com/javamagazine/issue-archives">issue archives</a> page, it seems they have converted the last few issues to HTML while other issues are still available as a PDF download.</p>



<p>Historically, magazines have provided an opportunity to expose the reader to new topics which they might not have otherwise found by covering a wide range of articles focused around a central topic. In the past, I&#8217;ve found Java Magazine has provided a casual introduction to a number of new ideas and concepts and a worthy revisitation of old ones. </p>



<p>With its new monthly publishing schedule it&#8217;s certainly one to add to the bookmarks.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Optionals</title>
		<link>http://www.andygibson.net/blog/programming/optionals/</link>
		
		<dc:creator><![CDATA[Andy Gibson]]></dc:creator>
		<pubDate>Tue, 06 Aug 2019 21:10:29 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=2327</guid>

					<description><![CDATA[Article about the semantic benefits of using java Optional values for returning results.]]></description>
										<content:encoded><![CDATA[
<p>I have to confess, I was sceptical when I first read about the new <code>Optional</code> class that was being introduced in Java 8 way back when. Its only over the last few years I have come to really appreciate how it can shape the way we define method signatures and invoke them. This post covers the various ways this simple class can help you write clearer and more robust code.</p>



<span id="more-2327"></span>



<p>When returning a value from a method, you want to return one of three things, either return the actual result, return an unknown (<code>null</code>) value, or throw an exception.<br> The first case is the happy path which most developers code for as it hopefully meets most cases. Returning a null can often be overlooked unless the developer is very conscientious or there is already an expectation that the result is likely to be null. The third option is that an exception can be thrown from the method if it is unable to complete the operation. The problem here is that we have a fairly loose contract with the client and leave it up to the caller to be aware of the different outcomes.</p>



<p>Once we have a value from a method, you typically want to do one of three things when it is null. Use a default value, throw an exception or change program flow to not use it. The following 3 examples show how this is done in a pre-Optional world: </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//Throw Exception
Integer size = calculateSize();
if (size == null) {
  throw new NullPointerException(&quot;Couldn&#039;t calculate size&quot;);
}
//do something with size.


 
//Default Value
Integer size = calculateSize();
if (size == null) {
  size = DEFAULT_SIZE;
}
allocateSpace(size);


//Different code path:
Integer size = calculateSize();
if (size != null) {
  allocateSpace(size);
}

//carry on

</pre></div>


<p>Because we have always been able to deal with null values like this, I wasn&#8217;t blown away by the prospect of the <code>Optional</code> class. However, the problem with the above is that we must always remember to handle a null result and inevitably at some point, someone will end up writing :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Integer size = calculateSize();
allocateSpace(size);
</pre></div>


<p>This will create code that is prone to sporadic unhandled failures. In general we want our code to be robust, easy to use and offer the least surprises. </p>



<p>To avoid repeating this in every invocation, we could roll the logic into our function so <code>calculateSize()</code> will throw an exception or return a default value. However, we might not always know which we want to do since it would depend on the context it was called in. </p>



<h2>Optionals To The Rescue</h2>



<p><code>Optional</code> values allow us to always return an object that acts as a container for the actual value that may or may not be null. We typically create a new <code>Optional</code> using either :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
return Optional.of(result);

or

return Optional.ofNullable(possibleNullValue);
</pre></div>


<p>If the value you return may be <code>null</code>, you should use the latter version otherwise an exception will be thrown if you invoke the first syntax with a <code>null</code> value.</p>



<p><code>Optional</code> values enable us to define the signature of the method to say the outcome could well be null and force the client to deal with it.</p>



<p>We can query the returned <code>Optional</code> value and handle it differently depending on whether there is a value or not. Here are the same above 3 cases implemented as an <code>Optional</code> value returned from <code>calculateSize()</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
//Default Value
Integer size = calculateSize().orElse(DEFAULT_SIZE);
allocateSpace(size);

//Throw Exception
Integer size = calculateSize().orElseThrow(()-&gt;new RuntimeException(&quot;Couldn&#039;t calculate size&quot;));
allocateSpace(size);

//Different code path
calculateSize().ifPresent(s-&gt; allocateSpace(s));

</pre></div>


<p>The real value of the <code>Optional</code> class is the semantics to say that this value could be <code>null</code>, forcing the developer to deal with it and providing convenience for handling <code>null</code> values in a different way.  Granted, just as before, someone could just incorrectly write :</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
Integer size = calculateSize().get();
allocateSpace(size);

</pre></div>


<p>But there are static analysis tools that can detect such code smells where you access an optional without checking it, and if you have proper unit test coverage (such that <code>calculateSize</code> returns an empty <code>Optional</code>) this code should be invoked with an empty optional and an error thrown.</p>



<h3>Improving clarity. </h3>



<p>When we return the actual object, callers of the method don&#8217;t know whether <code>null</code> could be returned or if the method will throw an exception without looking at either the method signature or java doc. When returning an <code>Optional</code>, you can safely assume that the value can be <code>null</code> and code defensively for it either by using one of the above solutions.</p>



<h3>Rules to code by:</h3>



<ul><li>If a value will always be returned then return the actual type.</li><li>If the method could return <code>null</code>, then return an <code>Optional</code> to let the caller know this is the case and force the client to deal with the result.</li><li>Throw an exception, select  default or change the program flow based on the result for the appropriate context of the caller.</li></ul>



<p></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
