lady-gaga-bubblesWrite WS client that uses JAXBContext, Marshaller and Unmarshaller. Use bubble sort algorithm as web method.

 

 

 

 

Example Solution

Service Implementation Bean

package com.fuzilaga.jws.bubblesort;

import java.util.ArrayList;
import java.util.Arrays;

import javax.jws.WebService;

@WebService(endpointInterface = "com.fuzilaga.jws.bubblesort.BubbleSortService")
public class BubbleSortServiceImpl implements BubbleSortService
{

	@Override
	public ArrayList<Person> sort(ArrayList<Person> list)
	{
		Person[] person = new Person[list.size()];
		list.toArray(person);

		boolean swapped = true;
		int j = 0;
		Person tmp;
		while (swapped)
		{
			swapped = false;
			j++;
			for (int i = 0; i < person.length - j; i++)
			{
				if (person[i].id > person[i + 1].id)
				{
					tmp = person[i];
					person[i] = person[i + 1];
					person[i + 1] = tmp;
					swapped = true;
				}
			}
		}

		return new ArrayList<Person>(Arrays.asList(person));
	}

}

Service Client

package com.fuzilaga.jws.bubblesort;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class BubbleSortClient
{
	public static void main(String args[]) throws Exception
	{
		// Marshall
		JAXBContext context = JAXBContext.newInstance(Person.class);
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		Person person = new Person();
		person.id = 1;
		person.twin = new Person();
		marshaller.marshal(person, System.out);

		String fileName = "C:\\temp.xml";
		FileOutputStream out = new FileOutputStream(fileName);
		marshaller.marshal(person, out);
		out.close();

		// Unmarshall
		Unmarshaller unmarshaller = context.createUnmarshaller();
		ArrayList<Person> list = new ArrayList<Person>();
		list.add(person);
		Person a = (Person) unmarshaller.unmarshal(new File(fileName));
		a.id = 4;
		list.add(a);
		Person b = (Person) unmarshaller.unmarshal(new File(fileName));
		b.id = 2;
		list.add(b);
		Person c = (Person) unmarshaller.unmarshal(new File(fileName));
		c.id = -5;
		list.add(c);

		// call service
		URL url = new URL("http://localhost:8880/bubblesort");
		QName qname = new QName("http://bubblesort.jws.fuzilaga.com/", "BubbleSortServiceImplService");
		Service service = Service.create(url, qname);
		BubbleSortService port = service.getPort(BubbleSortService.class);
		ArrayList<Person> resultList = port.sort(list);

		// output
		for (Person p : resultList)
		{
			System.out.println(p.id);
		}
	}
}

The result output is:
-5
1
2
4

NOTE: Full source and instructions on how to run locally can be found here.