Monthly Archives: March 2017

Scala classes/objects/traits a little more in depth

Recap on what a class, object and trait are…

A class is analogous to a C# class which is created on a per instance bases. An object is a singleton, analogous to a static class in C# and a trait can how declarations of functions (without implementations) or include implementations which is analogous to a C# abstract class.

So in summary

ScalaC#
classclass
objectstatic class
traitabstract class

Class

As previously mentioned, a class is a type which we can create an instance of, and cannot have abstract (or non-implemented) functions (see trait for abstract/interface types)

class Rectangle(width: Int, height: Int) {
  def area = width * height
}

and we can extend/derive from this using the extend keyword, giving us

class Square(side: Int) extends Rectangle(side, side) {
}

Object

As previously stated, an object can be viewed as a static class (in C#), giving us

object ShapeFactory {
  def createSquare(side: Int) = 
     new Square(side)
  def createRectangle(width: Int, height: Int) = 
     new Rectangle(width, height)
}

In use, we do not need to use the new keyword (just like C#), so we can use this factory like this

val square = ShapeFactory.createSquare(5)
assert(square.area == 25)

Trait

A trait can be viewed as being analogous to an abstract class. We can have functions with implementations or no implementation so that any class which extends this trait must implement the unimplemented functions. Here’s a trait with a single abstract function (no implementation) named area and an implementation of a function named name

trait Shape {
  def area : Int
  
  def name = "Shape"
}

We cannot create a trait without implementing the area function, but this doesn’t mean we must create a class (as such), we can create what C# might call and anonymous type, for example

val s = new Shape {
   override def area: Int = 20
}

But ofcourse, we can also extend the trait with another trait or a concrete implementation as a class, for example

class Rectangle(width: Int, height: Int) extends Shape {
  def area = width * height
}

Functions, by default, are virtual (as per Java) and so we can override the name function, for example

class Rectangle(width: Int, height: Int) extends Shape{
  def area = width * height

  override def name: String = "Rectangle"
}

If we want to stop a function being overridden we can use the final keyword (again like java). So Shape might be defined as

trait Shape {
  def area : Int

  final def name = "Shape"
}

Trait as an interface

So one thing you might notice is that in C# and Java we have the concept of an interface. Scala doesn’t support a specific interface keyword. So in this way it’s similar to C++ in that we can simply use a trait without any implementations.

For example

trait Shape {
   def area : Int
}

We can extend traits, for example

trait Triangle extends Shape {
  def isRightAngle : Boolean
}

and ofcourse we could have implemented some functions within the extended type. To implement a class from a Triangle we can just write the following

class RightAngleTriangle(adjacent: Int, opposite: Int) extends Triangle {
  override def area: Int = (adjacent * opposite) / 2
  override def isRightAngle: Boolean = true
}

How to create property like functionality in Scala

Scala has a slightly strange syntax for the equivalent of C# properties. Let’s take a look

class Person(private var _name: String) {
  // getter
  def name = _name
  // setter
  def name_=(m: Int): Unit = {
    println("Setter called")
    _name = m
  }
}

// code to call the above
val c = new Person("Scooby Doo")
c.name = "Scrappy Doo"

In the Person constructor we mark the _name as private so it cannot be altered outside of the class and notice it’s marked as a var as its used as the backing field for the name property. The getter name is pretty standard but the name_= is a little stranger.

Note: There can be no space between the _ and =

This is the syntax for a setter, you do not need to use something like c.name_= “Name” it simply translates to c.Name = “Name”.

Learning Scala – day 2

In my first post on learning Scala I mentioned using ScalaTest. I’m going to walk through the steps (using IntelliJ community edition) to get up and running with ScalaTest as it’s a great way to try things out (ofourse you could alternatively use the Scala console).

  • Create a new project
  • Select Scala and SBT
  • Give the project a name, mine’s named Demo
  • If not already selected, select the JDK you want to support as well as the SBT and Scala version, or stick with the defaults if they’re already setup correctly

Upon finishing the new project wizard, you’ll get a standard layout of folders, as follows

src/main/scala
src/test/scala

In the root of the project you’ll get a build.sbt file. This is the Scala build system. If we open it, IntelliJ has supplied the bare minimum

name := "Demo"
version := "1.0"
scalaVersion := "2.12.1"

Before we do anything more let’s go into src/main/scala, right mouse click on the folder and select New Scala class. Give it the name Calculator, here’s the code

class Calculator {
  def add(a: Int, b: Int) = {
    a + b
  }

  def subtract(a: Int, b: Int ) = {
    a - b
  }
}

Now, go back to the build.sbt file and add the following

libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"

When the build.sbt file was changed you’ll see it asking you to Refresh the Project, Enable auto-import or Ignore. I clicked Enable auto-import.

This will then import more Extendal Libraries (if you want to see what was imported, expand the External Libraries in the project view alt+1, if not already displayed)

Now, we could have done this in one step (but I wanted to demonstrate how the external libraries get added to), but now add the following

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test"

further external libraries will get imported if you refresh (or if auto-import is enabled, after a moment). These now include scalatest.

We’re going to let IntelliJ create our initial unit test fixture. To ensure everything is in place, carry out the following steps

  • Press the Project Structure button or File | Project Structure
  • In the Dependency tab or your project (i.e. mine’s demo) check the scalatest project has has been imported or add your preferred test package here
  • Press OK to close the dialog (or if no changes were made then Cancel is ofcourse fine)

Or if you’re happy all is ready then…

  • Load Calculator.scala into the editor
  • On the line of the class either right mouse click and select Goto | Test or the hot keys ctrl+shift+t
  • You should see a Create New Test popup
  • Select this to display a dialog
  • Now select the functions you want to create tests for, then press OK.

You’ll now be placed into the newly added CalculatorTest class and it’ll look like this

import org.scalatest.FunSuite

class CalculatorTest extends FunSuite {

  test("testAdd") {
  }

  test("testSubtract") {
  }
}

From here we can write our test code and further tests.

Like other test frameworks we now have access to assert functions, so for example we can have the testAdd look like this

test("testAdd") {
   val calc = new Calculator
    
    assert(calc.add(1, 2) == 3)
  }

org.scalatest contains a whole bunch of assert functions that we can use in our tests.

ScalaTest is not the only scala based test library

References

Working with Scala Tests
ScalaTest

Learning Scala – day 1

I’ve decided to learn (at least the basics) of Scala. This post will cover the standard programming constructs and features, whilst not intended to be in depth, it will act as an entry into using Scala or a reminder for myself.

Note: I will be writing this post as somebody who comes from a C# background and has also used F#. So, sorry if you’re reading this and thinking “I don’t know what F# would look like” for example.

val and var

A val is immutable whereas a var is not. Hence assuming we have the following

object Calculator {
  def add(a: Int, b: Int): Int = {
      a + b
  }

  def subtract(a: Int, b: Int): Int = {
    a - b
  }
}

The we can assign our val thus

val calc = Calculator

// this line will error
calc = Calculator

whereas our var will allow reassignment, hence

var calc = Calculator

// this line will success
calc = Calculator

Simple enough.

Types

I’m not going to list all the types supported in Scala – ofcourse we have Int, String etc. What I will say though, is like F#, a type may be inferred or we might specify the type where a hint is required

Let’s see how we can use a type

val inferredString = "Hello"
val explcitString : String = "Hello"

We declare a type after the name of the val/var, as per the example above.

There’s an ultimate base type in Scala (a little like object in C#) and this is called Any. According to Unified Type System this Any type is not the same as the java.lang.Object. In Scala we have AnyRef which IS analogous to java.lang.Object whereas AnyVal is the equivalent base of value types. Ofcourse Any is the base of both AnyValue and AnyRef.

Like F#, Scala prefers the idea of a Nothing value than a null but (again like F#) null is also supported.

Scala, ofcourse, supports collections and arrays.

We can declare and array with type expected type or inferred, for example, these two arrays create the same type of array

// explicit
val a = Array[String]("a", "b")
// inferred
val b = Array("a", "b")

To access/alter an array at a given index we again use brackets (), i.e.

val a = Array("a", "b")
// amend "b" to "c"
a(1) = "c"

Return values

When a method returns a value we can use the return function, for example

def result : Int = {
   return(123)
}

or without parenthesis, i.e. return 123 or, like F# the return can also be the last line of the function, i.e.

def result : Int = {
   123
}

and with the type being inferred we can reduce this further to

def result = {
   123
}

Loops

The for loop, using the to function, for example

for(i <- 1 to 3) {
   print(i);
}

// will print
// 123

The for loop, using the until method

for(i <- 1 until 3) {
   print(i);
}

// will print
// 12

to and until are methods, hence we could use the following syntax

for(i <- 1 to 3) {}
for(i <- 1 to.(3)) {}
for(i <- 1.to(3)) {}

each of the above does the same thing, just with different syntax. What each of these methods does is return a Range, for example, in the the following code r is of type Range

val r = 1.to(3)

for(i <- r) {
   print(i)
}

It’s always worth noting the i is a val (hence immutable) type and is created each time through the loop.

Note: So how can “to” and “until” be used without parenthesis? If a method is zero or one arguments, we do not need the parenthesis. Therefore, if we have code like this

object Calculator {
  def inc(a : Int): Int = {
    a + 1
  }
}

// we can do this

val calc = Calculator
val r = calc inc 2

Back to loops, so we have a for loop, we’ve also got while loops so

var i = 0
while(i < 3) {
   print(i)
   i = i + 1
}

as well as do…while

var i = 0
do {
   print(i)
   i = i + 1
} while(i < 3)

like C#/Java we can also break out of a loop, however this keyword is not part of Scala. To use, we need to import the functionality using

import scala.util.control._

var i = 0
while(true) {
   print(i)
   i = i + 1
   if(i == 3)
      Breaks.break
}

Importing functionality/libraries

As you’ve seen with the Breaks.break method, we can import functionality as we do in C# with using and import in Java, like this

import scala.util.control._

The use of the _ is like a saying import everything within the scala.util.control namespace and we’ll then use code like Breaks.break to call the method, but we could also be more explicit and change our code to be like this

import scala.util.control.Breaks.break

// other code
if(i == 3)
   break

Like F# being built atop .NET and therefore allowing us access to a rich framework and eco-system, Scala is built upon Java and hence allows us access to it’s rich set of frameworks etc.

import java.util.Date

def output  = print(new Date() + ":" + msg)

in the above, it’s probably obvious, we’re using the Java Date class, we can import multiple specific classes like this

import java.util.{Date, Locale}

or for all (as already seen)

import java.util._

Classes and Objects

We can define a class as follows

class Report(msg: String) {

  def output = println(msg)
}

By default (i.e. without an scope declaration) classes are public, we could prefix the class thus private class Report to change from the default.

The msg: String is like a constructor (a similar design came up for Primary constructors in C# 6) but we can also create overload for the constructor like this

class Report(msg: String) {

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output = println(msg)
}

We can also define an object like this

object Report {

  def output(msg: String) = println(msg)
}

In scala this is known as a singleton object, I would say similar to a static class in C#. Hence does not have a constructor as we cannot create an instance of Report and we do not use the new keyword to use it, i.e.

val s = Report
s.output("Hi")

It’s also possible to associate an object with a class, for example

class Report(msg: String) {

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output  = Report output(this.msg)
}

object Report {
  def output(msg: String) = println(msg)
}

This pairing of class with an object is known as a companion class and vice versa we can think of the object as the companion object. In the example above, we’ve defined the equivalent of a static method in the object and the class output calls this. Obviously this is a slightly convoluted example, but another use is that the object might include (for example) private fields which are used from the class, like this

class Report(msg: String) {

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output  = print(Report.name + ":" + msg)
}

object Report {
  private def name = "Report"
}

alternatively, we can import the object and remove the need to prefix use of name with Report – like this

class Report(msg: String) {

  import Report._

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output  = print(name + ":" + msg)
}

object Report {
  private def name = "Report"
}

Commenting code

As you’ve seen in some of the examples, scala supports // for single line comments as well as the standard (at least in C style languages) /* */

We can also support scaladoc comments, these use /** */ for example

/**
This is a report
*/
class Report(msg: String) {
}

In Intelli> (for example) selecting the Report when used in our code and pressing ctrl+q will result in a popup which will display the documentation for the class, the text with /** */ will be displayed as documentation.

Whoa, hold on, how about an application

So for all of the above, I’ve talked about the language, for these examples I’ve used ScalaTest but what about an entry point for an application.

Ofcourse we have main and we can create our application object like this

object MyApp {
  def main(args: Array[String]): Unit = {
     println("Hello World")
   }
}

As you’ll recall from the section on classes and objects, this is similar to a singleton class with, what we might view as, a static method.

This requires the args : Array[String]) and must return a void/Unit

Hosting more than one service using CXF and Jetty

This is a logical “next post” to Hosting a CXF SOAP webservice in an existing Jetty instance.

Let’s look at what’s need to host more than one service using CXF from a running instance of Jetty.

Changes to our SOAP Service

We’re going to do this by hosting our original HelloWorld service (from the previous post) with a single line change and alongside it we’ll create a REST service.

So in the AppConfig from the previous post, rename getService to getSoapServer (or whatever you like) and the code should look like this

@Bean @DependsOn( "cxf" )
public Server getSoapServer() {
   JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
   factory.setServiceBean(new HelloWorldImpl());
   factory.setAddress("/soap");
   return factory.create();
}

Apart from the method name change, we’ve added a setAddress call with a relative path. If you recall from the previous post our Jetty server will run on port 9000, i.e. http://localhost:9000 but now our SOAP service will be on http://localhost:9000/soap/HelloWorld?wsdl.

Adding a REST Service

Update the pom.xml with the following, in the properties we’ll add

<json.version>1.1.0-M1</json.version>
<glassfish.version>1.0.4</glassfish.version>

and these dependencies

<dependency>
   <groupId>javax.json</groupId>
   <artifactId>javax.json-api</artifactId>
   <version>${json.version}</version>
</dependency>

<dependency>
   <groupId>org.apache.cxf</groupId>
   <artifactId>cxf-rt-frontend-jaxrs</artifactId>
   <version>${cxf.version}</version>
</dependency>

<dependency>
   <groupId>org.apache.cxf</groupId>
   <artifactId>cxf-rt-rs-extension-providers</artifactId>
   <version>${cxf.version}</version>
</dependency>

<dependency>
   <groupId>org.glassfish</groupId>
   <artifactId>javax.json</artifactId>
   <version>${glassfish.version}</version>
</dependency>

Next we’ll create a simple REST service (I’ll actually duplicate the one from here).

So create a new Java class, mine’s named PeopleService and here’s the code

package com.putridparrot.core;

import javax.json.JsonArray;
import javax.json.Json;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/people")
public class PeopleService {
    @Produces({"application/json"})
    @GET
    public JsonArray getPeople() {
        return Json.createArrayBuilder()
                .add(Json.createObjectBuilder()
                        .add("firstName", "Brian")
                        .add("lastName", "Kernighan "))
                .add(Json.createObjectBuilder()
                        .add("firstName", "Dennis")
                        .add("lastName", "Ritchie "))
                .add(Json.createObjectBuilder()
                        .add("firstName", "Bjarne")
                        .add("lastName", "Stroustrup"))
                .build();
    }
}

within AppConfig, place the following

@Bean @DependsOn( "cxf" )
public Server getRestServer() {
   JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
   factory.setServiceBean(new PeopleService());
   factory.setProvider(new JsrJsonpProvider());
   factory.setAddress("/rest");
   return factory.create();
}

if you run the App.main, you should be able to navigate to http://localhost:9000/soap/HelloWorld?wsdl to get the SOAP service’s wsdl and http://localhost:9000/rest/people to get the results of the PeopleService call.

Just to complete the picture – the PeopleService is given a path to the REST calls. We’re simply returning JSON and so we annotate with the @Produces line. As we’re only support a GET call to this service we annotate @GET. Within the getPeople method we build up a JSON document and that’s all there is to it.

Hosting a CXF SOAP webservice in an existing Jetty instance

In the previous post we looked at creating a web service, exposing SOAP and running in a CXF created instance of Jetty, but what if you already have an application with an existing instance of Jetty running. All you want to do is drop a SOAP capable service into this instance.

Like most of the things I’ve discovered working with CXF (and Spring), it’s not that difficult, once you know how. It’s the finding out “how” that seems more difficult :)

First off, much credit goes to this post Embedded Jetty and Apache CXF: Secure REST Services With Spring Security or more specifically the source code for this post, here.

I’m not interested (at this time) in security, so we’ll ignore that and just concern ourselves with injecting a service into an instance of Jetty created by the application itself (not by CXF).

First up, let’s create our pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.putridparrot.core</groupId>
  <artifactId>cxfws</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>cxfws</name>
  <url>http://maven.apache.org</url>

  <properties>
    <cxf.version>3.0.1</cxf.version>
    <spring.version>4.1.0.RELEASE</spring.version>
    <jetty.version>9.4.2.v20170220</jetty.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxws</artifactId>
      <version>${cxf.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-server</artifactId>
      <version>${jetty.version}</version>
    </dependency>

    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-servlet</artifactId>
      <version>${jetty.version}</version>
    </dependency>
  </dependencies>
</project>

As usual, run mavn install to grab the dependencies.

Now create the usual folder structure for our source, /src/main/java and within this your package folders, i.e. com/putridparrot/core.

We’re going to create four files, two of which we’ve used in previous posts, HelloWorld and HelloWorldImpl, I’ll include those here first just for completeness

HelloWorld.java

package com.putridparrot.core;

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface HelloWorld {
    String reply(@WebParam(name="text") String text);
}

HelloWorldImpl.java

package com.putridparrot.core;

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(endpointInterface = "com.putridparrot.core.HelloWorld", serviceName="HelloWorld")
public class HelloWorldImpl implements HelloWorld {
    public String reply(@WebParam(name = "text") String text) {
        return "Hello " + text;
    }
}

As per the example from the referenced post Embedded Jetty and Apache CXF: Secure REST Services With Spring Security we’re going to create the configuration in code, so create AppConfig.java and place the following in this file

package com.putridparrot.core;

import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

@Configuration
public class AppConfig {
    @Bean( destroyMethod = "shutdown" )
    public SpringBus cxf() {
        return new SpringBus();
    }

    @Bean @DependsOn( "cxf" )
    public Server getServer() {
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        factory.setServiceBean(getService());
        return factory.create();
    }

    @Bean
    public HelloWorldImpl getService() {
        return new HelloWorldImpl();
    }
}

Finally create App.java and place the following inside it

package com.putridparrot.core;

import org.apache.cxf.transport.servlet.CXFServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

public class App {
    public static void main( String[] args ) throws Exception {

        Server server = new Server( 9000 );

        ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath( "/" );
        context.addServlet( servletHolder, "/*" );
        context.addEventListener( new ContextLoaderListener() );

        context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
        context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );

        server.setHandler( context );
        server.start();
        server.join();

        System.in.read();

        System.exit(0);
    }
}

Once this is built, run App.main and you should be able to use your web browser to navigate to http://localhost:9000/HelloWorld?wsdl and see the wsdl definitions for this service.

Great, but what’s it all doing?

Let’s start with the App.main method. The server variable is our Jetty instance. So really the only thing we’re interested here is which port have we assigned the instance to and the server.setHandler method call. This is where we embed our servlet context into the Jetty engine. From what I can understand, this basically allows us a way to intercept calls and pass to our specific servlet, in this case (ultimately) our CXFServlet.

The ServletHolder, as the name suggests, holds the servlet object that we want to use and will be added to the ServletContextHandler. As you can see this is where the bulk of the code is. The setContextPath call sets up the root level path of our context, i.e. changing to context.setContextPath( “/ws” ) means our webservice will now be located off of the ws path, thus http://localhost:9000/ws/HelloWorld?wsdl.

When we call addServlet we can, in essence, extend the root path further, so for example context.addServlet( servletHolder, “/services/*” ) will simply moved the servlet to your root path/services.

We add the spring ContextLoaderListener to the ServletContext and this is where we can setup the parameters required for spring to bring in our webservices etc.

The ContextLoaderListener “Create a new ContextLoaderListener that will create a web application context based on the “contextClass” and “contextConfigLocation” servlet context-params.” we’ll need to supplied the contextClass and contextConfigLocation parameters and that’s exactly what we do in the two setInitParameter lines of code.

The contextClass is going to use the web annotations (hence our webservices are annotated) and the contextConfigLocation will use our AppConfig class (instead of a config. file).

Configuration class

The AppConfig class supplies the configuration for the ContextLoaderListener and is first annotated with the Configuration, although removing this seemed to have no effect. What does have a big effect is the requirement for a bean named cxf – if this is missing you’ll get the following exception


Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘cxf’ is defined

In our case we return a SpringBus

Next up we supply a getServer bean which depends on the cxf bean – this simply means the cxf bean should be created before the getServer bean. This code creates the web service implementation (we could have created a REST implementation using JAXRSServerFactoryBean). Within this code we set the factory bean to use the web service supplied via our getService method (which above is marked as a bean but needn’t be). The we simply return the result of the create method and we’re done.

Writing the Hello World CXF webservice

Before I get into this post, I’m well aware that SOAP hasn’t been the cool kid on the block in terms of web service messaging for a while, but I’m looking at updating an old application’s webservice from a framework which is no longer supported on an older version of Java to a supported framework. So we need to keep everything working using SOAP.

Following these steps, we can get a service up and running in next to no time (ofcourse it took me far longer than “no time” to find out how to do this :)).

  • Create yourself a folder for your project, mine’s cxftest
  • Within your project’s folder create a Maven pom.xml to grab all our required dependencies we’ll require – here’s the pom
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.putridparrot.core</groupId>
      <artifactId>cxftest</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>cxftest</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <cxf.version>2.2.3</cxf.version>
      </properties>
    
      <dependencies>
    
        <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-rt-frontend-jaxws</artifactId>
          <version>${cxf.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-rt-transports-http</artifactId>
          <version>${cxf.version}</version>
        </dependency>
    
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>
    
  • We’re going to do everything from scratch here, but continue with the layout that Maven might generate for us, so off of your project’s folder create src/main/java/putridparrot/core
  • Now add three files, App.java, HelloWorld.java and HelloWorldImpl.java
  • Paste the following code into HelloWorld.java
    package com.putridparrot.core;
    
    import javax.jws.WebParam;
    import javax.jws.WebService;
    
    @WebService
    public interface HelloWorld {
        String reply(@WebParam(name="text") String text);
    }
    
  • Now let’s paste the following into the HelloWorldImpl
    package com.putridparrot.core;
    
    import javax.jws.WebParam;
    import javax.jws.WebService;
    
    @WebService(endpointInterface = "com.putridparrot.core.HelloWorld", serviceName="HelloWorld")
    public class HelloWorldImpl implements HelloWorld {
        public String reply(@WebParam(name = "text") String text) {
            return "Hello " + text;
        }
    }
    
  • Finally paste the following into App.java
    package com.putridparrot.core;
    
    import javax.xml.ws.Endpoint;
    import java.io.IOException;
    
    public class App {
       public static void main( String[] args ) 
          throws IOException, InterruptedException  {
    
       HelloWorldImpl impl = new HelloWorldImpl();
       String address = "http://localhost:9000/HelloWorld";
       Endpoint.publish(address, impl);
    
       // hold the service open
       System.in.read();
    
       System.exit(0);
    }
    

As you’ve probably noticed, we’re not using Spring to create our webservice (the HelloWorldImpl) and thus there’s no spring configuration or the likes. This really is a bare bones implementation to get us started.

Now if you run this you should be able to use the URL http://localhost:9000/HelloWorld?wsdl to grab the definition meta data. Hence from a C# client you can use wsdl.exe or using Visual Studio’s Add Service reference to generate C# classes to use this service.

Alternate code to start the server

In the above we used Endpoint to create the server, the alternative is to use the JaxWsServerFactoryBean, here’s the code

JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
factory.setServiceClass(HelloWorld.class);
factory.setAddress("http://localhost:9000/HelloWorld");
factory.create();

Beanify it

Okay, so we’ve proved the service works at this point, but we really don’t want to hardcode the service like this, so it’s type to turn it into a Spring bean.

First off let’s add to our pom.xml file, you’ll need the following added to the properties element

<spring.version>3.0.5.RELEASE</spring.version>

and then the following dependencies need to be added

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot</artifactId>
      <version>1.5.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>1.5.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.2.2</version>
    </dependency>

and we’re going to use Jetty as the HTTP server, so also add the following dependency

<dependency>
   <groupId>org.apache.cxf</groupId>
   <artifactId>cxf-rt-transports-http-jetty</artifactId>
   <version>${cxf.version}</version>
</dependency>

Obviously you’ll need to run mvn install to get the dependencies updated.

Next we need to create our beans file, within this we’ll actually create a server/endpoint which will be executed. So create a resources folder off of src/main in your project’s folder and add an XML file, mine’s named cxf.xml – within this file we can use one of either of these configurations

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" />

    <jaxws:server id="helloWorld"  serviceClass="com.putridparrot.core.HelloWorld" address="http://localhost:9000/HelloWorld">
        <jaxws:serviceBean>
            <bean class="com.putridparrot.core.HelloWorldImpl"/>
        </jaxws:serviceBean>
    </jaxws:server>
</beans>

or using an Endpoint we can use the following

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" />

 <jaxws:endpoint id="helloWorld" implementor="com.putridparrot.core.HelloWorldImpl"
                    address="http://localhost:9000/HelloWorld">
        <jaxws:features>
            <bean class="org.apache.cxf.feature.LoggingFeature"/>
        </jaxws:features>
    </jaxws:endpoint>
</beans>

You can change the address to address=”/HelloWorld” if you are using the default port etc. Otherwise to remove this will require looking into overriding Jetty’s port etc. (which is outside the scope of this post).

Finally we need to have the main method wire everything up, so within main we should have the following

new ClassPathXmlApplicationContext("cxf.xml");

// stop the server shutting down
System.in.read();
System.exit(0);

How does yield return work in .NET

A while back I had a chat with somebody who seemed very interested in what the IL code for certain C#/.NET language features might look like – whilst it’s something I did have an interest in during the early days of .NET, it’s not something I had looked into since then, so it made me interested to take a look again.

One specific language feature of interest was “what would the IL for yield return look like”.

This is what I found…

Here’s a stupidly simple piece of C# code that we’re going to use. We’ll generate the binary then decompile it and view the IL etc.

public IEnumerable<string> Get()
{
   yield return "A";
}

Using JetBrains dotPeek (ILDASM, Reflector or ILSpy can ofcourse be used to do generate the IL etc.). So the IL created for the above method looks like this

.method public hidebysig instance 
   class [mscorlib]System.Collections.Generic.IEnumerable`1<string> 
      Get() cil managed 
{
   .custom instance void  [mscorlib]System.Runtime.CompilerServices.IteratorStateMachineAttribute::.ctor(class [mscorlib]System.Type) 
   = (
      01 00 1b 54 65 73 74 59 69 65 6c 64 2e 50 72 6f // ...TestYield.Pro
      67 72 61 6d 2b 3c 47 65 74 3e 64 5f 5f 31 00 00 // gram+<Get>d__1..
      )
   // MetadataClassType(TestYield.Program+<Get>d__1)
   .maxstack 8

   IL_0000: ldc.i4.s     -2 // 0xfe
   IL_0002: newobj       instance void TestYield.Program/'<Get>d__1'::.ctor(int32)
   IL_0007: dup          
   IL_0008: ldarg.0      // this
   IL_0009: stfld        class TestYield.Program TestYield.Program/'<Get>d__1'::'<>4__this'
   IL_000e: ret          
} // end of method Program::Get

If we ignore the IteratorStateMachineAttribute and jump straight to the CIL code label IL_0002 it’s probably quite obvious (even if you do not know anything about IL) that this is creating a new instance of some type, which appears to be an inner class (within the Program class) named <Get>d__1. The preceeding ldc.i4.s instruction simply pushes an Int32 value onto the stack, in this instance that’s the value -2.

Note: IteratorStateMachineAttribute expects a Type argument which is the state machine type that’s generated by the compiler.

Now I could display the IL for this new type and we could walk through that, but it’d be much easier viewing some C# equivalent source to get some more readable representation of this. So I got dotPeek to generate the source for this type (from the IL).

First let’s see what changes are made by the compiler to the Get() method we wrote

[IteratorStateMachine(typeof (Program.<Get>d__1))]
public IEnumerable<string> Get()
{
   Program.<Get>d__1 getD1 = new Program.<Get>d__1(-2);
   getD1.<>__this = this;
   return (IEnumerable<string>) getD1;
}

You can now see the newobj in it’s C# form, creating the <Get>d__1 object with a ctor argument of -2 which is assigned as an initial state.

Now let’s look at this lt;Get>d__1 generated code

[CompilerGenerated]
private sealed class <Get>d__1 : 
    IEnumerable<string>, IEnumerable, 
    IEnumerator<string>, IDisposable, 
    IEnumerator
{
   private int <>1__state;
   private string <>2__current;
   private int <>l__initialThreadId;
   public Program <>4__this;

   string IEnumerator<string>.Current
   {
      [DebuggerHidden] get
      {
         return this.<>2__current;
      }
   }

   object IEnumerator.Current
   {
      [DebuggerHidden] get
      {
         return (object) this.<>2__current;
      }
   }

   [DebuggerHidden]
   public <Get>d__1(int <>1__state)
   {
      base..ctor();
      this.<>1__state = param0;
      this.<>l__initialThreadId = Environment.CurrentManagedThreadId;
   }

   [DebuggerHidden]
   void IDisposable.Dispose()
   {
   }

   bool IEnumerator.MoveNext()
   {
      switch (this.<>1__state)
      {
         case 0:
            this.<>1__state = -1;
            this.<>2__current = "A";
            this.<>1__state = 1;
            return true;
          case 1:
            this.<>1__state = -1;
            return false;
          default:
            return false;
      }
   }

   [DebuggerHidden]
   void IEnumerator.Reset()
   {
      throw new NotSupportedException();
   }

   [DebuggerHidden]
   IEnumerator<string> IEnumerable<string>.GetEnumerator()
   {
      Program.<Get>d__1 getD1;
      if (this.<>1__state == -2 && 
          this.<>l__initialThreadId == Environment.CurrentManagedThreadId)
      {
          this.<>1__state = 0;
          getD1 = this;
      }
      else
      {
          getD1 = new Program.<Get>d__1(0);
          getD1.<>4__this = this.<>4__this;
      }
      return (IEnumerator<string>) getD1;
   }

   [DebuggerHidden]
   IEnumerator IEnumerable.GetEnumerator()
   {
      return (IEnumerator) this.System.Collections.Generic.IEnumerable<System.String>.GetEnumerator();
    }
}

As you can see, yield causes the compiler to create enumerable implementation for just that one of code.

Using spring annotations

In a previous post I implemented a simple bean and created the SpringBeans configuration file, but spring can also be used with annotations (attributes to us .NET people).

So let’s take the previous posts code and amend it to use annotations.

  • Remove or comment out the contents of SpringBeans.xml
  • Change the HelloWorld bean to look like this
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class HelloWorld {
        private String name;
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void output() {
            System.out.println("Bean says " + name);
        }
    }
    
  • Change the main method to look like this
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public static void main( String[] args )
    {
       AnnotationConfigApplicationContext context =
          new AnnotationConfigApplicationContext(IocConfiguration.class);
    
       HelloWorld obj = (HelloWorld) context.getBean("helloBean");
       obj.output();
    }
    
  • We still need a way to define how our beans are going to be created. We’re going to do this via a class, which we’ll name IocConfiguration (the name is unimportant), here’s the class
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class IocConfiguration {
    
        @Bean(name = "helloBean")
        public HelloWorld getHelloWorld() {
            HelloWorld o = new HelloWorld();
            o.setName("Hello World");
            return o;
        }
    }
    
  • Now before you can using the @Configuration you’ll need to update the Maven pom.xml to download cglib, so add the following dependency
        <dependency>
          <groupId>cglib</groupId>
          <artifactId>cglib</artifactId>
          <version>2.2.2</version>
        </dependency>
    
  • Run mvn install and now build and run the application.

Creating a simple spring bean

I’m going to create the standard Hello World spring bean. To start with, let’s use Maven to create a simple “default” set of files and from this we’ll start coding our bean.

To start with, run the following Maven command

mvn archetype:generate -DgroupId=com.putridparrot.core -DartifactId=SpringStarter -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Now open the pom.xml and before the dependencies element add the following

<properties>
   <spring.version>3.0.5.RELEASE</spring.version>
</properties>

and within the dependencies element add the following

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
</dependency>

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.version}</version>
</dependency>

Back to the command line, run (from the folder where your pom.xml is located)

mvn install

This command will run the pom.xml and install the spring framework dependencies.

Let’s add a bean

Beans are simply classes which are managed by the spring framework, so let’s create the obligatory HelloWorld bean

package com.putridparrot.core;

public class HelloWorld {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void output() {
        System.out.println("Bean says " + name);
    }
}

Now we’ll need to change the main method generated by Maven to look like this

ApplicationContext context = 
   new ClassPathXmlApplicationContext(
      "SpringBeans.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.output();   

You’ll also need the following imports

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

Spring is an IoC container and it will use (in this instance) a configuration file to define the objects (beans) to be created when an identifier (helloBean) is used.

You’ll notice that we’re telling spring to use the SpringBeans.xml file, which we haven’t yet created. In your main folder create a resources folder and within this add create the file SpringBeans.xml. It should look like this

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="helloBean" class="com.putridparrot.core.HelloWorld">
        <property name="name" value="Hello World" />
    </bean>
</beans>

So in the above we create the identifier helloBean, as stated previously, when we ask for an object with this identifier spring will supply a com.putridparrot.core.HelloWorld instance. We also supply a property value which is injected to the setName method (Java doesn’t support properties like C# so name is translated to setName). Thus, the value Hello Worldoutput method to see whether it all worked.