Package org.jboss.jopr.jsfunit.as5.app.war

Source Code of org.jboss.jopr.jsfunit.as5.app.war.WarTest

/*
* JBoss, Home of Professional Open Source.
* Copyright 2009, 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.jopr.jsfunit.as5.app.war;

import com.gargoylesoftware.htmlunit.Page;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import com.gargoylesoftware.htmlunit.WebClient;
import org.jboss.jopr.jsfunit.util.EmbJoprTestToolkit.*;

import org.jboss.jopr.jsfunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import java.io.*;
import java.util.Properties;
import javax.faces.application.FacesMessage;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.jboss.jopr.jsfunit.exceptions.*;
import org.jboss.jopr.jsfunit.util.ActiveConditionChecker;
import org.jboss.jopr.jsfunit.util.DescribedCondition;
import org.jboss.jopr.jsfunit.util.EmbJoprTestToolkit.*;
import org.w3c.dom.Node;

/**
* This class contains tests for testing the EmbJopr Application
* Management Functions for Web Components with JBoss AS 5.
*
* Most tests currently fail because of
* JBAS-6640: Undeploying and deploying the same WAR in short time fails.
*/
public class WarTest extends ApplicationTestBaseAS5 {

  public static final int DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL = 6000;
  public static final int DEPLOY_UP_STATE_WAIT_CHECK_RETRIES = 50;

  public static final DeployableTypes APP_TYPE = DeployableTypes.WAR;

 

  /**
   * @return the suite of tests being tested
   */
  public static Test suite() {
    return new TestSuite(WarTest.class);
  }


  /*
   * testName: testBasicWarDeployment
   * assertion:  verify basic deployment of an EJB JAR.
   * test Strategy:  Navigate to WAR Applications.
   *      Add a new resource.  Verify the resource was successfully
   *      deployed.  Undeploy the archive.
   *
   */
  public void testBasicWarDeployment()
          throws IOException, HtmlElementNotFoundException, ActionNotAvailableException
  {

    final String DEPLOYABLE_NAME = BASIC_WAR;

    String filePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;

    try {
      deployWAR( filePath );

      // Check the success message.
      String expectedMessage = "Resource "+DEPLOYABLE_NAME+" created successfully";
      checkClientAndServerMessages(expectedMessage, expectedMessage, false);

      // Use JMX to assert that the WAR really did deploy successfully
      assertTrue("WAR was not deployed according to JMX", isWarDeployed(DEPLOYABLE_NAME));

      // use HtmlUnit to test the newly deployed war in a new WebClient session
      // note that I have full access to the FacesContext and the previous request
      //Thread.sleep(3000); // Give JBoss some time to launch the webapp.
      HttpServletRequest request =
         (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
      int port = request.getLocalPort();
      WebClient webClient = new WebClient();
      final String testPageUrl = "http://localhost:" + port + "/hellothere/hello.jsp";
      HtmlPage page = (HtmlPage)webClient.getPage(testPageUrl);
      assertTrue( "Test page '"+testPageUrl+"' should contain 'HELLO WORLD'. Instead, it is: "+page.asText(),
              page.asText().contains("HELLO WORLD"));

    }
    finally {
      // Undeploy the WAR
      undeployWAR(DEPLOYABLE_NAME);
    }
  }



  /*
    <jboss-web>
      <context-root>test</context-root>
      <virtual-host>snert.home.pilhuhn.de</virtual-host>
      <virtual-host>snert.home.bsd.de</virtual-host>
    </jboss-web>
   */
  public void testWarWithVirtualHosts()
          throws IOException, EmbJoprTestException
  {

    final String DEPLOYABLE_NAME = WAR_VIRTUAL_HOSTS;

    final String VHOST_1 = "snert.home.pilhuhn.de";
    final String VHOST_2 = "snert.home.bsd.de";


    String filePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;

    try {
      ejtt.deployment.deployViaEmbJopr(APP_TYPE, filePath);

      // Check the success message.
      String expectedMessage = "Resource "+DEPLOYABLE_NAME+" created successfully!";
      checkClientAndServerMessages(expectedMessage, expectedMessage, false);

      ejtt.deployment.waitActivelyForDeployment(APP_TYPE, DEPLOYABLE_NAME,
              DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES);



      /*
      // Use HtmlUnit to test the newly deployed war in a new WebClient session.
      // Commented out - localhost is not in the list of virtual hosts, thus the web app is not accessible there.
      int port = ejtt.getEmbJoprPort();
      WebClient webClient = new WebClient();
      //webClient.addRequestHeader("Host", VHOST_1);
      HtmlPage page = (HtmlPage)webClient.getPage("http://localhost:" + port + "/test/index.jsp");
      assertTrue(page.asText().contains("HELLO WORLD"));
      /**/


      /*
      // Get IP Address
      InetAddress addr = InetAddress.getLocalHost();
      byte[] ip = addr.getAddress();
      String host = String.format("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
      //HttpConnection hc = new HttpConnection( host, ejtt.getEmbJoprPort() );
      HttpConnection hc = new HttpConnection( host, VHOST_1, ejtt.getEmbJoprPort(), Protocol.getProtocol("http") );
      hc.open();
      // Lack of Commons HttpClient documentation.
      /**/

      /* This works,  but HTTP request
           GET /test/index.jsp
           Host: snert.home.bsd.de
       * returns 404.

      // Send a raw HTTP request to validate the virtual host functionality.
      InetAddress ip = ejtt.getEmbJoprIpAddress();
      log.info("Sending HTTP request to "+ip.toString()+" at port "+ejtt.getEmbJoprPort());
      Socket socket = new Socket(ip, ejtt.getEmbJoprPort());
      String httpRequest = "GET /test/index.jsp HTTP/1.1\nHost: "+VHOST_1+"\n\n";
      socket.getOutputStream().write( httpRequest.getBytes() );

      BufferedInputStream inputStream =  new BufferedInputStream(socket.getInputStream());
      StringBuilder sb = new StringBuilder(4096);

      int read;
      byte data[] = new byte[4096];
      do {
        read = inputStream.read(data);
        if( -1 == read )
          break;
        sb.append( new String(data) );
      }while( true );

      String responseText = sb.toString();
      log.debug("Vhost test web app response:\n"+responseText);
      assertTrue( responseText.contains("HELLO WORLD") );
      /**/




      // Check that the virtual hosts are listed in EmbJopr.

      // Expand the VHosts node and click it.
      ejtt.navTree.getNodeByLabel(NAV_JBOSS_WEB).getArrowLink().click();
      ejtt.navTree.waitUntilNodeLoadedByAjax(NAV_VIRTUAL_HOSTS, 1000, 6);
      ejtt.navTree.getNodeByLabel(NAV_VIRTUAL_HOSTS).getLabelLink().click();


      // Check that vhosts from the WARare listed.
      ContentTableRow row = ejtt.tabMenu.getTabContentBox().
              getDefaultTable().getFirstRowContainingLink(VHOST_1);
      if( null == row )
        throw new EmbJoprTestException("Vhost '"+VHOST_1+"' is not listed.", this);

      row = ejtt.tabMenu.getTabContentBox().
              getDefaultTable().getFirstRowContainingLink(VHOST_2);
      if( null == row )
        throw new EmbJoprTestException("Vhost '"+VHOST_2+"' is not listed.", this);

      // Expand the Virtual Hosts node
      ejtt.navTree.getNodeByLabel(NAV_VIRTUAL_HOSTS).getArrowLink().click();
      ejtt.navTree.getNodeByLabel(VHOST_1, true); // Throws if not found
      ejtt.navTree.getNodeByLabel(VHOST_2, true); // Throws if not found
     

    }
    finally {
      try {
        // Undeploy the app.
        ejtt.deployment.undeployViaEmbJopr(APP_TYPE, DEPLOYABLE_NAME);
      }catch( EmbJoprTestException ex ){
        log.debug("Exception during undeploy - "+ex.getMessage());
      }
    }
  }





  /**
   * Tries to deploy a invalid WAR (with invalid descriptor)
   * and checks that EmbJopr rejects this deployment.
   */
  public void testBadWarRedeploy() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = AppConstants.WAR_FILENAME_MALFORMED_APP;

    try {

      String filePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
      deployWAR(filePath);

      checkClientAndServerMessages("Failed to create Resource", "Failed to create Resource", true);
    }
    finally {
      try {
        undeployWAR(DEPLOYABLE_NAME);
      } catch (Exception ex) {
        log.info("Caught expected exception during undeploy: "+ex);
      }
    }
  }






  /**
   * Various ways to navigate to a WAR application:
   * Nav tree, apps listing, WARs listing.
   */
  public void testNavigationToWar() throws IOException, HtmlElementNotFoundException, ActionOutOfSyncException, ActionNotAvailableException, EmbJoprTestException, InterruptedException, ActionOutOfSyncException
  {

    // JBossAS Servers node
    NavTreeNode nodeServers = ejtt.getNavTree().getNodeByLabel("JBossAS Servers");
    nodeServers.click();

    {
      String headerText = "JBossAS Server";
      String jbossConfig = ejtt.getJBossConfig();

      assertTrue("Page doesn't contain the header: "+headerText,
              client.getPageAsText().contains(headerText));

      assertTrue("EmbJopr should list at least one server (the one it is running on)" +
              " and that should be in the UP sate.",
              client.getPageAsText().contains("UP"));
      // Check whether the server is listed. If not, Exception is thrown.
      ContentTableRow row =
              ejtt.getTabMenu().getTabContentBox().getTableUnderHeader(LABEL_AS_SERVERS_SUMMARY)
              .getFirstRowContainingLink( String.format(AS_NODE_NAME_FORMAT, jbossConfig)); // "JBoss EAP 5 (...)");
      // Click the server link
      //HtmlAnchor link row.getLinkByLabel("JBoss App Server:default");
      Node firstLink = row.getCellByColumnName("Name").getElementsByTagName("a").item(0);
      if( null == firstLink || !(firstLink instanceof HtmlAnchor) )
        throw new HtmlElementNotFoundException("Can't find the server link.");

      ((HtmlAnchor)firstLink).click();
    }

    // JBoss App Server:${config} node
    {
      String pageText = client.getPageAsText();

      String jbossConfig = ejtt.getJBossConfig();
      String headerText = String.format(AS_NODE_NAME_FORMAT, jbossConfig);
      assertTrue("Page doesn't contain the header: "+headerText,
              pageText.contains(headerText));

      headerText = "General Properties";
      assertTrue("Page doesn't contain the header: "+headerText,
              pageText.contains(headerText));

      // TODO: This page reports "Version:5.0 CR1" - EMBJOPR-77

      ejtt.getNavTree().getNodeByLabel("Applications").click();

    }


    // Applications node
    {

      ejtt.getTabMenu().clickTab("Summary");

      // TODO: Pagination options: EMBJOPR-78
      // resourceDataScroller.xhtml, TableManager.java, "pageSizes".


      // There's at least one Application with State == UP.
      //ContentTable table = ejtt.getTabMenu().getTabContentBox().getTableUnderHeader("Different types of Applications");
      HtmlTable tableElement = (HtmlTable)client.getElement("categorySummaryForm:dataTable");
      ContentTable table = ejtt.getTabMenu().getTabContentBox().getTable(tableElement);
      ContentTableRow row = table.getFirstRowContainingText("UP");

      // Go further - try to click on any Application that is up.
      HtmlAnchor link = row.getFirstLinkFromColumn("Name");
      link.click();
    }


    {
      // Go back to applications Sumary screen.
      ejtt.getNavTree().getNodeByLabel("Applications").click();
    }


    // Concrete appliction node.
    {

      final String DEPLOYABLE_NAME = BASIC_WAR_02;

      // Deploy the WAR.
      String filePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
      deployWarRepeatedly( filePath );

      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();

      // Get to the app through listing.
      log.debug("Looking for row with: "+DEPLOYABLE_NAME);

      // Commented out: we would have to click trough pages.
      //ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      ContentTableRow row = ejtt.getTabMenu().getTabContentBox()
              .findLinkRowInDataTableUsingPagination(DEPLOYABLE_NAME);

      assertTrue("Page doesn't list "+DEPLOYABLE_NAME+" in Summary tab.", row != null );

       // Go to the summary through listed item.
      row.getLinkByLabel(DEPLOYABLE_NAME).click();
      /**/

     
      // Other way to get to app: through nav tree.
      ejtt.getNavTree().getNodeArrow(NAV_WAR).click();
      ejtt.navTree.waitUntilNodeLoadedByAjax(DEPLOYABLE_NAME, 500, 15);
      ejtt.navTree.getNodeByLabel(DEPLOYABLE_NAME).click();
      /**/


      // Check that we have the summary tab for the selected WAR.
      assertTrue( "WAR name "+DEPLOYABLE_NAME+" not found in the content box.",
        ejtt.getTabMenu().getTabContentBox().getElement().getTextContent().contains(DEPLOYABLE_NAME) );

      // Go to the summary through nav tree node.
      NavTreeNode appNode = ejtt.getNavTree().getNodeByLabel(NAV_WAR);
      if( !appNode.isExpanded() ){
        log.info("Expanding.");
        appNode.getArrowLink().click();
        Thread.sleep(2000);
      }
      ejtt.getNavTree().getNodeByLabel(DEPLOYABLE_NAME).click();
      // Check that we have the summary tab for the selected WAR.
      ejtt.getTabMenu().getTabContentBox().getElement().getTextContent().contains(DEPLOYABLE_NAME);

      undeployWAR(DEPLOYABLE_NAME);

    }


  }// testNavigationToWar()







  /**
   * Tests the values shown in the Summary tab of WAR.
   *
   *  Was failing because of:  EMBJOPR-110 (missing / at the beginning of the path)
   */
  public void testWarSummaryTab() throws EmbJoprTestException, IOException, Exception {

    final int DEPLOY_TIMEOUT_SEC = 120;

    final String DEPLOYABLE_NAME = BASIC_WAR_03;

    // Deploy the WAR
    String appFilePath = System.getProperty(SYSPROP_TESTDATA_DIR) + "/war/"+DEPLOYABLE_NAME;
    deployWarRepeatedly( appFilePath );

    try {

      // Wait until the WAR appears...
      // Should be present when the page is reloaded.
      // TODO: Replace with waitUntil~()
      new ActiveConditionChecker(new DescribedCondition("WAR appears in Summary tab list") {
        public boolean isTrue() throws Exception {
          // Refresh, then check.
          ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
          ContentTableRow appRow = ejtt.getDefaultContentTable().findFirstRowContainingLink(DEPLOYABLE_NAME);
          return null != appRow;
        }
      }).dumpPageOnTimeout(this).throwOnTimeout().waitWithTimeout(2000, 5);
      /**/


      ContentTableRow appRow = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);

      // Wait until the Status is "UP".
      // TODO: Replace with ActiveConditionChecker.
      int maxLoops = DEPLOY_TIMEOUT_SEC;
      do {
        String statusText = appRow.getCellTextByColumnName("Status");
        log.debug("WAR Status: "+statusText);
        if( "UP".equals(statusText) )
          break;

        // Refresh page after 1 second.
        ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
        appRow = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);

        // We don't want an infinite loop by mistake.
        if( maxLoops-- <= 0 ){
          throw new EmbJoprTestException("WAR "+DEPLOYABLE_NAME+" not UP after "+DEPLOY_TIMEOUT_SEC+" seconds.");
        }
      } while( true );

      // FAILS because of EMBJOPR-80.
      appRow.getLinkByLabel(DEPLOYABLE_NAME).click();


      // Check the values in info table(s)

      // General Properties
      HtmlTable genpropTable = ejtt.getTabMenu().getTabContentBox().getTableUnderHeader("General Properties").getElement();
      ContentInfoTable infoTable = ejtt.getContentInfoTable( genpropTable );
      Properties props = infoTable.getProperties();
      log.info("General Properties: "+props.toString());

      assertEquals(DEPLOYABLE_NAME, props.getProperty("Name").trim());
      //assertEquals("?", props.getProperty("Version")); // TODO: Where does RHQ get the version from?


      // Resource Traits
      infoTable = ejtt.getContentInfoTable(
              ejtt.getTabMenu().getTabContentBox().getTableUnderHeader("Traits").getElement() );
      props = infoTable.getProperties();
      log.info("Traits: "+props.toString());
      log.debug("Path: "+props.getProperty("Path"));///


      String path = ejtt.getDeployDir()+"/"+DEPLOYABLE_NAME;
      path = path.replace("/", System.getProperty("file.separator"));
      assertEquals(path, props.getProperty("Path").trim());
      assertEquals("no", props.getProperty("Exploded?").trim());
     
     
      // Metrics Summary - currently hidden.
      ContentTable metricsTable = ejtt.getTabMenu().getTabContentBox().findTableUnderHeader("Numeric Metrics");
      if( null == metricsTable )
        log.info("Metrics table not present.");
      else{
        HtmlTable summaryTable = metricsTable.getElement();
        infoTable = ejtt.getContentInfoTable(summaryTable);
        // (nothing here yet)
      }
    }
    finally {
      ejtt.deployment.undeployViaEmbJopr(APP_TYPE, DEPLOYABLE_NAME);
    }

  }// testWarSummary()







  /**
   * Changes WAR configuration, and checks whether the changes were saved.
   *
   * FAILS because Config tab is disabled.
   */
  public void DISABLEDtestWarConfigurationTab() throws IOException, EmbJoprTestException, HtmlElementNotFoundException, Exception {

    final String DEPLOYABLE_NAME = BASIC_WAR_04;

    // Deploy the WAR.
    String filePath = ejtt.getTestDataDir() +"/war/"+ DEPLOYABLE_NAME;
    deployWarRepeatedly( filePath );

    try {

      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME, DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Navigate to the Configuration tab
      ContentTableRow appRow = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      appRow.getLinkByLabel(DEPLOYABLE_NAME).click();

      Page prevPage = client.getContentPage();
      ejtt.tabMenu.clickConfigurationTab();
      assertNotSame("We should move to other page after clicking the Config tab.",
              prevPage, client.getContentPage());

      // Read properties.
      Properties props = new Properties();
      String propsFilePath = ejtt.getTestDataDir()+"/war/"+"war-conf-basic.properties";
      props.load(new FileInputStream( propsFilePath ));


      // Set the configuration options and Save
      fillOutForm(props);
      //ejtt.getTabMenu().getTabContentBox().getButtonByLabel("Save");
      ejtt.getClickableByID("resourceConfigurationForm:saveButton").click();


      // Check whether the properties were saved.
      ejtt.tabMenu.clickConfigurationTab();

      // TODO: We don't see the success message! EMBJOPR-89
      //checkClientAndServerMessages("successfully", "successfully", false);

      // FAILS because some of the values are read-only.  EMBJOPR-96
      checkForm(props);

      // TODO: Finish when the properties are marked read-only.

    }
    finally {
      undeployWAR(DEPLOYABLE_NAME);
    }

  }





  /**
   * Changes WAR configuration, and verifies that the changes were NOT saved.
   *
   * Was failing because some of the values are read-only.  EMBJOPR-96
   * FAILS because Config tab is disabled.
   */
  public void DISABLEDtestWarConfigurationTabCancel() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = BASIC_WAR_05;

    // Deploy the WAR.
    String filePath = ejtt.getTestDataDir() +"/war/"+ DEPLOYABLE_NAME;
    deployWarRepeatedly( filePath );

    try {

      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME,
              DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Navigate to the Configuration tab
      ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      row.getLinkByLabel(DEPLOYABLE_NAME).click();

      Page prevPage = client.getContentPage();
      ejtt.tabMenu.clickConfigurationTab();
      assertNotSame("We should move to other page after clicking the Config tab.",
              prevPage, client.getContentPage());


      // Load properties (we will use their names).
      Properties propsToSet = new Properties();
      String propsFilePath = ejtt.getTestDataDir()+"/war/"+"war-conf-basic.properties";
      propsToSet.load(new FileInputStream( propsFilePath ));

      // Get the current properties.
      Properties propsOriginal = getFormPropertiesValues( propsToSet );


      // Set the configuration options and CANCEL
      fillOutForm( propsToSet );
      ejtt.getClickableByID("resourceConfigurationForm:cancelButton").click();


      // TODO: We should get back to Conf tab automatically: EMBJOPR-100
      ejtt.tabMenu.clickConfigurationTab();

      // Now check whether the values are the same as before editing.
      checkForm( propsOriginal );

    }
    finally {
      undeployWAR(DEPLOYABLE_NAME);
    }

  }




  /**
   * Redeploys WAR, using WAR's Content tab upload form.
   *
   * Was failing because of:  EMBJOPR-109
   * FAILS: EMBJOPR-172
   */
  public void testWarRedeployment() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = BASIC_WAR_06;

    // Deploy the WAR.
    String appFilePath = ejtt.getTestDataDir() +"/war/"+ DEPLOYABLE_NAME;
    deployWarRepeatedly( appFilePath );

    try {

      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME, DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Navigate to the Configuration tab
      ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      row.getLinkByLabel(DEPLOYABLE_NAME).click();
      ejtt.tabMenu.clickContentTab();

      String xPath = ".//table//input[@type='file']";
      HtmlFileInput fileInput = ejtt.tabMenu.getTabContentBox().getElement().getFirstByXPath(xPath);
      fileInput.setValueAttribute(appFilePath);
      xPath = ".//table//input[@type='submit']";
      HtmlSubmitInput submit = ejtt.tabMenu.getTabContentBox().getElement().getFirstByXPath(xPath);
      submit.click();

    }
    finally {
      try {
        DebugUtils.writeFile("target/redeployment.html", client.getPageAsText());///
        undeployWAR(DEPLOYABLE_NAME); // EMBJOPR-109 here
      }catch( Exception ex ){
        log.error("Exception caught in finally: "+ex.getMessage(), ex);
      }
    }

  }


  /**
   * Deploys the WAR, undeploys it and deploys again.
   * All these actions are done using EmbJopr.
   *
   * Fails because of EMBJOPR-125
   */
  public void testWarDeployUndeployDeploy() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = BASIC_WAR_DUD;


    // Deploy the WAR.
    String appFilePath = ejtt.getTestDataDir() +"/war/"+ DEPLOYABLE_NAME;
    deployWarRepeatedly( appFilePath );

    try {

      // Undeploy.
      log.info("Undeploying "+DEPLOYABLE_NAME);
      undeployWAR(DEPLOYABLE_NAME);
      //DebugUtils.writeFile("target/DUD-undeploy.html", client.getPageAsText());///
      assertFalse( "Deployable "+DEPLOYABLE_NAME+" shouldn't be listed as deployed after undeployment.",
              ejtt.deployment.isDeployedAccordingToEmbJopr(DeployableTypes.WAR, DEPLOYABLE_NAME, false) );

      // Deploy the same war again.
      log.info("Deploying "+DEPLOYABLE_NAME+" again.");
      deployWAR( appFilePath );
      //DebugUtils.writeFile("target/DUD-deploy.html", client.getPageAsText());///
      // EMBJOPR-125 here.
      assertTrue( "Deployable "+DEPLOYABLE_NAME+" should be listed as deployed after deployment.",
              ejtt.deployment.isDeployedAccordingToEmbJopr(DeployableTypes.WAR, DEPLOYABLE_NAME, false) );

    }
    finally {
      try {
        DebugUtils.writeFile("target/testDeployUndeployDeploy-finally.html", client.getPageAsText());///
        undeployWAR(DEPLOYABLE_NAME);
      }catch( Exception ex ){
        log.error("Exception caught in finally: "+ex.getMessage(), ex);
      }
    }

  }



  /**
   * Deploys the WAR, undeploys it and deploys again.
   * All these actions are done using EmbJopr.
   */
  public void testWarDeployUndeployDeployRetryOnErrors() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = BASIC_WAR_DUD_RETRY;


    // Deploy the WAR.
    String appFilePath = ejtt.getTestDataDir() +"/war/"+ DEPLOYABLE_NAME;
    deployWarRepeatedly( appFilePath );

    try {

      // Undeploy.
      log.info("Undeploying "+DEPLOYABLE_NAME);
      undeployWAR(DEPLOYABLE_NAME); // EMBJOPR-109 here
      assertFalse( "Deployable "+DEPLOYABLE_NAME+" shouldn't be listed as deployed after undeployment.",
              ejtt.deployment.isDeployedAccordingToEmbJopr(DeployableTypes.WAR, DEPLOYABLE_NAME, false) );

      // Deploy the same war again.
      log.info("Deploying "+DEPLOYABLE_NAME+" again.");
      deployWarRepeatedly( appFilePath );
      assertTrue( "Deployable "+DEPLOYABLE_NAME+" should be listed as deployed after deployment.",
              ejtt.deployment.isDeployedAccordingToEmbJopr(DeployableTypes.WAR, DEPLOYABLE_NAME, false) );

    }
    finally {
      try {
        DebugUtils.writeFile("target/testDeployUndeployDeployRetryOnErrors-finally.html", client.getPageAsText());///
        undeployWAR(DEPLOYABLE_NAME); // EMBJOPR-109 here
      }catch( Exception ex ){
        log.error("Exception caught in finally: "+ex.getMessage(), ex);
      }
    }

  }



  /**
   * Deploys exploded WAR and checks whether it is reported as exploded.
   *
   * DISABLED - Badly written test, to be fixed. TODO: Hot-deploy
   */
  public void DISABLEDtestUnzippedWarReportedAsExploded() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = BASIC_WAR_07;

    // Deploy the WAR.
    String WARFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
    deployWarRepeatedly( WARFilePath );

    try {
      // Wait for WAR to be deployed and UP
      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME, DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Click the WAR link
      ejtt.getTabMenu().getTabContentBox().getFirstTable()
              .getFirstRowContainingText(DEPLOYABLE_NAME).getFirstLinkFromColumn("Name").click();

      DebugUtils.writeFile("target/res_traits.html", client.getPageAsText());///

      ContentTable table = ejtt.getTabMenu().getTabContentBox().getTableUnderHeader("Resource Traits");
      ContentInfoTable infoTable = ejtt.getTabMenu().getTabContentBox().getContentInfoTable(table.getElement());
      Properties props = infoTable.getProperties();
      log.info("Resource Traits: "+props.toString());
      log.debug("Exploded?: "+props.getProperty("Exploded?"));

      assertEquals("'Exploded?' should be 'yes'", "yes", props.getProperty("Exploded?")/*.toLowerCase()*/ );

    }
    finally {
      undeployWAR(DEPLOYABLE_NAME);
    }

  }




  /**
   * Checks WAR metrics tab.
   *
   * FAILS because of:  EMBJOPR-110 (missing / at the beginning of the path)
   */
  public void testWarMetricsTab() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = BASIC_WAR_08;

    // Deploy the WAR.
    String WARFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
    deployWarRepeatedly( WARFilePath );

    try {

      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME, DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Navigate to the Metrics tab
      ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      row.getLinkByLabel(DEPLOYABLE_NAME).click();
      ejtt.tabMenu.clickMetricsTab();

      // Resource Traits

      // Check the Path.
      HtmlTable tbl = ejtt.getTabMenu().getTabContentBox().
              getTableUnderHeader("Traits").getElement();
      ContentInfoTable infoTable = ejtt.getContentInfoTable( tbl );
      Properties props = infoTable.getProperties();

      log.debug("Traits: "+ props.toString());

      String path = ejtt.getDeployDir()+"/"+DEPLOYABLE_NAME;
      path = path.replace("/", System.getProperty("file.separator"));
      assertEquals(path, props.getProperty("Path").trim());


    }
    finally {
      undeployWAR(DEPLOYABLE_NAME);
    }

  }


  /**
   * Changes WAR configuration, and checks whether the changes were saved.
   *
   * FAILS because some of the values are read-only.  EMBJOPR-96
   */
  public void testWarMetricsTabRefreshButton() throws IOException, EmbJoprTestException, HtmlElementNotFoundException, Exception {

    final String DEPLOYABLE_NAME = BASIC_WAR_09;

    // Deploy the WAR.
    String WARFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
    deployWarRepeatedly( WARFilePath );

    try {

      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME,
              DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Navigate to the Metrics tab
      ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      row.getLinkByLabel(DEPLOYABLE_NAME).click();
      ejtt.tabMenu.clickMetricsTab();

      // Click the Refresh button.
      // Can this change to submit? Perhaps set an ID and use ejtt.getClickableById().
      ejtt.tabMenu.getTabContentBox().getButtonInputByLabel("Refresh").click();

      // Check that we are still on the right tab.
      assertTrue("Metrics tab is active", ejtt.tabMenu.isTabActive("Metrics") );
      assertTrue("Page contains WAR name", client.getPageAsText().contains(DEPLOYABLE_NAME) );
      assertTrue("Page contains 'Refresh'", client.getPageAsText().contains("Refresh") );

    }
    finally {
      undeployWAR(DEPLOYABLE_NAME);
    }

  }


  /**
   * Deploys an exploded WAR application.
   *
   * FAILS when undeploying, because:
   *
org.jboss.jopr.jsfunit.exceptions.EmbJoprTestException: Couldn't delete following files:
  /home/ondra/work/JOPRembedded/embjopr-svn-trunk/jsfunit/target/jboss5x/deploy/unpacked-web1.war

  at org.jboss.jopr.jsfunit.util.EmbJoprTestToolkit$Deployment.deleteDirectory(EmbJoprTestToolkit.java:1662)
  at org.jboss.jopr.jsfunit.util.EmbJoprTestToolkit$Deployment.deleteFromDeployDir(EmbJoprTestToolkit.java:1652)
  at org.jboss.jopr.jsfunit.as5.WarTest.testDeployUnpackedWar(WarTest.java:663)
   *
   * TODO:  Catch exceptions in finally and log them only (in all tests),
   *        to get the eventual real exception from the try block.
   *
   * TODO:  Think up how to simulate hot-undeploy.
   *        Should we rename it to other dir and then delete?
   *
   *        Perhaps it just still didn't process the deployed war when trying to undeploy?
   *          "Condition 'WAR unpacked-web1.war appears in embjopr as deployed' not satisfied,
   *           0 retries left. Leaving the wait loop."
   *        Should we wait more? Or is it caused by failures of some previous tests?
   *
   */
  public void testDeployUnpackedWar() throws IOException, EmbJoprTestException {

    final String DEPLOYABLE_NAME = WAR_UNPACKED;

    // Deploy the unpacked WAR.
    // We have to use hotdeploy - can't upload a directory.
    //ejtt.deployment.unzipToDeployDir("war/"+WAR_UNPACKED_ZIP, "");
    String archivePath = ejtt.getTestDataDir()+"/war/"+WAR_UNPACKED_ZIP;
    String tempDir = ejtt.getTempDir();
    String destDir = ejtt.getDeployDir();

    log.info("Unzipping "+archivePath+" to "+tempDir);
    ejtt.deployment.unzipArchive( archivePath, tempDir );

    log.info("Moving "+tempDir+"/"+WAR_UNPACKED+" to "+destDir+"/"+WAR_UNPACKED);
    ejtt.deployment.moveDir(tempDir+"/"+WAR_UNPACKED, destDir+"/"+WAR_UNPACKED);
   


    try {
      // Loop, wait for the app to appear.
      log.info("Waiting for WAR to appear.");
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, WAR_UNPACKED,
            DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);


      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();

      //ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(WAR_UNPACKED);
                        if( !  ejtt.deployment.isDeployedAccordingToEmbJopr(APP_TYPE, WAR_UNPACKED)  )
                                throw new EmbJoprTestException("Unpacked hotdeployed war not found: "+WAR_UNPACKED, this);



      // TODO: Finish

      // TODO: Check whether Exploded?:  yes.  EMBJOPR-95

      // TODO: DeploymentUtils, DeployableTypes, isAvailable enum inner classes

      // TODO: Preliminary test - check system properties, their validity, java version, etc.
    }
    finally {
      // Delete the WAR dir.
      ejtt.deployment.deleteFromDeployDir(WAR_UNPACKED);
    }
  }




  /**
   * Stops and starts the WAR using buttons in the Control tab, and checks
   * whether it's really stopped and started by sending HTTP requests.
   */
  public void testStopAndStartWar() throws IOException, EmbJoprTestException
  {
    final String DEPLOYABLE_NAME = BASIC_WAR_STOPSTART;

    // Get the HTTP port and the URL of the test page.
    HttpServletRequest tmpRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    int port = tmpRequest.getLocalPort();
    String context = StringUtils.chomp( DEPLOYABLE_NAME, ".war" ); // Eventually remove ".war" suffix.
    String testPageUrl = "http://localhost:"+port+"/"+context+"/hello.jsp";

    // Create web client we will use to check the web app.
    WebClient webClient = new WebClient();
    // We'll get 404 after stopping the app.
    webClient.setThrowExceptionOnFailingStatusCode(false);
    HtmlPage page;


    // Deploy the WAR.
    String WARFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
    deployWarRepeatedly( WARFilePath );

    try {

      // Wait until app is UP
      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME,
              DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Assert that the app is running.
      page = (HtmlPage)webClient.getPage(testPageUrl);
      assertEquals( "HTTP status of "+testPageUrl+" should be 200", 200, page.getWebResponse().getStatusCode() );
      assertTrue("Page should contain 'HELLO WORLD'", page.asText().contains("HELLO WORLD"));

      // Refresh the page several times to increase the counter.
      page = (HtmlPage) page.refresh();
      page = (HtmlPage) page.refresh();

      // Get the counter number.
      String count1text = ( (HtmlElement) page.getBody().getHtmlElementById("count") ).getTextContent();
      Integer count1 = NumberUtils.createInteger( count1text );



      // Navigate to the web app, then to it's Control tab.
      ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      row.getLinkByLabel(DEPLOYABLE_NAME).click();
      ejtt.getTabMenu().clickControlTab();

      // Click the Stop button.
      ejtt.tabMenu.getTabContentBox().getButtonInputByLabel("Stop").click();

      // Check the latest message.
      ejtt.operations.waitActivelyForOperationToFinish("Stop", 1500, 5);
      assertTrue( ejtt.getTabMenu().getTabContentBox().getOperationsHistoryTable().wasLastOperationSuccesful() );



      // Assert that the app is stopped.
      page = (HtmlPage)webClient.getPage(testPageUrl);
      assertTrue( 200 != page.getWebResponse().getStatusCode() );


      // Click the Start button.
      ejtt.tabMenu.getTabContentBox().getButtonInputByLabel("Start").click();

      // Wait for the op to finish and check the final status.
      ejtt.operations.waitActivelyForOperationToFinish("Start", 1500, 5);
      assertTrue( ejtt.getTabMenu().getTabContentBox().getOperationsHistoryTable().wasLastOperationSuccesful() );


      // Assert that the app is running.
      page = (HtmlPage)webClient.getPage(testPageUrl);
      assertTrue( 200 == page.getWebResponse().getStatusCode() );
      assertTrue(page.asText().contains("HELLO WORLD"));

      // Get the counter number.
      String count2text = ( (HtmlElement) page.getBody().getHtmlElementById("count") ).getTextContent();
      Integer count2 = NumberUtils.createInteger( count2text );

      assertTrue( "Counter is reset upon app restart, thus should be lower after. " +
              "Old: "+count1text+" New: "+count2text, count1 > count2 );


    }
    finally {
      undeployWAR(DEPLOYABLE_NAME);
    }
  }


  /**
   * Restarts the WAR using button in the Control tab,
   * and checks whether it's really restarted by checking whether JSP variable was reset.
   *
   * FAILS: EMBJOPR-172
   */
  public void testRestartWar() throws IOException, EmbJoprTestException
  {
    final String DEPLOYABLE_NAME = BASIC_WAR_RESTART;

    // Get the HTTP port and the URL of the test page.
    HttpServletRequest tmpRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    int port = tmpRequest.getLocalPort();
    String context = StringUtils.chomp( DEPLOYABLE_NAME, ".war" ); // Eventually remove ".war" suffix.
    String testPageUrl = "http://localhost:"+port+"/"+context+"/hello.jsp";

    // Create web client we will use to check the web app.
    WebClient webClient = new WebClient();
    webClient.setThrowExceptionOnFailingStatusCode(false);
    HtmlPage page;


    // Deploy the WAR.
    String WARFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
    deployWarRepeatedly( WARFilePath );

    try {

      // Wait until app is UP
      ejtt.getNavTree().getNodeByLabel(NAV_WAR).click();
      ejtt.deployment.waitActivelyForDeployment(DeployableTypes.WAR, DEPLOYABLE_NAME,
              DEPLOY_UP_STATE_WAIT_CHECK_INTERVAL, DEPLOY_UP_STATE_WAIT_CHECK_RETRIES, this);

      // Assert that the app is running.
      page = (HtmlPage)webClient.getPage(testPageUrl);
      assertEquals( "HTTP status of "+testPageUrl+" should be 200", 200, page.getWebResponse().getStatusCode() );
      assertTrue("Page should contain 'HELLO WORLD'", page.asText().contains("HELLO WORLD"));

      // Refresh the page several times to increase the counter.
      page = (HtmlPage) page.refresh();
      page = (HtmlPage) page.refresh();

      // Get the counter number.
      String count1text = ( (HtmlElement) page.getBody().getHtmlElementById("count") ).getTextContent();
      Integer count1 = NumberUtils.createInteger( count1text );



      // Navigate to the web app, then to it's Control tab.
      ContentTableRow row = ejtt.getDefaultContentTable().getFirstRowContainingLink(DEPLOYABLE_NAME);
      row.getLinkByLabel(DEPLOYABLE_NAME).click();
      ejtt.getTabMenu().clickControlTab();

      // Click the Restart button.
      ejtt.tabMenu.getTabContentBox().getButtonInputByLabel("Restart").click();

      // Wait for the op to finish and check the final status.
      ejtt.operations.waitActivelyForOperationToFinish("Restart", 1500, 5);
      assertTrue( ejtt.getTabMenu().getTabContentBox().getOperationsHistoryTable().wasLastOperationSuccesful() );
     

      // Assert that the app is running.
      page = (HtmlPage)webClient.getPage(testPageUrl);
      assert( 200 == page.getWebResponse().getStatusCode() );
      assertTrue(page.asText().contains("HELLO WORLD"));

      // Get the counter number.
      String count2text = ( (HtmlElement) page.getBody().getHtmlElementById("count") ).getTextContent();
      Integer count2 = NumberUtils.createInteger( count2text );

      assertTrue( "Counter is reset upon app restart, thus should be lower after. " +
              "Old: "+count1text+" New: "+count2text, count1 > count2 );

    }
    finally {
      try {
        undeployWAR(DEPLOYABLE_NAME);
      } catch( Exception ex ){
        DebugUtils.writeFile("target/testRestartWar-undeploy.html", client.getPageAsText());///
        log.debug("Cathed an expected exception when trying to undeploy "+DEPLOYABLE_NAME+": "+ex );
      }
    }
  }




  /**
   * Deploys a WAR with bad farchive extension (.zip)
   * and checks whether EmbJopr reports deployment failure.
   */
  public void testDeployWarWithIncorrectExtension() throws IOException, EmbJoprTestException
  {
    final String DEPLOYABLE_NAME = WAR_UNPACKED_ZIP;


    // Deploy the WAR.
    String WARFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;
    deployWAR( WARFilePath );

    try {

      assertTrue( "There should be a faces message informing about failure.",
              server.getFacesMessages().hasNext() );

      assertTrue( "The failure message should have ERROR severity.",
              FacesMessage.SEVERITY_ERROR == server.getFacesMessages().next().getSeverity() );

      assertTrue( "Page should contain 'Incorrect extension' string (deployer message).",
        client.getPageAsText().contains("Incorrect extension") );

    }
    finally {
      // Undeploy for the case it was (errorneously) deployed.
      try {
        undeployWAR(DEPLOYABLE_NAME);
      } catch( Exception ex ){
        log.debug("Cathed an expected exception when trying to undeploy "+DEPLOYABLE_NAME+": "+ex );
      }
    }
  }


  /**
   * Deploys a WAR and checks that it doesn't appear under the Embedded Web App's node.
   */
  public void testStandaloneWarDoesntAppearInEmbeddedWars() throws IOException, EmbJoprTestException
  {
    final String DEPLOYABLE_NAME = BASIC_WAR_10;


    // Deploy the WAR.
    String appFilePath = ejtt.getTestDataDir() + "/war/"+DEPLOYABLE_NAME;

    try {
     
      deployWAR( appFilePath );

      ejtt.navTree.getNodeByLabel(DeployableTypes.EMB_WAR.getNavTreeLabel()).getLabelLink().click();

      assertFalse( ejtt.deployment.isDeployedAccordingToEmbJopr(DeployableTypes.EMB_WAR, DEPLOYABLE_NAME, false) );

    }
    finally {
      // Undeploy for the case it was (errorneously) deployed.
      try {
        undeployWAR(DEPLOYABLE_NAME);
      } catch( Exception ex ){
        log.debug("Cathed an expected exception when trying to undeploy "+DEPLOYABLE_NAME+": "+ex );
      }
    }
  }


  /**
   * Hot-deploy several WARs and check that after some time, all of them are deployed and UP.
   */
  public void testWarHotDeployManyWarsAtOnce() throws IOException, EmbJoprTestException
  {
    final String TEMP_DEPLOYABLE_NAME = BASIC_WAR_MULTI_HOTDEPLOY;
    final int APP_COPIES = 25;

    final String fileNamePattern = "multiHotdeploy%d"+APP_TYPE.getExtension();

    try {

      // Hot-deploy several WARs.
      String fileSrcPath = ejtt.getTestDataDir() +"/"+APP_TYPE.getDataDir()+"/"+ TEMP_DEPLOYABLE_NAME;
      for (int i = 0; i < APP_COPIES; i++) {
        String fileDestPath = ejtt.getDeployDir() +"/"+ String.format(fileNamePattern, i);
        FileUtils.copyFile( new File(fileSrcPath), new File(fileDestPath) );
      }

      ejtt.sleep(10000); // Wait for 10 sec - let AS crunch up the deployment.

      // Wait for them to get displayed and UP.
      for (int i = 0; i < APP_COPIES; i++) {
        String deployableName = String.format(fileNamePattern, i);
        ejtt.deployment.waitActivelyForDeployment(APP_TYPE, deployableName, 5000, 30);
      }

    }
    finally {
      // Undeploy all of them.
      for (int i = 0; i < APP_COPIES; i++) {
        String deployableName = String.format(fileNamePattern, i);
        try {
          //undeployWAR( deployableName ); // TODO: Generalize
          ejtt.deployment.undeployViaEmbJopr(APP_TYPE, deployableName);
        } catch( Exception ex ){
          log.warn("Cathed an expected exception when trying to undeploy "+deployableName+": "+ex );
        }
      }
    }
   
  }// testWarHotDeployManyWarsAtOnce()










  /**
   * Deploys WAR.
   */
  private void deployWAR( String warFilePath )
          throws IOException, HtmlElementNotFoundException
  {
    if( !(new File(warFilePath)).exists())
      throw new FileNotFoundException(warFilePath);
   
    log.info("Deploying: "+warFilePath);

    // Navigate to Enterprise Archives
    //ejtt.getNavTree().getNodeLink(NAV_WAR).click();
    ejtt.getNavTree().getNodeLink(AppConstants.DeployableTypes.WAR.getNavTreeLabel()).click();

    // click on the "Add new resource" button
    client.click("actionHeaderForm:addNewContent")// 404 if setThrowExceptionOnFailingStatusCode(true) above

    // Upload the file
    HtmlFileInput fileInput = (HtmlFileInput)client.getElement("createContentForm:file");
    fileInput.setContentType("application/war");
    fileInput.setValueAttribute(warFilePath);
    client.click("createContentForm:addButton");

    // Log server message.
    ejtt.logServerMessage();

    // Todo: Write some waitUntilDeployed().
    ejtt.sleep( 2000 );

  }



  /**
   * Deploys WAR; if fails, waits 5 seconds and re-tries; this is repeated 3 times.
   */
  private void deployWarRepeatedly( final String warFilePath )
          throws IOException, HtmlElementNotFoundException, EmbJoprTestException
  {

    File warFile = new File(warFilePath);
    final String warFileName = warFile.getName();

    try {

      // Try it 5x in 5 second interval.
      new ActiveConditionChecker( new DescribedCondition("WAR '"+warFileName+"' succesfuly deployed") {
        public boolean isTrue() throws Exception {
          deployWAR(warFilePath);

          // Check whether deployment ended with success message.
          /* Now broken, EmbJopr reports an error even when deployed successfully:
           * Failed to create Resource hellothere.war - cause:
              java.lang.RuntimeException:java.lang.NullPointerException
           -> java.lang.NullPointerException:null
           * See EMBJOPR-116
           */
          /*
          if( server.getFacesMessages().hasNext() ){
            FacesMessage msg = server.getFacesMessages().next();
            if( msg.getSeverity() == FacesMessage.SEVERITY_INFO )
              return true;
            else
              ejtt.logServerMessage("Deployment error: ");
          }
          */

          // Check whether the WAR is listed in EmbJopr.
          log.debug("Looking for listed WAR: "+warFileName);
          boolean listed = ejtt.deployment.isDeployedAccordingToEmbJopr(DeployableTypes.WAR, warFileName, true);
          if( listed )
            return true;
          else
            return false;
        }
      }).dumpPageOnTimeout(this).throwOnTimeout().waitWithTimeout(5000, 8);

    }
    catch( Exception ex ){
      throw new EmbJoprTestException(ex.getClass().getName()+": "+ex.getMessage(), ex);
    }


  }// deployWarRepeatedly()


  /**
   * Undeploys war.
   *
   * TODO: When tested, merge to EJTT.Deployment.
   */
  private void undeployWAR( String warFileName )
          throws IOException, HtmlElementNotFoundException, ActionNotAvailableException
  {

    // Navigate to Enterprise Archives
    ejtt.getNavTree().getNodeLink(NAV_WAR).click();

    ejtt.getTabMenu().clickSummaryTab();

    /// Debug log - we're getting HTTP 500 here :/
    String dumpFile = "target/"+this.getName()+"-undeployWar-"+(1000+RandomUtils.nextInt(1000))+".html";
    log.debug("Dumping page to "+dumpFile);
    DebugUtils.writeFile( dumpFile, client.getPageAsText());
    int httpStatusCode = client.getContentPage().getWebResponse().getStatusCode();
    if( 200 != httpStatusCode )
      log.warn("Status code before undeployment is: "+httpStatusCode);

    //HtmlButtonInput deleteButton = getAppDeleteButton( warFileName ).click();

    // Find the row containing the deployable. Use the pagination if needed.
    ContentTableRow appRow = ejtt.getTabMenu().getTabContentBox().
            findLinkRowInDataTableUsingPagination(warFileName);

    /// DEBUG dump
    //log.debug("Dumping page to: "+dumpFile+"2");
    //DebugUtils.writeFile(dumpFile+"2", client.getPageAsText());

    if( null == appRow ){
      log.warn("Can't find row with WAR to undeploy: "+warFileName);
      return;
    }

    appRow.getButtonByLabel("Delete").click();

    // Log the message (with prefix of potential warning)
    ejtt.logServerMessage("Something went wrong with undeploy: ");

    // Sleep for 3 sec. TODO: write some waitForUndeployed(), as negation of opposite.
    ejtt.sleep( 2000 );

  }

}
TOP

Related Classes of org.jboss.jopr.jsfunit.as5.app.war.WarTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.