2 February 2014

Creating a JAX-WS Dispatch client using JAXB

import cards.*;
import java.util.logging.*;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import javax.xml.ws.*;
import javax.xml.ws.soap.SOAPBinding;

public class CardDeckSEJaxbDispatchClient {

    private static final String URI = "http://ejbs/";
    public static final String NS = "ns1";

    public static void main(String[] args) {
        Service svc = Service.create(new QName(
            URI,
            "CardDeckSessionBeanService"));
        final QName portName = new QName(URI, "CardDeckSessionBeanPort");
        svc.addPort(portName,
            SOAPBinding.SOAP11HTTP_BINDING,
            "http://localhost:7001/CardDeckSessionBean/CardDeckSessionBeanService");
        try {
             // cards is a package with JAXB classes
             Dispatch<Object> dispatch = svc.createDispatch(portName,
                JAXBContext.newInstance("cards"),
                Service.Mode.PAYLOAD);
            // objectfactory is generated by wsimport
            ObjectFactory of = new ObjectFactory();
            // create deck
            CreateDeck createParam = of.createCreateDeck();
            createParam.setArg0(1);
            JAXBElement<CreateDeckResponse> createResponse
                = (JAXBElement<CreateDeckResponse>) dispatch.
                    invoke(of.createCreateDeck(createParam));
            int deckId = createResponse.getValue().getReturn();
            System.out.println("\nDeck ID = " + deckId);
            // getDeck
            GetDeck getParam = of.createGetDeck();
            getParam.setArg0(deckId);
            JAXBElement<GetDeckResponse> getResponse = 
                (JAXBElement<GetDeckResponse>) dispatch.
                invoke(of.createGetDeck(getParam));
            StackType deck = getResponse.getValue().getReturn();
            for (CardType card : deck.getCard()) {
                System.out.println(
                    card.getRank()
                    + " OF "
                    + ("JOKER".equals(card.getRank()) ? card.getColor() : card.getSuit()));
            } // end for all cards in deck
        } catch (JAXBException ex) {
            Logger.getLogger(CardDeckSEJaxbDispatchClient.class.getName()).
                log(Level.SEVERE, null, ex);
        } // end catch
    } // end main
} // end class

No comments:

Post a Comment