Simple WS endpoint deployment with JAXWS 2.2 HTTP container abstraction

Recently I’ve been playing with the JAXWS Endpoint.publish(..) API. For those not really involved in WS development, JAXWS includes an API for easily deploying an endpoint in JSE environment while starting a http server just for serving calls to the specified endpoint.

Endpoint endpoint = Endpoint.create(new EndpointBean());
endpoint.publish("http://localhost:8080/jaxws-endpoint1");
//invoke endpoint...
endpoint.stop();

While from a user point of view this API is of few interest on a JavaEE environment, this is still quite interesting in JSE env as well as whenever having the need for a quick/easy testing of basic endpoints.
Moreover, JAXWS 2.2 added a HTTP SPI for establishing / fixing the layer between http server containers and JAXWS stack implementations. This basically allows any jaxws 2.2 compliant implementation to be used on top of any “compatible” http server.
Jitendra Kotamraju (current JSR-224 spec lead) recently provided a bridge project for making Grizzly compatible with the JAXWS 2.2 HTTP SPI. I’ve done the same for the httpserver included in the JDK6 com.sun.net.httpserver.HttpServer. There’s also a similar project for Jetty. So, with the additions of spec 2.2 and the required vendor implementations to comply on that, users can finally do the following with any JAXWS compliant implementation:

import javax.xml.ws.spi.http.HttpContext;
..
HttpContext context = ..;
Endpoint endpoint = Endpoint.create(new EndpointBean());
endpoint.publish(context);
//invoke endpoint
endpoint.stop();

where the context is obtained according to the selected containers, for instance (using my bridge to the JDK6 httpserver):

import com.sun.net.httpserver.HttpServer;
..
HttpServer server = HttpServer.create(new InetSocketAddress(currentPort), 0);
HttpContext context = HttpServerContextFactory.createHttpContext(server, contextPath, path);
server.start();
..
//here comes the endpoint publish and usage as shown above
..
server.stop(0);

Quite handy, isn’t it? ;-)

JBossWS talk in Rome on April 28th

For those being around Rome next week… I’ll be presenting on the JBossWS project for the Rome’s JBoss User Group and Java User Group. More information available (in italian) at http://www.jugroma.it/wiki/jug/space/jug/eventi/Incontro+Aprile+2010 Also take a look at the Community Events calendar on JBoss.org, where every JBoss User Group event is listed.

Let’s hope the volcanic ash cloud goes away in the mean time ;-)

JavaDay in Rome

Just a short note to tell you an interesting event on Java is taking place in Rome next Saturday (Jan, 30th). If you’re around, you might want to attend that: http://roma.javaday.it/javaday2010/

Most of the talks are going to be in Italian, but at least three of them will be in English. The talks are going to be quite technical and should also cover interesting topics like scalability, concurrency, management and tuning.

java2scala #3: Variables and functions

In this third post of our java2scala series we will take a look to variables and functions definition and use.

As usual you can find the full maven/eclipse project on github.

Java class

package it.javalinux.samples.java.post3;

class VariablesAndFunctions {

	private final String inputString;

	public int fooIntVar = 11;
	public final String fooStringVal = "fooString";
	private double privateIntVar = 1.1;
	private final String privateStringVal = "fooString";

	public VariablesAndFunctions(String inputString) {
		//it could compile! and if you uncomment the line tests will fail
		//inputString = inputString + "hasBeenModified";
		this.inputString = inputString;
		//it doesent compile because you have already assigned the final property
		//this.inputString = inputString + "hasBeenModified";
		System.out.println("Created VariablesAndFunctions with inputString=" + inputString);
	}

	public VariablesAndFunctions() {
		this("defaultString");
	}

	public String getInputString() {
		return inputString;
	}

	public String getFooStringVal() {
		return fooStringVal;
	}

// i. You can't re-assign a final variable
//	public void setFooStringVal(String fooStringVal) {
//		this.fooStringVal = fooStringVal;
//	}

	public double getPrivateIntVar() {
		return privateIntVar;
	}

	public void setPrivateIntVar(double privateIntVar) {
		this.privateIntVar = privateIntVar;
	}

	public int getFooIntVar() {
		return fooIntVar;
	}

	public String getPrivateStringVal() {
		return privateStringVal;
	}

	public void setFooIntVar(int fooIntVar) {
		this.fooIntVar = fooIntVar;
	}

}

java Unit Test

package it.javalinux.samples.java.post3;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class VariablesAndFunctionsTest {

    @Test
    public void testAccessToPublicVar() {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	instance.fooIntVar = 12;
    	assertTrue(instance.fooIntVar == 12);
    }

    @Test
    public void  testAccessToPublicVal()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	// It doesn't compile...you can't reassign a final property
    	//instance.fooStringVal = "anotherString"
    	assertTrue(instance.fooStringVal.equals("fooString") );
    	assertFalse(instance.fooStringVal == new String("fooString") );
    }

    @Test
    public void  testAccessToPrivateVar()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	instance.setPrivateIntVar(12);
    	assertTrue(instance.getPrivateIntVar() == 12);
    }

    @Test
    public void  testEmptyConstructor()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	assertTrue(instance.getInputString().equals("defaultString"));
    	assertFalse(instance.getInputString() == new String("defaultString") );
    }

    @Test
    public void  testConstructor()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions("myString");
    	assertTrue(instance.getInputString().equals("myString"));
    	assertFalse(instance.getInputString() == new String("myString") );
    }

}

Scala class

package it.javalinux.samples.scala.post3

class VariablesAndFunctions(val inputString : String) {

    println("Created VariablesAndFunctions with inputString=" + inputString);

    // it doesnt compile
    // inputString = inputString + "hasBeenModified";

	def this() = this("defaultString")

	var fooIntVar : Int = 11
	val fooStringVal = "fooString"
	private var privateIntVar = 1.1
	private val privateStringVal = "fooString"

	def getPrivateVarIntVar() = privateIntVar

	def getPrivateStringVal() = privateStringVal

	def setPrivateVarIntVar(x : Int) {
	  privateIntVar = x
   	}

// It doesn't compile...you can't reassign val
//	def setPrivateStringVal(s : String) {
//	  privateStringVal = s;
//    }

}

Scala Unit Test

package it.javalinux.samples.scala.post3

import org.junit._
import Assert._

@Test
class VariablesAndFunctionsTest {

    @Test
    def testAccessToPublicVar() = {
    	val instance = new VariablesAndFunctions()
    	instance.fooIntVar = 12
    	assertTrue(instance.fooIntVar == 12)
    }

    @Test
    def testAccessToPublicVal() = {
    	val instance = new VariablesAndFunctions()
    	// It doesn't compile...you can't reassign val

    	//instance.fooStringVal = "anotherString"
    	assertTrue(instance.fooStringVal == new String("fooString") )
        assertFalse(instance.fooStringVal eq new String("fooString") )
    }

    @Test
    def testAccessToPrivateVar() = {
    	val instance = new VariablesAndFunctions()
    	instance.setPrivateVarIntVar(12)
    	assertTrue(instance.getPrivateVarIntVar == 12)
    }

    @Test
    def testEmptyConstructor() = {
    	val instance = new VariablesAndFunctions()
    	assertTrue(instance.inputString == new String("defaultString") )
        assertFalse(instance.inputString eq new String("defaultString") )
    }

    @Test
    def testConstructor() = {
    	val instance = new VariablesAndFunctions("myString")
    	assertTrue(instance.inputString == new String("myString") )
        assertFalse(instance.inputString eq new String("myString") )
    }

}

Ok, let me rapidly focus on some interesting things we can remark in previously pasted code (of course feel free to ask if I’ve missed to remark something that you’d like more explanations):

  • public is the default access modifier…conciseness one more time. Scala have 3 different access public (default), private and protected. While plublic and private are the same of java, protected is a bit more restrictive than java one: protected member can be accessed only by subclasses of the class in which they are defined; in java you can access protected memeber also by classes defined in the same package. In scala you can achieve this effect using scoped protection. I will explain that in further post: for the moment just take in mund that you can specify private[X] or protected[X] member meaning they are private or protected “up to” X where X could be an enclosing package or class.
  • scala has 2 different keyword to define mutable (var) and immutable variable. Immutable variable guarantee immutable state at compile time.
  • default constructor is defined implicitly in class definition:
    • every code put in the class except variables and methods definitions are considered part of the default constructor. In our case the println instruction for debug purpose.
    • every val defined into calss definition parenthesis act as parameter for the default constructor. It’s matter of facts that the inputString parameter is defined as val prevent any kind of modification. Of course you can do the same in java declaring the input parameter as final, but it’s quite less usual.
  • normally in scala public variables are accessed using variables names instead of odd getter and setter methods. BTW there is an annotation in scala to build getter and setter methods runtime. It is useful when you need java bean compatible objects written in scala.
  • a method or function is defined using keyword def
  • functions are methods that returns value. Normally defined using an = symbol after method name. Normally return keyword is not required and its use isn’t suggested, the last expression evaluated in the method is the returned one. Try to think functions as complex expression evaluation. Normally you don’t need to specify the type of returned value in method definition since scala will infer it for you. We will see type inference in one of next posts. For now just keep in mind that COMPILER will STATICALLY infer type for you.
  • The same STATIC inference of type is used to infer variable type when it isn’t specified. Try to play a little with my code to get idea about type inference of scala. It’s AMAZING.
  • methods without = symbol doesn’t return value. Formally they return an instance of Unit. Unit is the type of scala like void for java.
  • Don’t miss the different behaviour of == on object between scala and java. They are used in unit tests. Scala uses == to compare the content of objects, while it have eq operator to compare object references.

Ok that’s all for the moment, but as said feel free to play with my code and/or ask here any further explanations.

In next post of the series we will take a first look at scala’s type inference in some more detail. As said it’s absolutely AMAZING…stay tuned

java2scala #2: Hello world

The first java2scala samples we are going to discuss is generated by creating project from maven archetype.
Let me remember you that you need an environment with:

I’ve used m2eclipse plugin and created the two submodules using maven-archetype-quickstart (for java module) and scala-archetype-simple (for scala).

Let’s start with code samples (of course all code is available on our github project):

Java class

package it.javalinux.samples.java;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

Java unit test

package it.javalinux.samples.java;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        assertTrue( true );
    }
}

Scala class

package it.javalinux.samples.scala

/**
 * Hello world!
 *
 */
object App extends Application {
  println( "Hello World!" )
}

Scala Unit Test

package it.javalinux.samples.scala

import org.junit._
import Assert._

@Test
class AppTest {

    @Test
    def testOK() = assertTrue(true)

//    @Test
//    def testKO() = assertTrue(false)

}

Scala BDD specs

package it.javalinux.samples.scala

import org.specs._
import org.specs.runner.{ConsoleRunner, JUnit4}

class MySpecTest extends JUnit4(MySpec)
//class MySpecSuite extends ScalaTestSuite(MySpec)
object MySpecRunner extends ConsoleRunner(MySpec)

object MySpec extends Specification {
  "This wonderful system" should {
    "save the world" in {
      val list = Nil
      list must beEmpty
    }
  }
}

My Comments
It have been your first taste of scala. How do you feel with it?

Of course, since it is your first piece of scala code in this samples you have to note a lot of things. Don’t try to get all aspects right now, I promise I’ll explain you each of them in great detail in next future:

  • Scala support two keyword class and object. The first one is the same than in scala, while the object is the keyword to define singleton object. Singleton object is the way scala define “static” methods in a pure object oriented style…don’t ask me to explain in this very first sample singleton object and/or companion object…we will explain their usefulness very sonn, just be a little patience and think it as classes with all static methods. Let me remark they are much more than this, but we will focus on them later in our series.
  • Scala method definition syntax. The equals after a method name suggest that a method is function returning a value, while methods without equals symbol, or declaring Unit as return type, are procedure defined only for their side effects.
  • Scala val keyword. Scala support two kind of variable definition. val keyword define an immutable variable (like final in java) while var define a mutable variable. Please keep in mind using of val is encouraged and very often used to develop with a functional style.
  • Scala conciseness: The App class is more concise in scala, and AppTest is much more concise than Java one. Conciseness can hurt you at a very first stage, you can feel concise code less readable in some cases. But it is really an advantage: less code = less error, and a good code style can help you to keep your code readable even if concise.
  • Scala doesn’t need main() method to make a class executable. You just need to extends Application trait. WTF is a trait? We will have a lot of time to explain it better with some more useful samples. For now just think a trait as an interface with some methods implementation.
  • Underscore char ( _ ) is used in imports instead of star ( * ) as wild card. Moreover Scala support also imports of classes sets in same package using {firstClass,SecondClass} notation (have a look of that on MySpecTest).
  • The scala maven artifact create also a BDD spec. It’s because BDD is supported and suggested by the scala community. I’m not going to introduce you to BDD specs here, at least not today. Just keep in mind BDD is quite used in scala community.

Ok, it has been just your first taste of Scala, I’ve already said too much and put too much things in our plate. In our next post we will take a look to some very basic language’s feature like how to define class, variables, and methods/procedures.

Of course all code is available on our github project

Next post is coming in few days (probably during next week end) and it will be focus on basic variables and methods definition.

Stay tuned.