
package org.eclipse.birt.report.tests.viewer.regression;

import java.io.File;
import java.io.IOException;

import org.apache.cactus.WebRequest;
import org.eclipse.birt.report.servlet.BirtEngineServlet;
import org.eclipse.birt.report.tests.viewer.BaseViewerTestCase;
import org.xml.sax.SAXException;

import com.meterware.httpunit.HTMLElement;
import com.meterware.httpunit.WebResponse;

/**
 * <b>Description:</b>
 * <p>
 * Cannot find image from defined resource path when deploy birt.
 * <p>
 * <b>Steps to reproduce:</b>
 * <ol>
 * <li>Set BIRT_RESOURCE_PATH as local absolute path.
 * <li>Copy aa.jpg to this folder
 * <li>Deploy birt
 * <li>Preview a report which uses aa.jpg
 * </ol>
 * <b>Expected result:</b> Image shows.
 * <p>
 * <b>Actual result:</b> Failed to show image. <b>Test description:</b> View
 * the report, get the response, make sure the image source link is correct and
 * the catched image is generated under correct path.
 */
public class Regression_141954 extends BaseViewerTestCase
{

	private final static String REPORT = "report/regression_141954.rptdesign"; //$NON-NLS-1$

	/**
	 * @param webRequest
	 * @throws Exception
	 */
	public void begin_regression_141954( WebRequest webRequest )
	{
		webRequest.setURL( null, null, SERVLET_PATH_RUN, null, null );
		webRequest.addParameter( PARAM_REPORT, REPORT );
		webRequest.addParameter( PARAM_LOCALE, "en_US" ); //$NON-NLS-1$
	}

	/**
	 * test_regression_141954
	 */
	public void test_regression_141954( )
	{
		BirtEngineServlet servlet = new BirtEngineServlet( );
		try
		{
			servlet.init( config );
			servlet.doGet( request, response );
		}
		catch ( Exception e )
		{
			e.printStackTrace( );
			fail( e.toString( ) );
		}
	}

	/**
	 * @param webResponse
	 * @throws IOException
	 * @throws SAXException
	 * @throws Exception
	 */
	public void end_regression_141954( WebResponse webResponse )
			throws IOException, SAXException
	{
		String text = webResponse.getText( );
		HTMLElement[] elements = webResponse.getElementsWithAttribute(
				"id", "bk1" ); //$NON-NLS-1$//$NON-NLS-2$

		assertNotNull( elements );
		assertTrue( elements.length > 0 );

		HTMLElement imageElement = elements[0];
		String src = imageElement.getAttribute( "src" ); //$NON-NLS-1$

		System.out.println( src );

		// match image source like:
		// "/WebViewerExample_0821/run?__imageID=file1.jpg"

		assertTrue( src.matches( "/" + RUNTIME + "/run\\?__imageID=.*jpg" ) ); //$NON-NLS-1$//$NON-NLS-2$
		String imageName = src.substring( src.indexOf( "=" ) + 1 ); //$NON-NLS-1$
		System.out.println( imageName );

		// make sure the temparary image is generated under default image
		// folder.

		String imageFilePath = getRuntimeFolder( ) + IMAGE_DIR + "/" //$NON-NLS-1$
				+ imageName;
		System.out.println( imageFilePath );

		File imageFile = new File( imageFilePath );
		assertTrue( imageFile.exists( ) );
		System.out.println( text );
	}

}