/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file 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.soa.bpel.tests;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import javax.management.MBeanServerConnection;
import javax.naming.NamingException;

import junit.framework.TestCase;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.jboss.logging.Logger;
import org.jboss.soa.esb.message.Message;
import org.jboss.soa.esb.message.format.MessageFactory;
import org.jboss.soa.esb.client.ServiceInvoker;

/**
 * Base class for RiftSaw test cases. Based on
 * equivalent class in JBossWS written by
 * Thomas Diesler and Richard Opalka.
 *
 */
public abstract class RiftSawTest extends TestCase {
	
   protected static Logger log = Logger.getLogger(RiftSawTest.class.getName());
   private RiftSawTestHelper delegate = new RiftSawTestHelper();
   
   private String m_testSuiteName=null;

   public RiftSawTest(String name) {
      super(name);
      
      m_testSuiteName = name;
   }
   
   public String getTestSuiteName() {
	   return(m_testSuiteName);
   }

   public MBeanServerConnection getServer() throws NamingException {
      return RiftSawTestHelper.getServer();
   }

   /** Deploy the given archive
    */
   public void deploy(String archive) throws Exception {
      delegate.deploy(getTestSuiteName(), archive);
   }

   /** Undeploy the given archive
    */
   public void undeploy(String archive) throws Exception {
      delegate.undeploy(getTestSuiteName(), archive);
   }

   public File getTestFile(String filename) {
      return delegate.getTestFile(getTestSuiteName(), filename);
   }

   public URL getTestFileURL(String filename) throws MalformedURLException {
      return delegate.getTestFileURL(getTestSuiteName(), filename);
   }
   
	protected void assertMessageFromFile(String message, String mesgFile) throws Exception {
		String mesgpath=System.getProperty("test.dir")+java.io.File.separator+getTestSuiteName()+
									java.io.File.separator+mesgFile;

		java.io.FileInputStream is=new java.io.FileInputStream(mesgpath);
		byte[] b=new byte[is.available()];
		is.read(b);
		is.close();
		
		String comparison=new String(b).trim();
		message = message.trim();
		
		if (!comparison.equals(message)) {
			fail("Message in file '"+mesgFile+"' has content ["+comparison+
					"] which is not the same as ["+message+"], lengths "+comparison.length()+" to "+message.length());
		}
	}
	
	protected void assertMessage(String message, String comparison) throws Exception {
		message = message.trim();
		
		if (!comparison.equals(message)) {
			fail("Expected message has content ["+comparison+
					"] which is not the same as ["+message+"], lengths "+comparison.length()+" to "+message.length());
		}
	}
	
	protected String sendSOAPMessage(String mesgFile, String url) throws Exception {
		String mesgpath=System.getProperty("test.dir")+java.io.File.separator+getTestSuiteName()+
						java.io.File.separator+mesgFile;
		
		java.io.FileInputStream is=new java.io.FileInputStream(mesgpath);
		byte[] b=new byte[is.available()];
		is.read(b);
		is.close();
		
		java.net.URL u=new java.net.URL(url);
		String soapAction="";
		String request=new String(b);
				
		HttpClient httpClient = new HttpClient();
        PostMethod httpPostMethod = new PostMethod(u.toExternalForm());
        httpPostMethod.setRequestHeader("SOAPAction", "\"" + soapAction + "\"");
        httpPostMethod.setRequestHeader("Content-Type", "text/xml");
        httpPostMethod.setRequestEntity(new StringRequestEntity(request));
        httpClient.executeMethod(httpPostMethod);
        String result=httpPostMethod.getResponseBodyAsString();
		
		return(result);
	} 
	
	protected String sendESBMessage(String message, String serviceCategory, String serviceName)
					throws Exception {
		return(sendESBMessage(message, serviceCategory, serviceName, 10000));
	}
	
	protected String sendESBMessage(String message, String serviceCategory, String serviceName, long timeout)
					throws Exception {
		String result=null;
		
        System.setProperty("javax.xml.registry.ConnectionFactoryClass",
        			"org.apache.ws.scout.registry.ConnectionFactoryImpl");

        Message esbMessage = MessageFactory.getInstance().getMessage();

    	esbMessage.getBody().add(message);
    	
        Message respMessage = new ServiceInvoker(serviceCategory, serviceName).deliverSync(esbMessage, timeout);
    	
        result = (String)respMessage.getBody().get();

        return(result);
	}
}
