
package com.sun.xml.ws.commons.virtualbox;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.WebServiceException;
import org.virtualbox.service.InvalidObjectFaultMsg;
import org.virtualbox.service.RuntimeFaultMsg;
import org.virtualbox.service.VboxService;
import org.virtualbox.service.VboxPortType;

public class VirtualBox {
    public static IVirtualBox connect(URL url) 
    {
        return connect(url.toExternalForm());
    }
    
    public static IVirtualBox connect(String url) 
    {
        return connect(url, "", "");
    }

    public static IVirtualBox connect(String url, String user, String password) {
        try {
            URL wsdl = VirtualBox.class.getClassLoader().getResource("vboxwebService.wsdl");
            if (wsdl==null)
                throw new LinkageError("vboxwebService.wsdl not found, but it should have been in the jar");
            VboxService svc = new VboxService(wsdl, new QName("http://www.virtualbox.org/Service", "vboxService"));
            VboxPortType port = svc.getVboxServicePort();
            ((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
            String vbox = port.iWebsessionManagerLogon(user, password);
            return new IVirtualBox(vbox, port);
        } catch (InvalidObjectFaultMsg e) {
          throw new WebServiceException(e);
        } catch (RuntimeFaultMsg e) {
          throw new WebServiceException(e);
        }
    }
}
