Service first using JAX-WS

There are two ways for developing services using JAX-WS, service first, and contract first. Service first means you would typically write the implementation first and generate the WSDL afterwards, whereas contract first you would define the WSDL first, then write the implementation afterwards. There are pros and cons for each approach, but I won’t dwell on those now.

There are 2 parts to a JAX-WS service, the Service Endpoint Interface (SEI) and the Service Implementation Bean (SIB). The SEI is an interface where you abstractly declare the methods (or operations) that your service will provide, along with the inputs and outputs. The SIB is a concrete implementation of the SEI, where you actually implement the code for the SEI. Let me show you a basic example

SEI

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface TeamService {

    @WebMethod
    public String getTeam();
}

SIB

import javax.jws.WebService;

@WebService(endpointInterface = "com.jameselsey.webservices.basicimplementationfirst.service.TeamService")
public class TeamServiceImpl implements TeamService{

    @Override
    public String getTeam(){
        return "Geelong Cats";
    }
}

That is pretty much it, now we just need to deploy the service. Lets avoid using a servlet container for now, as it complicates this example somewhat, we can run the service by implementing the following and taking advantage of the publish method on Endpoint.

import com.jameselsey.webservices.service.sib.TeamServiceImpl;
import javax.xml.ws.Endpoint;

public class Runner {

    public static void main(String[] args) {
        String address = "http://localhost:9876/footy";
        Endpoint.publish(address, new TeamServiceImpl());

        System.out.println("Server up and running on " + address);
    }
}

If you then open http://localhost:9876/footy on your browser you’ll see a page listing the services and their WSDLs. The generated WSDL should look something like this.

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service.basicimplementationfirst.webservices.jameselsey.com/" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://service.basicimplementationfirst.webservices.jameselsey.com/" name="TeamServiceImplService">
   <types />
   <message name="getTeam" />
   <message name="getTeamResponse">
      <part name="return" type="xsd:string" />
   </message>
   <portType name="TeamService">
      <operation name="getTeam">
         <input wsam:Action="http://service.basicimplementationfirst.webservices.jameselsey.com/TeamService/getTeamRequest" message="tns:getTeam" />
         <output wsam:Action="http://service.basicimplementationfirst.webservices.jameselsey.com/TeamService/getTeamResponse" message="tns:getTeamResponse" />
      </operation>
   </portType>
   <binding name="TeamServiceImplPortBinding" type="tns:TeamService">
      <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc" />
      <operation name="getTeam">
         <soap:operation soapAction="" />
         <input>
            <soap:body use="literal" namespace="http://service.basicimplementationfirst.webservices.jameselsey.com/" />
         </input>
         <output>
            <soap:body use="literal" namespace="http://service.basicimplementationfirst.webservices.jameselsey.com/" />
         </output>
      </operation>
   </binding>
   <service name="TeamServiceImplService">
      <port name="TeamServiceImplPort" binding="tns:TeamServiceImplPortBinding">
         <soap:address location="http://localhost:9876/footy" />
      </port>
   </service>
</definitions>

The important parts in the WSDL that I should mention are:

Port
The port section describes the operations that the service exposes, you can think of this a little bit like a Java interface, where it declares the inputs and outputs abstractly, but mentions nothing about the actual implementation. You will notice that the operations match onto the methods marked as @WebMethod. Notice that the name on the port matches the interface and not the implementation.
Binding
The binding section is where you mention implementation details for an implementation of the interface (port), such as transport, style, and usages. Transport is typically http (although smtp can be used), style matches onto the SOAPBinding annotation that we set. The default style is document however I’ve overridden this to be rpc as it makes the examples easier to follow as its less complex.
Service
The service section maps interfaces onto implementations, or in WSDL terms, it lists the ports and their bindings. In the above example it mentions that there is an implementation of TeamServiceImplPort as described in TeamServiceImplPortBinding, available on http://localhost:9876/footy.

You can actually see this working, by creating a project from the WSDL using SOAPUI, it will generate the following request for you

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sei="http://sei.basicimplementationfirst.webservices.jameselsey.com/" xmlns:sib="http://sib.service.webservices.jameselsey.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <sei:getTeam/>
   </soapenv:Body>
</soapenv:Envelope>

As you can see the body contains a tag which is requesting the getTeam port, ultimately bound onto the getTeam Java interface method, implemented to return a pre defined string. If you execute the request, you’ll get the following response

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:getTeamResponse xmlns:ns2="http://sei.basicimplementationfirst.webservices.jameselsey.com/">
         <return>Geelong Cats</return>
      </ns2:getTeamResponse>
   </S:Body>
</S:Envelope>

Summary
This was a quick brain dump of a simple JAX-WS service (I’m currently studying for the Oracle web services certification, trying to write my notes up). I’ve covered how to implement a SEI/SIB, how to publish a service, covered in brief the elements of the WSDL we’re interested in, and showed how the service can be invoked. Please check back soon as I’ll continue this example and post more of my study notes.

Grails based survey system, the android app

Some time back I wrote an article describing the roosearch system I developed using grails. This is the second part, the android client, please checkout the previous article otherwise this might not make much sense!

After completing the grails component, I had a RESTful API available to me, and I just needed to build an app that could consume those services.

Customer lookup and QR codes

The app needs to be simple and quick to use, one of the things I remember from a UX discussion at DroidCon UK is “Don’t annoy your users, they control your app ratings and your income!”. In order to lookup the surveys quickly, I’ve added the ability to scan QR codes. Actually I didn’t have to do a great deal as there is already an app called ZXing by Google that scans QR codes, so I just needed to make Roosearch delegate to ZXing and handle the result.

Of course, we don’t want to exclude users that don’t have ZXing, or even a camera on their device, so I’ve also provided a text field where they can enter the customer Id manually if required.

When the user clicks on the “scan barcode” button, I first check if ZXing is installed using the following

    public void scanBarCode(View v) {
        final boolean scanAvailable = isIntentAvailable(this,
                "com.google.zxing.client.android.SCAN");
        if (!scanAvailable){
            Toast.makeText(this, "You need to install the ZXing barcode app to use this feature", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }

If the user does have ZXing installed on their device, and choose to use it, we can get the result back from the bar code scan using:

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                performRooLookup(contents);
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }

    private void performRooLookup(String rooId) {
        if (StringUtils.isBlank(rooId)) {
            Toast.makeText(this, "Please enter a valid customer id", Toast.LENGTH_SHORT).show();
            return;
        }

        Integer customerId;
        try {
            customerId = Integer.parseInt(rooId);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "Customer id needs to be numeric", Toast.LENGTH_SHORT).show();
            return;
        }
        new FindRooTask(this, new FindRooTaskCompleteListener()).execute(customerId);
    }

I then have the following buried in a service call, invoked by an AsyncTask, which handles finding Customer details:

    public Customer getCustomerDetails(int customerId) {

        try {
            final String url = "http://roosearchdev.jameselsey.cloudbees.net/api/customer/{query}";

            HttpHeaders requestHeaders = new HttpHeaders();

            // Create a new RestTemplate instance
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

            // Perform the HTTP GET request
            ResponseEntity<Customer> response = restTemplate.exchange(url, HttpMethod.GET,
                    new HttpEntity<Object>(requestHeaders), Customer.class, customerId);

            return response.getBody();
        } catch (Exception e) {
            System.out.println("Oops, got an error retrieving from server.. + e");
        }
         return null;
    }

A Customer looks like this:

public class Customer implements Parcelable {

    @JsonProperty("company_name")
    private String companyName;
    private String twitter;
    private String facebook;
    private List<SurveySummary> surveys = new ArrayList<SurveySummary>();
    //Accessors omitted
}

The SurveySummary just has a title and Id. The reason for just returning summaries is because a customer may have many surveys, and there is no need to obtain them all, we just obtain the title to display to the user, if selected, we’ll retrieve the survey by its id.

To recap, here are 2 screenshots that show the above; the landing screen, and then the customer display screen

Landing screen for Roosearch, where the user can enter a customer Id or scan a QR code

Landing screen for Roosearch, where the user can enter a customer Id or scan a QR code

Customer screen, display social media links, name, photo, and list of surveys that the customer has

Customer screen, display social media links, name, photo, and list of surveys that the customer has

 

The survey engine

This is where the magic happens. I have a single activity and single view that handles presenting the survey to the user. As the surveys can change number of questions, and number of responses, I needed a way of dynamically traversing the survey object and allowing user to move between the questions whilst retaining state of what they have selected so far.

I’ve created the following method that will redraw the layout for a given question id:

    public void drawQuestionOnScreen(int id) {
        TextView question = (TextView) findViewById(R.id.question);
        question.setText(s.getQuestion(id - 1).getText());   // subtract 1 as lists are indexed from 0

        LinearLayout linLay = (LinearLayout) findViewById(R.id.answers);
        linLay.removeAllViews();
        RadioGroup rg = new RadioGroup(this);
        rg.setId(1);
        for (int aIndex = 0; aIndex < s.getQuestion(id - 1).getResponses().size(); aIndex++) {
            Answer a = s.getQuestion(id - 1).getAvailableOption(aIndex);
            RadioButton button = new RadioButton(this);
            button.setText(a.getText());
            button.setTextColor(R.color.dark_text_color);
            button.setId(aIndex);
            rg.addView(button);
        }
        linLay.addView(rg);

        TextView status = (TextView) findViewById(R.id.status);
        status.setText(format("%d of %d", id, s.getQuestionCount()));
    }

As you can see, it will retrieve the question by Id, then iterate over the responses and generate RadioButtons. Moving to the next question is reasonably easy, firstly I work out if an option has been selected, and prevent moving on if not. After that, I mark the selected response in the survey object, and then work out if there is another question in the sequence to display, if not we can progress to the finish.

One of the questions in the given survey

One of the questions in the given survey

    public void next(View v) {
        RadioGroup rg = (RadioGroup) findViewById(1);

        int selectedRadioId = rg.getCheckedRadioButtonId();
        if(selectedRadioId == -1){
            Toast.makeText(this, "Please select a response", Toast.LENGTH_SHORT).show();
            return;
        }

        s.getQuestion(questionIndex - 1).getResponses().get(selectedRadioId).setSelected(true);
        // work out if there is another question, then move to it
        if (s.getQuestionCount() > 1 && questionIndex < s.getQuestionCount()) {
            questionIndex++;
            drawQuestionOnScreen(questionIndex);
        } else {
            // if there are no other questions, show dialog saying submit or not
            Toast.makeText(this, "Reached the end of the survey", Toast.LENGTH_SHORT).show();
            // HERE we should process the entire survey, crunch data and post off (maybe async)

            Intent i = new Intent(this, SurveyComplete.class);
            i.putExtra("com.roosearch.domain.Survey", s);
            startActivity(i);
        }
    }

A similar approach is needed for moving back to previous questions, determine if there is a previous question to move to then redraw the screen, like so:

    public void previous(View v) {
        // work out if there is a previous question, and if so move to it
        if (s.getQuestionCount() > 1 && questionIndex > 1) {
            questionIndex--;
            drawQuestionOnScreen(questionIndex);
        } else {
            //if there are no other questions, move back to home screen, finish() this and scrap any progress
            finish();
        }
    }

Once the user completes all questions, the SurveyComplete activity is invoked.

Completing a survey

When the user has completed all questions, the survey object is passed into the SurveyComplete activity, which handles sending the responses back to the grails web application.

@Override
    protected void onResume()
    {
        super.onResume();
        TextView tv = (TextView) findViewById(R.id.completeMessage);
        tv.setText("Thank you for taking the time to complete the survey");
        tv.setTextColor(R.color.dark_text_color);

        Survey s = getIntent().getExtras().getParcelable("com.roosearch.domain.Survey");

        if (s != null)
        {
            StringBuffer sb = new StringBuffer();
            sb.append("\n" + s.getTitle() + "\n");
            for (Question q : s.getQuestions())
            {
                sb.append("\nQ: " + q.getText());
                sb.append("\nA: " + q.getSelectedAnswer() + "\n");
            }
            tv.append("\n\n" + sb.toString());
        }

        new SurveyUploadTask(this, new SurveyUploadTaskCompleteListener()).execute(s);
    }

    public class SurveyUploadTaskCompleteListener implements AsyncTaskCompleteListener<Void> {
        @Override
        public void onTaskComplete(Void voidz) {
            Toast.makeText(SurveyComplete.this, "Survey uploaded", Toast.LENGTH_SHORT).show();
        }
    }

The activity uses an AsyncTask to post the data back to the grails API controller, and displays a toast when successful.

Survey completed, results uploaded, and summary presented to user

Survey completed, results uploaded, and summary presented to user

 

Wrapping it up

Overall quite a simple app, I spent probably around 2 or 3 weekends putting together, most of that time was spent getting to grips with some automated testing for android. The code is admittedly a little rough around the edges, but I was aiming for an MVP (most viable product) to get working, feel free to contribute or suggest improvements!

I chose to use maven, but would use gradle if I were to pick this up again. Be sure to check out the code on github and try running it against Roosearch web, it does work!

Click here for the source code on Github

BrickPi Lego robot takes its first steps!

A little while back I wrote a post about creating a python script to control a brickpi robot, now that I actually have the brickpi components, motors and cables and have actually tried it out, I’ve made a few improvements to that script to make it work.

Installing Raspbian

Firstly, I had to revisit the raspbian installation. With the brickpi bundle I bought from Dexter Industries, it came with a pre-installed raspbian SD card. I’m not sure what was wrong, but I wasn’t able to boot into it, there were startup errors regarding /etc/init.d. A quick Google didn’t help, so I decided to flash a new SD card with a more recent version of raspbian.

It’s important to note that the stock raspbian image won’t automatically work with the brickpi, as some modifications are required in order to control I/O for the motors. You can make these modifications yourself as there are instructions on the brickpi website, but it’s far easier to just download the pre-modified raspbian from dexter industries.

This was quite simple, on a mac you can erase and format an SD card using Disk Utility, after that, use these commands to create the SD card image:

diskutil list
diskutil unmountdisk /dev/disk1
dd if=2013.07.27_BrickPi.img of=/dev/disk1 bs=2m

diskutil list will show you the drives attached, in my case the SD card was disk1 but it may vary for you. It takes around 10 minutes to flash the SD card so go make a brew.

Configuring WiFi

Setting up wifi on the pi is pretty easy, I have a USB wifi adapter, so it was just a case of configuring a wireless interface, which can be done by adding the following to /etc/network/interfaces

sudo nano /etc/network/interfaces
add
iface wlan0 inet dhcp
wpa-ssid "NETWORK_ID_HERE"
wpa-psk "NETWORK_PASSWORD_HERE"

Then do a sudo reboot

Expanding the SD card

In order to expand the root partition and make use of the entire SD card, run the following command and follow the menus to expand SD card

sudo raspi-config

Then do a sudo reboot

Setting up the brickpi dependencies

SSH onto the pi and run the following

mkdir brickpi
cd brickpi/
git clone https://github.com/DexterInd/BrickPi_Python.git
cd BrickPi_Python
sudo apt-get install python-setuptools
sudo python setup.py install

This will clone the BrickPi python repository (which contains a load of examples), install python-setuptools and install the brickpi module, so you can import Brickpi globally in your python scripts.

Controlling the robot

After testing out the brickpi examples, it was quite clear that I’d need to modify my original python script. I needed 2 threads.

  • Thread 1 would continually update the motors every 200ms, otherwise the motors would turn briefly and then remain still.
  • Thread 2 would process incoming commands and set the motor speeds.

Other than the threading code, the script is quite easy to follow

from BrickPi import *   #import BrickPi.py file to use BrickPi operations
import threading
import socket
import select
import Queue
from threading import Thread
import sys

BrickPiSetup()  # setup the serial port for communication
BrickPi.MotorEnable[PORT_A] = 1 #Enable the Motor A
BrickPi.MotorEnable[PORT_D] = 1 #Enable the Motor D
BrickPiSetupSensors()   #Send the properties of sensors to BrickPi

running = True

#This thread is used for keeping the motor running while the main thread waits for user input
class BrickPiThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        while running:
            BrickPiUpdateValues()       # Ask BrickPi to update values for sensors/motors
            time.sleep(.2)              # sleep for 200 ms

brickPiThread = BrickPiThread(1, "BrickPiThread", 1)                #Setup and start the thread
brickPiThread.setDaemon(True)
brickPiThread.start()

class ProcessCommandThread(Thread):
    def __init__(self):
        super(ProcessCommandThread, self).__init__()
        self.running = True
        self.q = Queue.Queue()

    def add(self, data):
        self.q.put(data)

    def stop(self):
        self.running = False

    def run(self):
        q = self.q
        while self.running:
            try:
                # block for 1 second only:
                value = q.get(block=True, timeout=1)
                process(value)
            except Queue.Empty:
                sys.stdout.write('.')
                sys.stdout.flush()
        if not q.empty():
            print "Elements left in the queue:"
            while not q.empty():
                print q.get()

commandThread = ProcessCommandThread()
commandThread.start()

def process(value):
    print "Processing [{v}]".format(v=value)

    # Left side
    if value == 'L-FORWARD-Start':
        print "L-FORWARD-Start"
        BrickPi.MotorSpeed[PORT_A] = 200
    elif value == 'L-FORWARD-Stop':
        print "L-FORWARD-Stop"
        BrickPi.MotorSpeed[PORT_A] = 0
    elif value == 'L-BACK-Start':
        print "L-BACK-Start"
        BrickPi.MotorSpeed[PORT_A] = -200
    elif value == 'L-BACK-Stop':
        print "L-BACK-Stop"
        BrickPi.MotorSpeed[PORT_A] = 0
    # Right side
    if value == 'R-FORWARD-Start':
        print "R-FORWARD-Start"
        BrickPi.MotorSpeed[PORT_D] = 200
    elif value == 'R-FORWARD-Stop':
        print "R-FORWARD-Stop"
        BrickPi.MotorSpeed[PORT_D] = 0
    elif value == 'R-BACK-Start':
        print "R-BACK-Start"
        BrickPi.MotorSpeed[PORT_D] = -200
    elif value == 'R-BACK-Stop':
        print "R-BACK-Stop"
        BrickPi.MotorSpeed[PORT_D] = 0

def main():
    s = socket.socket()
    #host = socket.gethostname()
    host = "192.168.0.10"
    port = 3033
    s.bind((host, port))

    print "Server listening on port {p}...".format(p=port)

    s.listen(5)                 # Now wait for client connection.

    while True:
        try:
            client, addr = s.accept()
            ready = select.select([client, ], [], [], 2)
            if ready[0]:
                data = client.recv(4096)
                commandThread.add(data)
        except KeyboardInterrupt:
            print
            print "Stopping server."
            break
        except socket.error, msg:
            print "Socket error %s" % msg
            break

    cleanup()

def cleanup():
    commandThread.stop()
    commandThread.join()

if __name__ == "__main__":
    main()

Paste that into server.py then run the following:

sudo python server.py

You should see some output in the terminal as it’ll print out any incoming commands. Then its up to you to connect onto that socket with a client of your choice. I’m using an android app (which I’ve detailed here), but you could use something as simple as the following Java client

import java.io.*;
import java.net.Socket;

public class Runner {

    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("raspberrypi", 3033);

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

        osw.write("L-FORWARD-Stop");
        osw.flush();
    }
}

Resources

Any thoughts / suggestions? Please comment below!

Why all Java devs should at least consider Groovy and Spock for testing

As a developer, testing is very important. Some developers have the mindset of “Meh, I write code, testing is a QAs job”, which is pretty poor. It’s much better for the developer to be test driving their code, generally if adopted well it produces better quality code, and of course the sooner issues are caught the cheaper they are to address.

Most Java developers who are following TDD probably use mockito or powermock alongside JUnit. I’ve never been much of a fan of those combinations as I believe they involve far too much boilerplate code, and test code often becomes more verbose and harder to maintain than the actual production code itself.

After being introduced to Spock, and testing using Groovy last year, I’m absolutely sold on it and have subsequently used it on several other projects.

For the purpose of this post, I’ll base it around a service class that does some things with a domain object, via a data access layer, which is something most enterprise developers can relate to.

Heres the domain class:

public class User {

    private int id;
    private String name;
    private int age;

    // Accessors omitted
}

Heres the DAO interface:

public interface UserDao {

    public User get(int id);

}

And finally the service:

public class UserService {

    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User findUser(int id){
        return null;
    }
}

Nothing too complex to mention here. The class that we’re going to put under test is the service. You can see that the service is dependant on a UserDao, which is passed into the constructor. This is a good design practice because you’re stating that in order to have a UserService, it must be constructed with a UserDao. This also becomes useful later when using dependency injection frameworks like Spring so you can mark them both as Components and Autowire the constructor arguments in, but alas.

Lets go ahead and create a test class for the service (command+shift+t if using IntelliJ on a mac).

class UserServiceTest extends Specification {

    UserService service
    UserDao dao = Mock(UserDao)

    def setup(){
        service = new UserService(dao)
    }

    def "it gets a user by id"(){
        given:
        def id = 1

        when:
        def result = service.findUser(id)

        then:
        1 * dao.get(id) >> new User(id:id, name:"James", age:27)
        result.id == 1
        result.name == "James"
        result.age == 27
    }
}

Here we go, right in at the deep end, let me explain what is going on here. Firstly, we’re using groovy, so although it looks like Java (I suppose it is in some respects as it compiles down to Java bytecode anyway) the syntax is a bit lighter, such as no semi-colons to terminate statements, no need for public accessor as everything is public by default, Strings for method names. If you want to learn more about groovy, check out their documentation here.

As you can see, the test class extends from spock.lang.Specification, this is a Spock base class and allows us to use the given, when and then blocks in our test.

You’ll see the subject of the test then, the service. I prefer to define this as a field and assign it in the setup, but others prefer to instantiate it in the given block of each test, I suppose this is really just a personal preference.

Creating mocks with Spock is easy, just use Mock(Class). I then pass the mocked DAO dependency into the userService in the setup method. Setup runs before each test is executed( likewise, cleanup() is run after each test completes). This is an excellent pattern for testing as you can mock out all dependencies and define their behaviour, so you’re literally just testing the service class.

A great feature of groovy is that you can use String literals to name your methods, this makes tests much easier to read and work out what it is actually testing rather than naming them as “public void testItGetsAUserById()”

Given, when, then

Spock is a behaviour driven development (BDD) testing framework, which is where it gets the given, when and then patterns from (amongst others). The easiest way I can explain it as follows:

Given some parts, when you do something, then you expect certain things to happen.

It’s probably easier to explain my test. We’re given an id of 1, you can think of this as a variable for the test. The when block is where the test starts, this is the invocation, we’re saying that when we call findUser() on the service passing in an id, we’ll get something back and assign it to the result.

The then block are your assertions, this is where you check the outcomes. The first line in the then block looks a little scary, but actually it’s very simple, lets dissect it.

1 * dao.get(id) >> new User(id:id, name:"James", age:27)

This line is setting an expectation on the mocked dao. We’re saying that we expect 1 (and only 1) invocation on the dao.get() method, that invocation must be passed id (which we defined as 1 earlier). Still with me? Good, we’re half way.

The double chevron “>>” is a spock feature, it means “then return”. So really this line reads as “we expect 1 hit on the mocked dao get(), and when we do, return a new User object”

You can also see that I’m using named parameters in the constructor of the User object, this is another neat little feature of groovy.

The rest of the then block are just assertions on the result object, not really required here as we’re doing a straight passthrough on the dao, but gives an insight as to what you’d normally want to do in more complex examples.

The implementation.

If you run the test, it’ll fail, as we haven’t implemented the service class, so lets go ahead and do that right now, its quite simple, just update the service class to the following:

public class UserService {

    private UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User findUser(int id){
        return userDao.get(id);
    }
}

Run the test again, it should pass this time.

Stepping it up

That was a reasonably simple example, lets look at creating some users. Add the following into the UserService:

public void createUser(User user){
        // check name

        // if exists, throw exception

        // if !exists, create user
    }

Then add these methods into the UserDao

public User findByName(String name);
    public void createUser(User user);

Then start with this test

def "it saves a new user"(){
        given:
        def user = new User(id: 1, name: 'James', age:27)

        when:
        service.createUser(user)

        then:
        1 * dao.findByName(user.name) >> null

        then:
        1 * dao.createUser(user)
    }

This time, we’re testing the createUser() method on the service, you’ll notice that there is nothing returned this time.

You may be asking “why are there 2 then blocks?”, if you group everything into a single then block, Spock just asserts that they all happen, it doesn’t care about ordering. If you want ordering on assertions then you need to split into separate then blocks, spock then asserts them in order. In our case, we want to firstly find by user name to see if it exists, THEN we want to create it.

Run the test, it should fail. Implement with the following and it’ll pass

    public void createUser(User user){
        User existing = userDao.findByName(user.getName());

        if(existing == null){
            userDao.createUser(user);
        }
    }

Thats great for scenarios where the user doesn’t already exist, but what if it does? Lets write so co…NO! Test first!

    def "it fails to create a user because one already exists with that name"(){
        given:
        def user = new User(id: 1, name: 'James', age:27)

        when:
        service.createUser(user)

        then:
        1 * dao.findByName(user.name) >> user

        then:
        0 * dao.createUser(user)

        then:
        def exception = thrown(RuntimeException)
        exception.message == "User with name ${user.name} already exists!"
    }

This time, when we call findByName, we want to return an existing user. Then we want 0 interactions with the createUser() mocked method.

The third then block grabs hold of the thrown exception by calling thrown() and asserts the message. Note that groovy has a neat feature called GStrings that allow you to put arguments inside quoted strings.

Run the test, it will fail. Implement with the following at it’ll pass.

public void createUser(User user){
        User existing = userDao.findByName(user.getName());

        if(existing == null){
            userDao.createUser(user);
        } else{
            throw new RuntimeException(String.format("User with name %s already exists!", user.getName()));
        }
    }

I’ll leave it there, that should give you a brief intro to Spock, there is far more that you can do with it, this is just a basic example.

Snippets of wisdom

  • Read the spock documentation!
  • You can name spock blocks such as given:”Some variables”, this is useful if its not entirely clear what your test is doing.
  • You can use _ * mock.method() when you don’t care how many times a mock is invoked.
  • You can use underscores to wildcard methods and classes in the then block, such as 0 * mock._ to indicate you expect no other calls on the mock, or 0 * _._ to indicate no calls on anything.
  • I often write the given, when and then blocks, but then I start from the when block and work outwards, sounds like an odd approach but I find it easier to work from the invocation then work out what I need (given) and then what happens(then).
  • The expect block is useful for testing simpler methods that don’t require asserting on mocks.
  • You can wildcard arguments in the then block if you don’t care what gets passed into mocks.
  • Embrace groovy closures! They can be you’re best friend in assertions!
  • You can override setupSpec and cleanupSpec if you want things to run only once for the entire spec.

Conclusion

Having used Spock (and groovy for testing) on various work and hobby projects I must admit I’ve become quite a fan. Test code is there to be an aid to the developer, not a hinderance. I find that groovy has many shortcuts (collections API to name but a few!) that make writing test code much nicer.

Check out the Github Gist here

Robots! (part 1)

Inspired by the android controlled lego robots I saw at DroidCon UK this year, and with difficulty finding a use for my raspberry pi, I’ve decided to have a go at building a robot that I can control via an android app. Having a 24 hour flight home from Australia at the weekend, I’ve had plenty of time to think about how I might approach this task (or challenge as I refer to it as I’ve no prior experience with robotics / socket programming).

Lego robot powered by the BrickPi

My plan is to have a python socket server running on the pi. This will provide a socket that an android client can invoke commands on. This python server will also interact with the python scripts that the BrickPi uses to control lego motors.

Whilst most of my experience revolves around Java, I’ve opted for python for the following reasons

  • Python is supported on the pi out of the box, no need to mess around with installing Java
  • The BrickPi has support for Python (and C)
  • I feel like learning something new

Baby steps…

Starting simple, I thought it best to create a simple script that listens on a socket, and then create a client that sends it some data to print out to the console. Once I have this working I can expand on it and make the client more sophisticated (an android app for example) and also enhance the server so it can handle different types of commands.

Server
There are plenty of example python scripts online, I found a good one here and tweaked it slightly to remove the parts I don’t want. (full credit to pythonadventures!)

#!/usr/bin/env python
# server.py

import socket
import select
import Queue
from threading import Thread
import sys

class ProcessThread(Thread):
    def __init__(self):
        super(ProcessThread, self).__init__()
        self.running = True
        self.q = Queue.Queue()

    def add(self, data):
        self.q.put(data)

    def stop(self):
        self.running = False

    def run(self):
        q = self.q
        while self.running:
            try:
                # block for 1 second only:
                value = q.get(block=True, timeout=1)
                process(value)
            except Queue.Empty:
                sys.stdout.write('.')
                sys.stdout.flush()
        #
        if not q.empty():
            print "Elements left in the queue:"
            while not q.empty():
                print q.get()

t = ProcessThread()
t.start()

def process(value):
    print value

def main():
    s = socket.socket()
    host = socket.gethostname()
    port = 3033
    s.bind((host, port))

    print "Server listening on port {p}...".format(p=port)

    s.listen(5)                 # Now wait for client connection.

    while True:
        try:
            client, addr = s.accept()
            ready = select.select([client,],[], [],2)
            if ready[0]:
                data = client.recv(4096)
                t.add(data)
        except KeyboardInterrupt:
            print
            print "Stopping server."
            break
        except socket.error, msg:
            print "Socket error %s" % msg
            break

    cleanup()

def cleanup():
    t.stop()
    t.join()

if __name__ == "__main__":
    main()

The socket is bound to a port, and then continually listens for incoming data. Once some data is received, it is added onto a queue, which is then sequentially executed.

Client
The client is is fairly straightforward, it involves opening a connection on a socket and writing data to it, a few lines of Java code.

public static void main(String[] args) throws IOException {

        InetAddress address = InetAddress.getLocalHost();
        Socket socket = new Socket(address, 3033);

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

        System.out.println("Sending message...");

        osw.write("Hello!");
        osw.flush();
    }

Thats it for now, you can checkout my code on github (or just copy/paste the above) and run the client and server and see it in action.

I’ll start on the client next..

A few little tweaks to automate Android instrumentation testing via Robotium & Maven

Having recently revived an android project I haven’t opened in close to 6 months, I was left scratching my head as to why I couldn’t run any of my integration tests.

Thinking back, I remembered having problems getting robotium to instrument the clicking of a button, as simple as it sounds, theres a few little gotchas involved. Firstly, I needed to modify the test code to click on text, rather than a button, as it has been suggested by various users on StackOverflow that there does tend to be odd side effects when clicking buttons:

public void testClickGetSurveyTakesToSurveyRunner() {
 solo.clickOnText("Get Survey");
 solo.assertCurrentActivity("Current activity was not correct", SurveyRunner.class);
 }

Next, I needed to add this into the test projects AndroidManifest

<uses-sdk android:targetSdkVersion="10" />

And then to add this into the main projects AndroidManifest:

<supports-screens android:anyDensity="true"/> 

Both of these tweaks are mentioned on the Robotium FAQ, so it might be worth glancing there to see if any enhancements get made in the future

After making those changes, I stumbled into another error that reared its ugly head in the logcat:

ERROR/AndroidRuntime(1185): FATAL EXCEPTION: main
 java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
 at com.roosearch.android.activity.SurveyRunner.onResume(SurveyRunner.java:38)
 at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
 at android.app.Activity.performResume(Activity.java:3832)
 at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
 at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
 at android.app.ActivityThread.access$1500(ActivityThread.java:117)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
 at android.os.Handler.dispatchMessage(Handler.java:99)
 at android.os.Looper.loop(Looper.java:130)
 at android.app.ActivityThread.main(ActivityThread.java:3683)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:507)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 at dalvik.system.NativeStart.main(Native Method)

There seems to be a rather peculiar requirement, that any dependencies your using on your main application, also need to be in the test projects pom.xml, but marked with a scope of provided. After making that change as advised here and rebuilding, both the app and instrumentation app build and test successfully.

I was also pleasantly surprised that I could run the instrumentation tests via IntelliJ IDEA 12 Ultimate, last time I tried that (on an older version albeit), it wasn’t so simple…

How I passed the SCJP / OCPJP

After procrastinating for many years (4 to be precise), I finally sat and passed the SCJP exam. The exam itself wasn’t particularly difficult, but theres a lot of things you can get tested on that you’ll rarely use in everyday development. Having been developing in Java for around 4 years now, I’ve never needed to do any serialisation or do any fancy concurrency work other than starting a thread for an asynchrnous task.

So to iterate, theres a lot in there that you may not use, but the test expects you to know it well, so be sure to practice and write a lot of code.

Anyways, the reason for this post was to discuss some of the tactics I used to get through.

The study part

The first thing you need to do, is to get hold of the study guide and start reading through it. If you’re relatively new to Java, such as a student or someone transitioning from another background, then you can get Head First Java which will give you a fantastic intro to the Java programming language in an easy to digest read. You should be able to get through HFJ in a few weeks as it has a relatively informal style, but you should certainly allow a month or two to read the study guide, as its around 800 pages and you need to keep focus!

Write code

I can’t stress how important this is! My memory is pretty useless, I can read a book and then a month or two later I’ll have forgotten most of it. I found the best way to remember things is to practice them, so when I’ve read a chapter (or even a few pages on a specific topic) I’d start experimenting with some code. It just helps the knowledge stay in.

My advice here, just download an IDE and start writing, you can also post your code up onto Github too, it makes a great reference point, and may help others. You can also blog using your study notes, which is pretty much the main reason I setup this blog in the first place.

 

Resources, things to buy, free stuff

  1. Head First Java
  2. SCJP Study Guide
  3. SCJP Practice exam book
  4. A set of blank flash/record cards, these will be around £4 from your local stationary shop, use them to write important points and revise when you can spare the odd 5 minutes here and there.
  5. Evernote.com – Get signed up on there, its a great way to store your study notes. You can also get the mobile app to revise your notes when on a train / plane etc.
  6. JavaRanch.com – Post up here in the certification section any questions that you may have, very useful community
  7. StackOverflow.com – I used this a lot for finding answers that were not always obvious in the study guides. If your questions are well defined, you’ll get great help here
  8. Colleagues – Don’t underestimate your peers, if you don’t understand areas of the syllabus, chat to people!
  9. Whizlabs – Great testing kit, but make sure you use it. I wasn’t aware that the software expires after 1 year, so unfortunately I didn’t get to use it for my exam :(
  10. Enthuware – This is much better than whizlabs as it doesn’t require being online, and you get to select how many questions. Often I didn’t want to do all 60 in one go

 

Suggested schedule

When booking my exam, I gave myself around 3 months, considering I’d already been over the book a few times it was plenty enough to recap the important chapters and squeeze in some mock tests. If you’re sitting this for the first time, I’d suggest a preparation schedule like below, assuming you will have 8 months to prepare. Of course, if you’ve been developing for a while you can probably skip the first 2 weeks, read the study guide in a condensed amount of time, and take less practice tests.

 

Week 1 Read Head First Java
Week 2 Read Head First Java
Week 3 Take a week off
Week 4 Study guide chapter 1
Week 5 Experiment with code relating to chapter, then do chapter quiz
Week 6 Study guide chapter 2
Week 7 Experiment with code relating to chapter, then do chapter quiz
Week 8 Study guide chapter 3
Week 9 Experiment with code relating to chapter, then do chapter quiz
Week 10 Study guide chapter 4
Week 11 Experiment with code relating to chapter, then do chapter quiz
Week 12 Study guide chapter 5
Week 13 Experiment with code relating to chapter, then do chapter quiz
Week 14 Study guide chapter 6
Week 15 Experiment with code relating to chapter, then do chapter quiz
Week 16 Study guide chapter 7
Week 17 Experiment with code relating to chapter, then do chapter quiz
Week 18 Study guide chapter 8
Week 19 Experiment with code relating to chapter, then do chapter quiz
Week 20 Study guide chapter 9
Week 21 Experiment with code relating to chapter, then do chapter quiz
Week 22 Study guide chapter 10
Week 23 Take a week off
Week 24 Whizlabs Tests
Week 25 Whizlabs Tests
Week 26 Whizlabs Tests
Week 27 Take a week off
Week 28 enthuware tests
Week 29 enthuware tests
Week 30 enthuware tests
Week 31 Take a week off
Week 32 Self assessment 1, then brush up on any key areas you really missed on
Week 33 Self assessment 2, then brush up on any key areas you really missed on
Week 34 Practice test 1 & 2
Week 35 Practice test 3 & 4

Tips for the exam:

  • Get there early, my train got cancelled so I was running/stressing to the exam room, which didn’t help.
  • Don’t stress! Thats the worst thing you can do!
  • The actual exam will say how many answers you need to select, so don’t worry about the “select all that apply” that you often see in mock tests.
  • You can “strikeout” answers on the real exam, which means you can eliminate the answers you think are wrong, very useful for those questions that are a complete guess.
  • You don’t get your results immediately, you have to login to Oracle Certview about an hour after completing the exam to see your score card.

 

Continue and break, with and without labels, for the SCJP

Looping constructs are very useful in any programming language, however they can be come particularly complex when you have a variety of nested loops and you need to drop out from particular iterations, or exit the loops entirely under a set of given circumstances. Fortunately for us, Java provides us with 2 keywords that we can use to help in these situations:

  • break – breaks out of the entire loop, and no more iterations will occur. The thread of execution will then move onto the next line of code after the loop.
  • continue – the current iteration will be terminated, and the thread of execution will move onto the next iteration, if there is one, otherwise the loop will complete.

It is important to note, that in both of these keywords, unless otherwise specified via the use of a label, they will apply to the inner most loop that is currently executing.

If you would like to break or continue out of a loop that happens to be nested outside of your current loop, then you need to use labeled loops, whereby you give each one a label and then you can continue/break on one of those given labels. For example, if you have 3 loops, one nested in another, and you’re cycling through the inner most loop and decide that you don’t need to iterate over any of them anymore, as you have all the data you need, then you can call break on the outermost loop and move onto the next piece of code.

Please consider the following example that I have on my SCJP examples page, if I’ve missed anything obvious please let me know:

package com.jameselsey.demo.scjp.flow_control;

/**
 * Author:  JElsey
 * Date:    22/08/2012
 *
 * Experimenting with the break and continue keywords, also using labeling.
 */
public class UsingBreakAndContinue
{
    public static void main(String[] args)
    {
        doUnlabeledBreak();
        doUnlabeledContinue();

        doLabeledBreak();
        doLabeledContinue();

        doNestedLabeledBreak();
        doNestedLabeledContinue();
    }

    /*
        Since we're not using any labels here, the break will break out of the inner most loop, then move
        onto the next statement AFTER the loop. Break will &quot;break out&quot; immediately from the iteration, great for
        cases when you're counting up something, find you have done all the iterations you need, then you can break out
        and prevent wasting time on iterations you no longer need.
     */
    private static void doUnlabeledBreak()
    {
        System.out.println(&quot;START - Un-labeled break&quot;);
        for (int i = 0; i &lt; 5; i++)
        {
            System.out.println(&quot;\tIteration on i:&quot; + i);
            System.out.println(&quot;\tLets call break, we don't want to do any more&quot;);
            break;
            // We're done with the whole loop, &quot;break out&quot; and move onto whatever comes after the loop
            // we don't want to do any more iterations
        }
        System.out.println(&quot;END - Un-labeled break&quot;);

    }

    /*
        We're using no labeling here, so much like the example above, the continue will take effect on the inner most
        loop. Continue drops out of the current iteration immediately, and attempts the next iteration, if there is one.
        This is great for scenarios where you're checking numbers for odd/even, if its an odd number, you could continue on
        to the next iteration; if you only require doing stuff with even numbers (just an example).
     */
    private static void doUnlabeledContinue()
    {
        System.out.println(&quot;START - Un-labeled continue&quot;);
        for (int i = 0; i &lt; 5; i++)
        {
            System.out.println(&quot;\tIteration on i:&quot; + i);
            System.out.println(&quot;\tLets call continue, we don't want to do any more in this iteration&quot;);
            continue;
            // anything under here can't be accessed, since you've called continue which drops out
            // of the iteration and &quot;continues&quot; with the next iteration, if there is one
        }
        System.out.println(&quot;END - Un-labeled continue&quot;);
    }

    /*
        Behaves similar to the unlabeled break, however if you break on a label, it will break for THAT label rather
        than the inner most loop. This is great when you have complex, nested iteration cycles.
     */
    private static void doLabeledBreak()
    {
        System.out.println(&quot;START - labeled break&quot;);
        labeledBreak:
        for (int i = 0; i &lt; 5; i++)
        {
            System.out.println(&quot;\tIteration on i: &quot; + i);
            System.out.println(&quot;\tLets call break, we don't want to do any more in this iteration&quot;);
            break labeledBreak;
            // We've broken out to the &quot;labeledBreak&quot;, so we won't do any more further iterations of this label
        }
        System.out.println(&quot;END - labeled break&quot;);
    }

    /*
        Similar to the labled break, the labeled continue will move onto the next iteration of the label you've
        specified, if there is an iteration, otherwise the loop is complete.
     */
    private static void doLabeledContinue()
    {
        System.out.println(&quot;START - Labeled continue&quot;);
        labeledContinue:
        for (int i = 0; i &lt; 5; i++)
        {
            System.out.println(&quot;\tIteration on i:&quot; + i);
            System.out.println(&quot;\tLets call continue, we don't want to do any more in this iteration&quot;);
            continue labeledContinue;
            // anything under here can't be accessed, since you've called continue which drops out
            // of the iteration and &quot;continues&quot; with the next iteration, if there is one
        }
        System.out.println(&quot;END - Labeled continue&quot;);
    }

    /*
        Using nested breaks here, with labels, so you can see how breaking out of individual nested looping
        constructs would work.
     */
    private static void doNestedLabeledBreak()
    {
        System.out.println(&quot;START - Nested Labeled break&quot;);
        outerLoop:
        for (int i = 0; i &lt; 5; i++)
        {
            innerLoop:
            for(int inner = 0; inner &lt; 5; inner++)
            {
                System.out.println(&quot;We're in the inner loop, lets break out of it...&quot;);
                break innerLoop;
            }
            System.out.println(&quot;Now lets break out of the outer loop too&quot;);
            break outerLoop;
        }
        System.out.println(&quot;END - Nested Labeled break&quot;);
    }

    /*
        Using nested labeled continues here to demonstrate how you'd continue onto labeled looping constructs.
     */
    private static void doNestedLabeledContinue()
    {
        System.out.println(&quot;START - Nested Labeled continue&quot;);
        outerLoop:
        for (int i = 0; i &lt; 5; i++)
        {
            innerLoop:
            for(int inner = 0; inner &lt; 5; inner++)
            {
                System.out.println(&quot;We're in the inner loop, lets continue out of it...&quot;);
                continue innerLoop;
            }
            System.out.println(&quot;Now lets continue out of the outer loop too&quot;);
            continue outerLoop;
        }
        System.out.println(&quot;END - Nested Labeled continue&quot;);
    }

    /*
        Not quite sure where I was going with this one, but was experimenting with some continue
        and break combinations.
     */
    private static void countingNumbers()
    {
        outerLoop:
        for(int i = 0; i         {
            if(i % 2 == 0)
            {
                System.out.println(&quot;Number is odd, lets continue to next iteration&quot;);
                continue outerLoop;
            }

            int sumOfEvens = 0;
            for(int j = 0; j &lt; i; j++)
            {
                 sumOfEvens+= j;
            }

            if(i == 50)
            {
                System.out.println(&quot;We'll only count halfway, and give up at 50&quot;);
                break outerLoop;
            }
        }
    }
}

Interfaces, declaring and implementing

Another bite-size SCJP blog post, this time we’ll tackle interfaces.

Interfaces are, in the simplest terms, just a contract. It specifies things that a class must do if that class signs up to its contract, but it doesn’t provide any details of how those things must be done.

For example, you may wish to create an interface called Driveable. This interface defines the behaviour of anything that wants to become driveable, whether it be a Car class, a Motorcycle class, or even a Boat class.

You can think of an interface like a 100% abstract class, whereby all methods are implicitly abstract and public. Any class that decides to implement the interface, but provide method bodies for every single method in that interface, otherwise the compiler will complain.

Have a look at my sample below of a really basic interface and its implementation, you can find these on my SCJP samples on Github:

package com.jameselsey.demo.scjp.declarations_initialisation_scoping;

/**
 * Author:  JElsey
 * Date:    20/08/2012
 *
 * A quick example to show how an interface can be created, and more importantly how it is implemented.
 */
public class ImplementingAnInterface
{
    public static void main(String[] args)
    {
        // Notice the polymorphism here once again, how car IS-A driveable
        Driveable d1 = new Car();
        Driveable d2 = new Motorcycle();
        // The implementations provide the drive() method body.
        d1.drive();
        d2.drive();
    }
}

/*
 Create an interface, along with its methods. Think of it like a contract, anything that wants to become Driveable MUST
 implement the drive method, otherwise the contract is not fulfilled and the compiler will complain!
  */
interface Driveable
{
    public void drive();
}

class Car implements Driveable
{
    @Override
    public void drive()
    {
        System.out.println("Super charged v8 goes VROOOOM!!");
    }
}
class Motorcycle implements Driveable
{
    @Override
    public void drive()
    {
        System.out.println("Front rears up, wheelie down the highway!");
    }
}

Polymorphism, a little overview with code samples

Polymorphism basically means that one thing can take many forms, and this is particularly useful for programmers, as it allows us to treat similar types of object in a single manner, yet the objects may actually be slightly different at runtime.

One application of this might be where we have an animal class, we know that the animal class has methods like makeNoise(), move() and eat(), and we can happily develop our application against this. However, we may then like to extend the animal class, and create subclasses like Dog, Fish, and Cat, each which would inherit those methods, and optionally override the implementation to do things that are a little more Dog specific.

Consider the following example that I have hosted up on my SCJP samples Github page:

package com.jameselsey.demo.scjp.oo_concepts;

/**
 * Author:  JElsey
 * Date:    16/08/2012
 *
 * A few examples of polymorphism, meaning that one thing can represent many, or in another words, "morphed" in many (poly) ways
 */
public class Polymorphism
{
    public static void main(String[] args)
    {
        Animal animal;

        //  Polymorphic assignments here, animal being assigned as one of its sub-classes
        animal = new Cat();
        System.out.println("Cat makes a noise : " + animal.makeANoise());
        animal = new Dog();
        System.out.println("Dog makes a noise : " + animal.makeANoise());
        animal = new Fish();
        System.out.println("Fish makes a noise : " + animal.makeANoise());

        // Polymorphic array, declared as type Animal but contains sub-types
        Animal[] theAnimals = new Animal[]{new Cat(), new Dog(), new Fish()};
        for (Animal a : theAnimals)
        {
            // Since they're all of type animal, they all have a makeANoise() method, but the actual
            // implementation varies
            System.out.println(a.makeANoise());
        }
    }
}

abstract class Animal
{
     public abstract String makeANoise();
}

class Cat extends Animal
{
    @Override
    public String makeANoise()
    {
        return "Meow";
    }
}

class Dog extends Animal
{
    @Override
    public String makeANoise()
    {
        return "Woof";
    }
}

class Fish extends Animal
{
    @Override
    public String makeANoise()
    {
        return "Gurgle";
    }
}

Most of the time, you’ll actually use polymorphism without even realising, you just do it naturally. You’ll often find that it is useful especially when you “code to the interface, not the implementation”.

That is all.