
/**
 * Copyright (C) 2008-2009 Sun Microsystems, Inc.
 *
 * This file is part of a free software library; you can redistribute
 * it and/or modify it under the terms of the GNU Lesser General
 * Public License version 2.1 as published by the Free Software
 * Foundation and shipped in the "COPYING.LIB" file with this library.
 * The library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY of any kind.
 *
 * Sun LGPL Disclaimer: For the avoidance of doubt, except that if
 * any license choice other than GPL or LGPL is available it will
 * apply instead, Sun elects to use only the Lesser General Public
 * License version 2.1 (LGPLv2) at this time for any software where
 * a choice of LGPL license versions is made available with the
 * language indicating that LGPLv2 or any later version may be used,
 * or where a choice of which version of the LGPL is applied is
 * otherwise unspecified.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 USA or visit http://www.sun.com if you need
 * additional information or have any questions.
 *
 * IWebsessionManager.java
 *
 * DO NOT EDIT! This is a generated file.
 * Generated from: src/VBox/Main/idl/VirtualBox.xidl (VirtualBox's interface definitions in XML)
 * Generator: src/VBox/Main/webservice/glue-jaxws.xsl
 */


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

import org.virtualbox_2_2.VboxPortType;
import org.virtualbox_2_2.VboxService;
import org.virtualbox_2_2.InvalidObjectFaultMsg;
import org.virtualbox_2_2.RuntimeFaultMsg;
import javax.xml.ws.WebServiceException;

import java.net.URL;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import javax.xml.ws.WebServiceException;

class PortPool
{
    private Map<VboxPortType, Integer> known;
    private boolean initStarted;
    private VboxService svc;

    PortPool(boolean usePreinit)
    {
        known = new HashMap<VboxPortType, Integer>();

        if (usePreinit)
        {
           new Thread(new Runnable()
              {
                 public void run()
                 {
                    // need to sync on something else but 'this'
                    synchronized (known)
                    {
                      initStarted = true;
                      known.notify();
                    }

                    preinit();
                 }
               }).start();

           synchronized (known)
           {
              while (!initStarted)
              {
                 try {
                   known.wait();
                 } catch (InterruptedException e) {
                 break;
                 }
              }
           }
        }
    }

    private synchronized void preinit()
    {
        VboxPortType port = getPort();
        releasePort(port);
    }

    synchronized VboxPortType getPort()
    {
        VboxPortType port = null;
        for (VboxPortType cur: known.keySet())
        {
            if (known.get(cur) == 0)
            {
                port = cur;
                break;
            }
        }

        if (port == null)
        {
            if (svc == null) {
                URL wsdl = PortPool.class.getClassLoader().getResource("vboxwebService.wsdl");
                if (wsdl == null)
                    throw new LinkageError("vboxwebService.wsdl not found, but it should have been in the jar");
                svc = new VboxService(wsdl,
                                      new QName("http://www.virtualbox.org/Service",
                                                "vboxService"));
            }
            port = svc.getVboxServicePort();
        }
        known.put(port, new Integer(1));
        return port;
    }

    synchronized void releasePort(VboxPortType port)
    {
        Integer val =  known.get(port);
        if (val == null || val == 0)
        {
            // know you not
            return;
        }
        known.put(port, val - 1);
    }
}

public class IWebsessionManager {

    private static PortPool pool = new PortPool(true);
    protected VboxPortType port;

    public IWebsessionManager(URL url)
    {
        connect(url);
    }

    public IWebsessionManager(String url)
    {
        connect(url);
    }

    public IWebsessionManager(URL url, Map<String, Object> requestContext, Map<String, Object> responseContext)
    {
        connect(url.toExternalForm(), requestContext, responseContext);
    }

    public IWebsessionManager(String url, Map<String, Object> requestContext, Map<String, Object> responseContext)
    {
        connect(url, requestContext, responseContext);
    }

    public void connect(URL url)
    {
        connect(url.toExternalForm());
    }

    public void connect(String url)
    {
        this.port = pool.getPort();
        ((BindingProvider)port).getRequestContext().
                put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
    }

    public void connect(String url, Map<String, Object> requestContext, Map<String, Object> responseContext)
    {
         this.port = pool.getPort();

         ((BindingProvider)port).getRequestContext();
         if (requestContext != null)
               ((BindingProvider)port).getRequestContext().putAll(requestContext);

         if (responseContext != null)
               ((BindingProvider)port).getResponseContext().putAll(responseContext);

         ((BindingProvider)port).getRequestContext().
                put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
    }


    public void disconnect(IVirtualBox refIVirtualBox)
    {
        logoff(refIVirtualBox);
        pool.releasePort(port);
    }

    public void cleanupUnused()
    {
       System.gc();
       Runtime.getRuntime().runFinalization();
    }

    /* method IWebsessionManager::logon(
            [in] wstring username,
            [in] wstring password,
            [return] IVirtualBox return)
     */
    public IVirtualBox logon(String username, String password) {
        try {
            String retVal = port.iWebsessionManagerLogon(username, password);
            return new IVirtualBox(retVal, port);
        } catch (InvalidObjectFaultMsg e) {
            throw new WebServiceException(e);
        } catch (RuntimeFaultMsg e) {
            throw new WebServiceException(e);
        }
    }

    /* method IWebsessionManager::getSessionObject(
            [in] IVirtualBox refIVirtualBox,
            [return] ISession return)
     */
    public ISession getSessionObject(IVirtualBox refIVirtualBox) {
        try {
            String retVal = port.iWebsessionManagerGetSessionObject(((refIVirtualBox == null)?null:refIVirtualBox.getRef()));
            return new ISession(retVal, port);
        } catch (InvalidObjectFaultMsg e) {
            throw new WebServiceException(e);
        } catch (RuntimeFaultMsg e) {
            throw new WebServiceException(e);
        }
    }

    /* method IWebsessionManager::logoff(
            [in] IVirtualBox refIVirtualBox)
     */
    public void logoff(IVirtualBox refIVirtualBox) {
        try {
            port.iWebsessionManagerLogoff(((refIVirtualBox == null)?null:refIVirtualBox.getRef()));
        } catch (InvalidObjectFaultMsg e) {
            throw new WebServiceException(e);
        } catch (RuntimeFaultMsg e) {
            throw new WebServiceException(e);
        }
    }
}
