/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.test.util.service;

import java.net.URL;
import java.net.URLConnection;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.HashMap;
import javax.management.ObjectName;
import javax.management.NotificationListener;
import javax.management.Notification;

import org.jboss.deployment.DeploymentException;
import org.jboss.deployment.SARDeployerMBean;
import org.jboss.deployment.DeploymentInfo;
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.system.ServiceMBean;
import org.jboss.system.ServiceControllerMBean;
import org.jboss.mx.util.MBeanProxy;

/** A utility service that allows one to overwrite the contents of a
 * mbean service descriptor with a descriptor specified via a URL.
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1.2.2 $
 */
public class RedeployService extends ServiceMBeanSupport
   implements NotificationListener, RedeployServiceMBean
{
   private SARDeployerMBean sarDeployer;
   private HashMap redeployMap = new HashMap();

   /** Overwrites the service descriptor for the targetService with the content
    * of the descriptorURL.
    * 
    * @param targetService
    * @param descriptor
    */ 
   public void redeploy(ObjectName targetService, URL descriptorURL)
      throws DeploymentException
   {
      // Get the DeploymentInfo for the targetService
      DeploymentInfo di = sarDeployer.getService(targetService);
      if( di == null )
      {
         boolean isRegistered = server.isRegistered(targetService);
         throw new DeploymentException("Failed to find DeploymentInfo for: "
            +targetService+", isRegistered="+isRegistered);
      }
      Object redeployMonitor = new Object();
      redeployMap.put(targetService, redeployMonitor);

      log.info("WatchURL for: "+targetService+" is: "+di.watch);
      /* Obtain the contents of the descriptorURL and overwrite the
      targetService descriptor with the content.
      */
      try
      {
         URL targetURL = new URL(di.watch.toExternalForm());
         URLConnection conn = targetURL.openConnection();
         OutputStream os = conn.getOutputStream();
         InputStream is = descriptorURL.openStream();
         byte[] buffer = new byte[1024];
         int bytes = 0;
         int totalBytes = 0;
         while( (bytes = is.read(buffer)) > 0 )
         {
            os.write(buffer, 0, bytes);
            totalBytes += bytes;
         }
         os.flush();
         is.close();
         os.close();
         log.info("Updated service descriptor, length="+totalBytes);
         log.info("Waiting for "+targetService+" to restart");
         synchronized( redeployMonitor )
         {
            redeployMonitor.wait();
         }
         log.info(targetService+" has restarted");
      }
      catch(Exception e)
      {
         throw new DeploymentException("Failed to update service descriptor", e);
      }
      finally
      {
         redeployMap.remove(targetService);
      }
   }

   public void handleNotification(Notification msg,
      Object notused)
   {
      String type = msg.getType();
      log.debug("handleNotification, notification="+msg);
      if( type.equals(ServiceMBean.START_EVENT) )
      {
         ObjectName serviceName = (ObjectName) msg.getUserData();
         if( redeployMap.containsKey(serviceName) )
         {
            Object monitor = redeployMap.get(serviceName);
            if( monitor != null )
            {
               synchronized( monitor )
               {
                  log.info("Notified redeploy thread of create");
                  monitor.notify();
               }
            }
         }
      }
   }

   protected void startService() throws Exception
   {
      sarDeployer = (SARDeployerMBean) MBeanProxy.get(SARDeployerMBean.class,
         SARDeployerMBean.OBJECT_NAME, server);
      server.addNotificationListener(ServiceControllerMBean.OBJECT_NAME,
         this, null, null);
   }
   protected void stopService() throws Exception
   {
      server.removeNotificationListener(ServiceControllerMBean.OBJECT_NAME, this);
   }
}
