示例#1
0
/**
 * Condition is fulfilled when tree has children.
 *
 * @author Jaroslav Jankovic
 * @author Jiri Peterka
 */
public class TreeHasChildren extends AbstractWaitCondition {
  private Logger log = Logger.getLogger(TreeHasChildren.class);
  private Tree tree;

  /**
   * Construct tree has children condition.
   *
   * @param tree given tree
   */
  public TreeHasChildren(Tree tree) {
    super();
    this.tree = tree;
  }

  @Override
  public boolean test() {
    int count = tree.getItems().size();
    log.trace("Count of found tree items:" + count);
    if (count > 0) {
      return true;
    }
    return false;
  }

  @Override
  public String description() {
    return "tree has children";
  }
}
/**
 * Internal Progress Listener of Browser
 *
 * @author Vlado Pakan
 */
public class BrowserProgressListener implements ProgressListener {
  private final Browser browser;
  private boolean done = true;
  private int numCalledIsDoneWithNoChange = 0;
  private static final Logger log = Logger.getLogger(BrowserProgressListener.class);

  public BrowserProgressListener(Browser browser) {
    this.browser = browser;
  }
  // returns true in case page is loaded completely or
  // there is no change after calling this method more then 20 times
  // because on MS Windows method completed is not called properly
  public synchronized boolean isDone() {
    log.debug("Calling isDone()");
    numCalledIsDoneWithNoChange++;
    return done || numCalledIsDoneWithNoChange > 20;
  }

  public synchronized void setDone(boolean done) {
    this.done = done;
  }

  public synchronized void changed(ProgressEvent event) {
    log.debug("Calling chanded()");
    numCalledIsDoneWithNoChange = 0;
  }

  public void completed(ProgressEvent event) {
    setDone(true);
    browser.getSWTWidget().removeProgressListener(this);
  }
}
示例#3
0
/**
 * Wait condition for shells checking whether some shell is active (empty constructor) or using
 * Shell.equals (parameterized constructor).
 *
 * @author rhopp, [email protected]
 */
public class ShellIsActive extends AbstractWaitCondition {

  private Shell shell;
  private static final Logger log = Logger.getLogger(ShellIsActive.class);

  /**
   * Fulfilled, when active shell is equal to given shell.
   *
   * @param shell Shell to compare to.
   */
  public ShellIsActive(Shell shell) {
    InstanceValidator.checkNotNull(shell, "shell");
    this.shell = shell;
  }

  @Override
  public boolean test() {
    if (shell == null) {
      return ShellLookup.getInstance().getCurrentActiveShell() != null;
    } else {
      org.eclipse.swt.widgets.Shell currentActiveShell =
          ShellLookup.getInstance().getCurrentActiveShell();
      if (currentActiveShell == null) {
        log.debug("Current active shell is null");
        return false;
      }
      return currentActiveShell.equals(shell.getSWTWidget());
    }
  }

  @Override
  public String description() {
    return "shell is active";
  }
}
/**
 * Tests JPA Details view
 *
 * @author Jiri Peterka
 */
@RunWith(RedDeerSuite.class)
@Database(name = "testdb")
public class JPADetailsViewTest extends HibernateRedDeerTest {

  private final String PRJ = "mvn-hibernate50-ent";
  @InjectRequirement private DatabaseRequirement dbRequirement;

  private static final Logger log = Logger.getLogger(JPADetailsViewTest.class);

  @Before
  public void testConnectionProfile() {
    log.step("Import test project");
    importMavenProject(PRJ);
    DatabaseConfiguration cfg = dbRequirement.getConfiguration();
    log.step("Create database driver definition");
    DriverDefinitionFactory.createDatabaseDriverDefinition(cfg);
    log.step("Create database connection profile");
    ConnectionProfileFactory.createConnectionProfile(cfg);
    // log.step("Convert project to faceted form");
    // ProjectConfigurationFactory.convertProjectToFacetsForm(PRJ);
    log.step("Set project facet for JPA");
    ProjectConfigurationFactory.setProjectFacetForDB(PRJ, cfg);
  }

  @After
  public void cleanUp() {
    DatabaseConfiguration cfg = dbRequirement.getConfiguration();
    ConnectionProfileFactory.deleteConnectionProfile(cfg.getProfileName());
  }

  @Test
  public void testJPADetailView() {

    log.step("Open entity");
    ProjectExplorer pe = new ProjectExplorer();
    pe.open();
    try {
      pe.getProject(PRJ)
          .getProjectItem("Java Resources", "src/main/java", "org.gen", "Actor.java")
          .open();
    } catch (RedDeerException e) {
      fail("Entities not generated, possible cause https://issues.jboss.org/browse/JBIDE-19175");
    }
    TextEditor textEditor = new TextEditor("Actor.java");
    textEditor.setCursorPosition(20, 1);

    log.step("Open JPA view and check content");
    JPADetailsView jpaDetailsView = new JPADetailsView();
    jpaDetailsView.open();

    try {
      new DefaultStyledText("Type 'Actor' is mapped as entity.");
    } catch (RedDeerException e) {
      fail(
          "JPA details should be available - known issue - https://issues.jboss.org/browse/JBIDE-17940");
    }
  }
}
示例#5
0
/**
 * Parent test for each test of Red Deer
 *
 * @deprecated use {@link org.jboss.reddeer.junit.extensionpoint} extensions to set up and clean
 *     your tests. Once these extensions are installed they are called automatically when test is
 *     running with {@link RedDeerSuite}
 * @author Vlado Pakan
 * @author Jiri Peterka
 * @author jjankovi
 */
@RunWith(RedDeerSuite.class)
@Ignore
public class RedDeerTest {

  @Rule public RedDeerWatchdog rule = new RedDeerWatchdog();

  Logger log = Logger.getLogger(RedDeerTest.class);

  @Before
  public void setUpRDT() {
    setUp();
  }

  @After
  public void tearDownRDT() {
    tearDown();
  }
  // Default setup for each test

  protected void setUp() {
    // close Welcome screen
    for (IViewReference viewReference : WorkbenchLookup.findAllViews()) {
      if (viewReference.getPartName().equals("Welcome")) {
        final IViewReference iViewReference = viewReference;
        Display.syncExec(
            new Runnable() {
              @Override
              public void run() {
                iViewReference.getPage().hideView(iViewReference);
              }
            });
        break;
      }
    }
  }

  //  Default tearDown for each test
  protected void tearDown() {
    // empty for now can be overridden by child classes
  }
}
示例#6
0
/**
 * Default shell returns active shell if available if not it returns first available shell
 *
 * @author Jiri Peterka, Andrej Podhradsky, [email protected]
 */
public class DefaultShell extends AbstractShell {
  private static final Logger log = Logger.getLogger(DefaultShell.class);

  public DefaultShell(String title) {
    super(ShellLookup.getInstance().getShell(title));
    try {
      setFocus();
      log.debug("Shell with title '" + title + "' found");
    } catch (Exception e) {
      throw new SWTLayerException("No shell with title '" + title + "' is available", e);
    }
  }

  /**
   * Creates a new DefaultShell matching specified matcher. First found shell with specified matcher
   * is created. Beware, there is no strict (deterministic) order of shells.
   *
   * @param matcher matcher to match title of a shell
   */
  public DefaultShell(Matcher<String> matcher) {
    super(ShellLookup.getInstance().getShell(matcher));
    try {
      setFocus();
      log.debug("Shell matching specified matcher is found and focused");
    } catch (Exception e) {
      throw new SWTLayerException(
          "Shell matching specified matcher was not focused successfully.", e);
    }
  }

  public DefaultShell() {
    super(ShellLookup.getInstance().getActiveShell());
    try {
      setFocus();
      log.debug("Active shell with title '" + getText() + "' found");
    } catch (Exception e) {
      throw new SWTLayerException("No active shell is available at the moment", e);
    }
  }
}
/**
 * RedDeer implementation of Hybrid Mobile > Android Preferences page
 *
 * @author Vlado Pakan
 */
public class AndroidPreferencesPage extends WorkbenchPreferencePage {

  public static final String PAGE_NAME = "Android";

  private static final Logger log = Logger.getLogger(AndroidPreferencesPage.class);

  public AndroidPreferencesPage() {
    super("Hybrid Mobile", PAGE_NAME);
  }
  /**
   * Sets Android SDK Location to androidSDKLocation
   *
   * @param androidSDKLocation
   */
  public void setAndroidSDKLocation(String androidSDKLocation) {
    log.info("Setting Android SDK Location to: " + androidSDKLocation);
    findAdnroidSDKLocation().setText("");
    KeyboardFactory.getKeyboard().type(androidSDKLocation);
  }
  /**
   * Returns Android SDK Location
   *
   * @return
   */
  public String getAndroidSDKLocation() {
    return findAdnroidSDKLocation().getText();
  }

  /**
   * Finds Output Directory Combo
   *
   * @return
   */
  private Text findAdnroidSDKLocation() {
    return new LabeledText("Android SDK Directory:");
  }
}
/**
 * Condition is met when shell has children or is not available anymore
 *
 * @author rawagner
 */
public class ShellHasChildrenOrIsNotAvailable implements WaitCondition {

  private Shell shell;
  private static final Logger log = Logger.getLogger(ShellHasChildrenOrIsNotAvailable.class);

  /**
   * Default constructor.
   *
   * @param deleteShell instance of shell to test
   */
  public ShellHasChildrenOrIsNotAvailable(Shell deleteShell) {
    this.shell = deleteShell;
  }

  @Override
  public boolean test() {
    int childShells = 0;
    org.eclipse.swt.widgets.Shell swtShell = shell.getSWTWidget();
    ShellHandler handler = ShellHandler.getInstance();
    try {
      childShells = handler.getShells(swtShell).length;
    } catch (CoreLayerException e) {
      if (swtShell != null) {
        return handler.isDisposed(swtShell);
      }
      return true;
    }
    log.debug("number of child shells: " + childShells);
    return childShells > 0;
  }

  @Override
  public String description() {
    return "Shell has children or is not available.";
  }
}
public class ViewDialog extends AbstractDialog {
  private static final Logger log = Logger.getLogger(ViewDialog.class);

  public ViewDialog() {
    super("Create Relational View");
  }

  @Override
  public void finish() {
    log.info("Finishing '" + title + "' Dialog");
    new OkButton().click();
    new WaitWhile(new ShellWithTextIsActive(title), TimePeriod.NORMAL);
    AbstractWait.sleep(TimePeriod.SHORT);
  }

  public ViewDialog setName(String name) {
    log.info("Setting table name to '" + name + "'");
    new LabeledText("Name").setText(name);
    return this;
  }

  public ViewDialog setNameInSource(String name) {
    log.info("Setting name is source to '" + name + "'");
    new LabeledText("Name In Source").setText(name);
    return this;
  }

  public ViewDialog setCardinality(String value) {
    log.info("Setting cardinality to '" + value + "'");
    new DefaultTabItem("Properties").activate();
    new LabeledText("Cardinality").setText(value);
    return this;
  }

  public ViewDialog chceckSupportUpdateIsSystemTable(boolean supportTable, boolean isSystemTable) {
    log.info("Setting checkboxes to ");
    new DefaultTabItem("Properties").activate();
    if (!new CheckBox("Supports Update").isChecked() && supportTable) {
      new CheckBox("Supports Update").click();
    }
    if (!new CheckBox("Is System Table").isChecked() && isSystemTable) {
      new CheckBox("Is System Table").click();
    }
    return this;
  }

  public ViewDialog setDescription(String value) {
    log.info("Setting description to '" + value + "'");
    new DefaultTabItem("Properties").activate();
    new DefaultStyledText().setText(value);
    return this;
  }

  public ViewDialog addColumn(String name, String dataType, String length) {
    log.info("Adding column " + name + " " + dataType + " " + length);
    new DefaultTabItem("Columns").activate();
    new PushButton("Add").click();
    DefaultTable table = new DefaultTable();
    table.getItem(table.rowCount() - 1).select();
    // TODO TEIIDDES-2903
    new PushButton("Edit...").click();
    AbstractWait.sleep(TimePeriod.SHORT);
    new DefaultShell("Edit Column");
    new LabeledText("Name").setText(name);
    new LabeledCombo("Data Type").setSelection(dataType);
    new LabeledText("Length").setText(length);
    new OkButton().click();
    AbstractWait.sleep(TimePeriod.SHORT);
    this.activate();
    return this;
  }

  public ViewDialog setMaterializedTable(String table) {
    new DefaultTabItem("Properties").activate();
    new CheckBox("Materialized").click();
    new PushButton("...").click();
    new DefaultShell("Table Selection");
    new DefaultTable(0).getItem(table).select();
    new PushButton("OK").click();
    return this;
  }
}
public class MavenUserPreferencePage extends PreferencePage {

  private static final Logger log = Logger.getLogger(MavenUserPreferencePage.class);

  public MavenUserPreferencePage() {
    super("Maven", "User Settings");
  }

  public void setUserSettings(String pathToSettings) {
    Text text = null;
    for (int i = 0; i < 10; i++) {
      text = new DefaultText(i);
      if (text.getMessage().contains("settings") && text.getMessage().contains(".xml")) {
        break;
      }
    }
    if (!text.getText().equals(pathToSettings)) {
      text.setText(pathToSettings);
      Button button = new PushButton("Update Settings");
      button.click();
      try {
        new DefaultShell("Update project required");
        new PushButton("Yes").click();
        new DefaultShell("Preferences");
      } catch (SWTLayerException ex) {
        log.debug("'Update project required' shell not found.");
      } finally {
        new WaitUntil(new JobIsRunning(), TimePeriod.NORMAL, false);
        new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG);
      }
    }
  }

  public String getUserSettings() {
    Text text = null;
    for (int i = 0; i < 10; i++) {
      text = new DefaultText(i);
      if ((text.getMessage().contains("settings") && text.getMessage().contains(".xml"))
          || (text.getText().contains("settings") && text.getText().contains(".xml"))) {
        break;
      }
    }
    if (!text.getText().isEmpty()) {
      return text.getText();
    }
    return text.getMessage();
  }

  public void ok() {
    new PushButton("Apply").click();
    try {
      new DefaultShell("Update project required");
      new PushButton("Yes").click();
      new DefaultShell("Preferences");
    } catch (SWTLayerException ex) {
      log.info("Update project required shell was not found.");
    } finally {
      new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG);
      new WorkbenchPreferenceDialog().ok();
    }
  }
}
/**
 * This testsuite consist of one test. It imports all examples (location of examples is defined by
 * system property "examplesLocation") and checks for errors and warnings.
 *
 * @author rhopp, jkopriva
 */
public abstract class AbstractImportQuickstartsTest {

  protected static String SERVER_NAME = "";
  protected QuickstartsReporter reporter = QuickstartsReporter.getInstance();
  protected static LogView errorLogView;

  private static final Logger log = Logger.getLogger(AbstractImportQuickstartsTest.class);

  @BeforeClass
  public static void setup() {
    setupLog();
  }

  @After
  public void cleanup() {
    clearWorkspace();
  }

  @AfterClass
  public static void teardown() {
    createReports();
  }

  protected static void setServerName(String serverName) {
    SERVER_NAME = serverName;
  }

  protected void checkServerStatus() {
    ServersView serversView = new ServersView();
    serversView.open();
    Server server = serversView.getServer(getServerFullName(serversView.getServers(), SERVER_NAME));
    assertTrue("Server has not been started!", server.getLabel().getState() == ServerState.STARTED);
    // assertTrue("Server has not been
    // synchronized!",server.getLabel().getPublishState() ==
    // ServerPublishState.SYNCHRONIZED);
  }

  /*
   * Deploy and undeploy quickstart on running server
   */
  protected void deployUndeployQuickstart(Quickstart qstart, String serverName) {
    new ConsoleView().clearConsole();
    ProjectExplorer explorer = new ProjectExplorer();

    findDeployableProjects(qstart, explorer);

    ServersView serversView = new ServersView();
    serversView.open();
    String fullServerName = getServerFullName(serversView.getServers(), serverName);
    Server server = serversView.getServer(fullServerName);

    for (String deployableProjectName : qstart.getDeployableProjectNames()) {
      try {
        // deploy
        deployProject(deployableProjectName, explorer);
        // check deploy status
        checkDeployedProject(qstart, fullServerName);
        // undeploy
        unDeployModule(
            qstart.getName().equals("template") ? "QUICKSTART_NAME" : qstart.getName(), server);
      } catch (CoreLayerException ex) {
        new DefaultShell("Server Error");
        new OkButton().click();
      }
    }
  }

  private void unDeployModule(String moduleName, Server server) {
    log.info("UNDEPLOYING MODULE" + moduleName + " ON SERVER " + server.getLabel());
    ServerModule serverModule = server.getModule(new RegexMatcher(".*" + moduleName + ".*"));
    serverModule.remove();
    new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG);
  }

  private void findDeployableProjects(Quickstart qstart, ProjectExplorer explorer) {
    explorer.activate();
    for (Project project : explorer.getProjects()) {
      explorer.getProject(project.getName()).select();
      try {
        if (new ContextMenu("Run As", "1 Run on Server").isEnabled()) {
          qstart.addDeployableProjectName(project.getName());
        }
        new WizardDialog().finish();
      } catch (CoreLayerException ex) {
        continue; // non deployable project
      }
    }
  }

  private void deployProject(String deployableProject, ProjectExplorer explorer) {
    log.info("DEPLOYING " + deployableProject);
    explorer.activate();
    Project project = explorer.getProject(deployableProject);
    project.select();
    new ContextMenu("Run As", "1 Run on Server").select();
    new WizardDialog().finish();
  }

  private String getServerFullName(List<Server> servers, String partOfName) {
    for (Server srv : servers) {
      if (srv.getLabel().getName().contains(partOfName)) {
        return srv.getLabel().getName();
      }
    }
    return null;
  }

  protected String getDeployableProjectName(List<Project> projects, String quickstartName) {
    for (Project prj : projects) {
      if (prj.getName().contains(quickstartName)) {
        return prj.getName();
      }
    }
    return null;
  }

  protected static Collection<Quickstart> createQuickstartsList() {
    ArrayList<Quickstart> resultList = new ArrayList<Quickstart>();
    ArrayList<String> specificQuickstarts = new ArrayList<String>();
    if (System.getProperty("specificQuickstarts") != null
        && !System.getProperty("specificQuickstarts").trim().equals("${specificQuickstarts}")) {
      specificQuickstarts =
          new ArrayList<String>(
              Arrays.asList(System.getProperty("specificQuickstarts").trim().split(",")));
    }
    File file = new File(System.getProperty("examplesLocation"));
    FileFilter directoryFilter =
        new FileFilter() {

          @Override
          public boolean accept(File arg0) {
            return arg0.isDirectory();
          }
        };
    for (File f : file.listFiles(directoryFilter)) {
      // if (f.getAbsolutePath().contains("picketlink") ||
      // f.getAbsolutePath().contains("wsat")) { // JBIDE-18497
      // // Picketlink
      // // quickstart
      // // is
      // // not
      // // working
      // QuickstartsReporter.getInstance().addError(new
      // Quickstart("Picketlink", f.getAbsolutePath()),
      // "Picketlink was skipped due to JBIDE-18497");
      // continue;
      // }
      if (!f.getPath().contains("/.")) {
        if (specificQuickstarts.size() == 0 || specificQuickstarts.contains(f.getName())) {
          log.info("PROCESSING " + f.getAbsolutePath());
          Quickstart qstart = new Quickstart(f.getName(), f.getAbsolutePath());
          resultList.add(qstart);
        }
      }
    }
    return resultList;
  }

  protected static void setupLog() {
    errorLogView = new LogView();
    errorLogView.open();
    errorLogView.deleteLog();
  }

  protected static void clearWorkspace() {
    cleanupShells();
    deleteAllProjects();
    closeBrowser();
    new ConsoleView().clearConsole();
  }

  protected void runQuickstarts(Quickstart qstart, String serverName) {
    try {
      importQuickstart(qstart);
      importTestUtilsIfNeeded(qstart);
      if (!isError()
          && System.getProperty("deployOnServer") != null
          && System.getProperty("deployOnServer").equals("true")) {
        checkServerStatus();
        deployUndeployQuickstart(qstart, SERVER_NAME);
      }
    } catch (NoProjectException ex) {
      // there was no project in this directory. Pass the test.
      return;
    }
    checkForWarnings(qstart);
    checkForErrors(qstart);
    checkErrorLog(qstart);
  }

  protected static void createReports() {
    QuickstartsReporter.getInstance().generateReport();
    QuickstartsReporter.getInstance().generateErrorFilesForEachProject(new File("target/reports/"));
    QuickstartsReporter.getInstance()
        .generateAllErrorsFile(new File("target/reports/allErrors.txt"));
  }

  protected void checkErrorLog(Quickstart qstart) {
    List<LogMessage> allErrors = new ArrayList<LogMessage>();
    List<LogMessage> errors = errorLogView.getErrorMessages();
    String errorMessages = "";
    for (LogMessage message : errors) {
      if (!message.getMessage().contains("Unable to delete")
          && !message.getMessage().contains("Could not delete")) {
        reporter.addError(qstart, "ERROR IN ERROR LOG: " + message.getMessage());
        errorMessages += "\t" + message.getMessage() + "\n";
      }
    }
    errorLogView.deleteLog();
    if (!allErrors.isEmpty()) {
      fail("There are errors in error log:\n" + errorMessages);
    }
  }

  private void restartServer() {
    ServersView serversView = new ServersView();
    serversView.open();
    Server server = serversView.getServer(getServerFullName(serversView.getServers(), SERVER_NAME));
    server.clean();
    server.restart();
  }

  protected void checkForWarnings(Quickstart q) {
    for (String warning : ExamplesOperator.getInstance().getAllWarnings()) {
      reporter.addWarning(q, warning);
    }
  }

  protected void checkForErrors(Quickstart q) {
    updateProjectsIfNeeded();
    String errorMessages = "";
    List<String> allErrors = new ArrayList<String>();
    List<String> errors = ExamplesOperator.getInstance().getAllErrors();
    for (String error : errors) {
      if (!error.contains("Unable to delete") && !error.contains("Could not delete")) {
        reporter.addError(q, "ERROR IN PROJECT: " + error);
        errorMessages += "\t" + error + "\n";
        allErrors.add(error);
      }
    }
    if (!allErrors.isEmpty()) {
      fail("There are errors in imported project:\n" + errorMessages);
    }
  }

  protected boolean isError() {
    updateProjectsIfNeeded();
    if (!ExamplesOperator.getInstance().getAllErrors().isEmpty()) {
      return true;
    }
    return false;
  }

  protected void updateProjectsIfNeeded() {
    for (String string : ExamplesOperator.getInstance().getAllErrors()) {
      if (string.contains("not up-to-date with pom.xml")) { // maven
        // update is
        // needed
        // sometimes.
        runUpdate();
      }
    }
  }

  private void runUpdate() {
    new ProjectExplorer().getProjects().get(0).select();
    new ContextMenu("Maven", "Update Project...").select();
    new DefaultShell("Update Maven Project");
    new PushButton("Select All").click();
    new PushButton("OK").click();
    new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG);
  }

  protected static void deleteAllProjects() {
    ProjectExplorer projectExplorer = new ProjectExplorer();
    projectExplorer.open();
    List<Project> projects = projectExplorer.getProjects();
    for (Project p : projects) {
      DeleteUtils.forceProjectDeletion(p, false);
    }
  }

  protected static void cleanupShells() {
    ShellHandler.getInstance().closeAllNonWorbenchShells();
  }

  protected void importQuickstart(Quickstart quickstart) throws NoProjectException {
    ExtendedMavenImportWizard mavenImportWizard = new ExtendedMavenImportWizard();
    mavenImportWizard.open();
    MavenImportWizardFirstPage wizPage = new MavenImportWizardFirstPage();
    try {
      wizPage.setRootDirectory(quickstart.getPath().getAbsolutePath());
    } catch (WaitTimeoutExpiredException e) {
      cleanupShells();
      throw new NoProjectException();
    }
    try {
      mavenImportWizard.finish();
    } catch (MavenImportWizardException e) {
      for (String error : e.getErrors()) {
        reporter.addError(quickstart, error);
      }
    }
  }

  private void importTestUtilsIfNeeded(Quickstart qstart) {
    for (String error : ExamplesOperator.getInstance().getAllErrors()) {
      if (error.contains("Missing artifact org.javaee7:test-utils")) {
        Quickstart testUtils =
            new Quickstart(
                "test-utils",
                qstart.getPath().getAbsolutePath().replace(qstart.getName(), "test-utils"));
        importQuickstart(testUtils);
        break;
      }
      if (error.contains("Missing artifact org.javaee7:util")) {
        Quickstart testUtils =
            new Quickstart(
                "util", qstart.getPath().getAbsolutePath().replace(qstart.getName(), "test-utils"));
        importQuickstart(testUtils);
        break;
      }
    }
  }

  protected static void closeBrowser() {
    try {
      BrowserEditor browser = new BrowserEditor(new RegexMatcher(".*"));
      while (browser != null) {
        browser.close();
        try {
          browser = new BrowserEditor(new RegexMatcher(".*"));
        } catch (CoreLayerException ex) {
          browser = null;
        }
      }
    } catch (CoreLayerException ex) {
      return;
    }
  }

  private static void setupMavenRepo() {
    String mvnConfigFileName = new File("target/classes/settings.xml").getAbsolutePath();
    WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog();
    preferenceDialog.open();
    MavenSettingsPreferencePage prefPage = new MavenSettingsPreferencePage();
    preferenceDialog.select(prefPage);
    prefPage.setUserSettingsLocation(mvnConfigFileName);
    preferenceDialog.ok();
    new WaitUntil(new JobIsRunning());
  }

  /**
   * Extended maven import wizard. When super.finsh() fails, waits another 15 minutes.
   *
   * @author rhopp
   */
  private class ExtendedMavenImportWizard extends MavenImportWizard {

    @Override
    public void finish() {
      try {
        super.finish();
      } catch (WaitTimeoutExpiredException ex) {
        new WaitWhile(new JobIsRunning(), TimePeriod.getCustom(60 * 15));
      }
    }
  }

  class NoProjectException extends RedDeerException {

    public NoProjectException() {
      super("There is no project in this directory");
    }
  }

  /**
   * Checks whether is project deployed properly.
   *
   * @param projectName
   * @param serverNameLabel
   */
  public void checkDeployedProject(Quickstart qstart, String serverNameLabel) {
    if (!qstart.getName().contains("ejb-timer")
        && !qstart.getName().contains("cluster-ha-singleton")) {
      new WaitWhile(new JobIsRunning());
      new WaitUntil(new ConsoleHasNoChange(TimePeriod.LONG), TimePeriod.VERY_LONG);
    }
    JBossServerView serversView = new JBossServerView();
    serversView.open();
    String moduleName = qstart.getName().equals("template") ? "QUICKSTART_NAME" : qstart.getName();
    JBossServerModule module =
        (JBossServerModule)
            serversView
                .getServer(serverNameLabel)
                .getModule(new RegexMatcher(".*" + moduleName + ".*")); // cannot
    // be
    // used
    // projectName
    // -
    // issues
    // with
    // parent
    // projects
    if (new ContextMenu("Show In", "Web Browser").isEnabled()) {
      module.openWebPage();

      final BrowserEditor browser = new BrowserEditor(new RegexMatcher(".*"));
      try {
        new WaitUntil(new BrowserIsnotEmpty(browser));
      } catch (WaitTimeoutExpiredException e) {
        // try to refresh browser and wait one more time.
        browser.refreshPage();
        new WaitUntil(new BrowserIsnotEmpty(browser));
      }

      // Now the browser should not be empty. Let's check for error
      // messages
      // (strings like "404")
      checkBrowserForErrorPage(browser);
      assertNotEquals("", browser.getText());
      new DefaultEditor().close();
    }
    checkConsoleForException();
    checkServerViewForStatus(moduleName, serverNameLabel);
  }

  protected void checkServerViewForStatus(String projectName, String serverNameLabel) {
    ServersView serversView = new ServersView();
    serversView.open();
    Server server = serversView.getServer(serverNameLabel);
    ServerModule serverModule = server.getModule(new RegexMatcher(".*" + projectName + ".*"));
    ModuleLabel moduleLabel = serverModule.getLabel();
    ServerState moduleState = moduleLabel.getState();
    org.junit.Assert.assertTrue("Module has not been started!", moduleState == ServerState.STARTED);
  }

  protected void checkConsoleForException() {
    ConsoleView consoleView = new ConsoleView();
    consoleView.open();
    assertFalse(
        "Console contains text 'Operation (\"deploy\") failed':\n" + consoleView.getConsoleText(),
        consoleView.getConsoleText().contains("Operation (\"deploy\") failed"));
  }

  protected void checkBrowserForErrorPage(BrowserEditor browser) {
    ConsoleView consoleView = new ConsoleView();
    consoleView.open();
    assertFalse(
        "Browser contains text 'Status 404'\n Console output:\n" + consoleView.getConsoleText(),
        browser.getText().contains("Status 404") || browser.getText().contains("404 - Not Found"));
    assertFalse(
        "Browser contains text 'Error processing request'\n Console output:\n"
            + consoleView.getConsoleText(),
        browser.getText().contains("Error processing request"));
  }

  class BrowserIsnotEmpty extends AbstractWaitCondition {

    BrowserEditor browser;

    public BrowserIsnotEmpty(BrowserEditor browser) {
      this.browser = browser;
    }

    public boolean test() {
      return !browser.getText().equals("");
    }

    public String description() {
      return "Browser is empty!";
    }
  }

  class ModuleStarted extends AbstractWaitCondition {

    String projectName;
    String serverNameLabel;

    public ModuleStarted(String projectName, String serverNameLabel) {
      this.projectName = projectName;
      this.serverNameLabel = serverNameLabel;
    }

    public boolean test() {
      ServersView serversView = new ServersView();
      serversView.open();
      Server server = serversView.getServer(serverNameLabel);
      ServerModule serverModule = server.getModule(new RegexMatcher(".*" + projectName + ".*"));
      ModuleLabel moduleLabel = serverModule.getLabel();
      ServerState moduleState = moduleLabel.getState();
      return moduleState == ServerState.STARTED;
    }

    public String description() {
      return "Module has not started!";
    }
  }
}
/**
 * Reverse Engineering File (reveng.xml) file test Creates file
 *
 * @author jpeterka
 */
@RunWith(RedDeerSuite.class)
@Database(name = "testdb")
public class RevengFileTest extends HibernateRedDeerTest {

  private String PROJECT_NAME = "revengfiletest";
  @InjectRequirement private DatabaseRequirement dbRequirement;

  private static final Logger log = Logger.getLogger(RevengFileTest.class);

  @Before
  public void prepare() {
    log.step("Import test project");
    importProject(PROJECT_NAME);
    prepareConsoleConfiguration();
  }

  public void prepareConsoleConfiguration() {
    log.step("Create hibernate configuration file with console configuration");
    NewHibernateConfigurationWizard wizard = new NewHibernateConfigurationWizard();
    wizard.open();
    NewConfigurationLocationPage p1 = new NewConfigurationLocationPage();
    p1.setLocation(PROJECT_NAME, "src");
    wizard.next();

    DatabaseConfiguration cfg = dbRequirement.getConfiguration();
    NewConfigurationSettingPage p2 = new NewConfigurationSettingPage();
    p2.setDatabaseDialect("H2");
    p2.setDriverClass(cfg.getDriverClass());
    p2.setConnectionURL(cfg.getJdbcString());
    p2.setUsername(cfg.getUsername());
    p2.setCreateConsoleConfiguration(true);

    wizard.finish();
  }

  @Test
  public void testCreateRevengFile() {
    ProjectExplorer pe = new ProjectExplorer();
    pe.open();
    pe.selectProjects(PROJECT_NAME);

    log.step("Create hibernate reverese engineering via reveng wizard");
    NewReverseEngineeringFileWizard wizard = new NewReverseEngineeringFileWizard();
    wizard.open();
    wizard.next();
    TableFilterWizardPage page = new TableFilterWizardPage();
    page.setConsoleConfiguration(PROJECT_NAME);
    page.refreshDatabaseSchema();
    page.pressInclude();
    log.step("Finish wizard to create a file");
    wizard.finish();

    EditorHandler.getInstance().closeAll(false);
    pe.open();
    new DefaultTreeItem(PROJECT_NAME, "hibernate.reveng.xml").doubleClick();
    new DefaultEditor("Hibernate Reverse Engineering Editor").activate();

    RevengEditor re = new RevengEditor();
    re.activateDesignTab();
    re.activateOverviewTab();
    re.activateSourceTab();
    re.activateTableFiltersTab();
    re.activateTypeMappingsTab();
  }

  @After
  public void clean() {}
}
示例#13
0
/**
 * Lookup for {@link org.eclipse.graphiti.ui.editor.DiagramEditor}
 *
 * @author Andrej Podhradsky ([email protected])
 */
public class DiagramEditorLookup {

  protected final Logger log = Logger.getLogger(this.getClass());

  private static DiagramEditorLookup instance;

  private DiagramEditorLookup() {}

  /**
   * Gets the single instance of DiagramEditorLookup.
   *
   * @return single instance of DiagramEditorLookup
   */
  public static DiagramEditorLookup getInstance() {
    if (instance == null) {
      instance = new DiagramEditorLookup();
    }
    return instance;
  }

  /**
   * Finds a diagram editor in an active editor.
   *
   * @return Diagram editor
   */
  public DiagramEditor findDiagramEditor() {
    return findDiagramEditor(new ActiveEditor().getIEditorPart());
  }

  /**
   * Finds a diagram editor in a given editor part.
   *
   * @param editorPart Editor part
   * @return Diagram editor
   */
  public DiagramEditor findDiagramEditor(final IEditorPart editorPart) {
    DiagramEditor diagramEditor =
        Display.syncExec(
            new ResultRunnable<DiagramEditor>() {
              @Override
              public DiagramEditor run() {
                return (DiagramEditor) editorPart.getAdapter(DiagramEditor.class);
              }
            });
    if (diagramEditor == null) {
      throw new GEFLayerException("Cannot find diagram editor in a given editor part");
    }
    return diagramEditor;
  }

  /**
   * Helper class for achieving active {@link org.eclipse.ui.IEditorPart}. This class can be removed
   * when {@link org.jboss.reddeer.workbench.lookup} is exported.
   *
   * @author Andrej Podhradsky ([email protected])
   */
  private class ActiveEditor extends DefaultEditor {

    public ActiveEditor() {
      super();
    }

    public IEditorPart getIEditorPart() {
      return getEditorPart();
    }
  }
}
示例#14
0
/** @author Jiri Peterka */
@RunWith(RedDeerSuite.class)
public class MenuTest {

  protected final Logger log = Logger.getLogger(this.getClass());
  private ProjectExplorer explorer = new ProjectExplorer();
  private static int limit = 20;

  @Before
  public void setUp() {
    explorer.open();
  }

  @Test
  public void preferencesMenuTest() {
    log.info("Preferences menu test");
    new DefaultShell();
    Menu m = new ShellMenu("Window", "Preferences");
    m.select();
    Shell s = new DefaultShell("Preferences");
    s.close();
  }

  @Test
  public void aboutMenuTest() {
    log.info("About menu test");
    new DefaultShell();
    @SuppressWarnings("unchecked")
    Menu m =
        new ShellMenu(
            new WithMnemonicTextMatcher("Help"), new WithTextMatcher(new RegexMatcher("About.*")));
    m.select();
    Shell s = new DefaultShell();
    s.close();
  }

  @Test
  public void logTest() {
    log.debug("debug");
    log.error("error");
    log.fatal("fatal");
    log.warn("info");
    log.info("info");
  }

  @Test
  public void regexMenuTest() {

    log.info("regex menu test");
    try {
      RegexMatcher[] regexMatchers = {new RegexMatcher("Win.*"), new RegexMatcher("Pref.*")};
      WithTextMatchers m = new WithTextMatchers(regexMatchers);
      new ShellMenu(m.getMatchers());
    } catch (SWTLayerException e) {
      fail("there should be no exception");
    }
  }

  @Test
  public void unavailableMenuTest() {
    log.info("unavailable regex menu test");
    try {
      RegexMatcher[] regexMatchers = {new RegexMatcher("Win.*"), new RegexMatcher("Prefz.*")};
      WithTextMatchers m = new WithTextMatchers(regexMatchers);
      new ShellMenu(m.getMatchers());
      fail("exception should be thrown");
    } catch (SWTLayerException e) { // do nothing

    }
  }

  @Test
  public void contextMenuTest() {

    ProjectExplorer pe = new ProjectExplorer();
    pe.open();

    Menu menu = new ContextMenu("New", "Project...");
    menu.select();
    Shell s = new DefaultShell("New Project");
    s.close();
  }

  @Test
  public void hundertscontextMenuTest() {
    for (int i = 0; i < limit; i++) {
      contextMenuTest();
    }
  }

  @Test
  public void contextMenuItemTextTest() {
    // make sure shell is focused
    new DefaultShell();

    ProjectExplorer pe = new ProjectExplorer();
    pe.open();

    Menu menu = new ContextMenu("New", "Project...");
    assertTrue("Menuitem text not expected to be empty", !menu.getText().equals(""));
  }

  @Test
  public void shellMenuItemTextTest() {
    new DefaultShell();
    Menu menu = new ShellMenu("Window", "Preferences");
    assertTrue("Menuitem text not expected to be empty", !menu.getText().equals(""));
  }

  @Test
  public void menuWithMnemonicTest() {
    log.info("menu with mnemonic test");
    new DefaultShell();
    Menu m = new ShellMenu("File", "New", "Other...");
    m.select();
    Shell s = new DefaultShell("New");
    s.close();
  }

  private class ProjectExplorer extends WorkbenchView {
    public ProjectExplorer() {
      super("General", "Project Explorer");
    }
  }
}
示例#15
0
/**
 * Contains methods for handling UI operations on {@link CCombo} widgets.
 *
 * @author Andrej Podhradsky
 */
public class CComboHandler {

  private static CComboHandler instance;

  private static final Logger log = Logger.getLogger(CComboHandler.class);

  private CComboHandler() {}

  /**
   * Gets instance of CComboHandler.
   *
   * @return instance of CComboHandler
   */
  public static CComboHandler getInstance() {
    if (instance == null) {
      instance = new CComboHandler();
    }
    return instance;
  }

  /**
   * Gets items included in specified {@link CCombo}.
   *
   * @param ccombo custom combo to handle
   * @return names of items included in custom combo
   */
  public String[] getItems(final CCombo ccombo) {
    return Display.syncExec(
        new ResultRunnable<String[]>() {

          @Override
          public String[] run() {
            return ccombo.getItems();
          }
        });
  }

  /**
   * Sets selection of specified {@link CCombo} to the item on specified position.
   *
   * @param ccombo custom combo to handle
   * @param index index of item to select
   */
  public void setSelection(final CCombo ccombo, final int index) {
    Display.syncExec(
        new Runnable() {

          @Override
          public void run() {
            int itemsLength = getItems(ccombo).length;
            if (index >= itemsLength) {
              log.error("CCombo does not have " + index + 1 + "items!");
              log.info("CCombo has " + itemsLength + " items");
              throw new CoreLayerException("Nonexisted item in combo was requested");
            } else {
              ccombo.select(index);
            }
          }
        });
  }

  /**
   * Sets selection of specified {@link CCombo} to specified text.
   *
   * @param ccombo custom combo to handle
   * @param text text to set
   */
  public void setSelection(final CCombo ccombo, final String text) {
    Display.syncExec(
        new Runnable() {

          @Override
          public void run() {
            String[] items = getItems(ccombo);
            int index = Arrays.asList(items).indexOf(text);
            if (index == -1) {
              log.error("'" + text + "' is not contained in custom combo items");
              log.info("Items present in custom combo:");
              int i = 0;
              for (String item : items) {
                log.info("    " + item + "(index " + i);
                i++;
              }
              throw new CoreLayerException("Nonexisting item in custom combo was requested");
            } else {
              ccombo.select(index);
            }
          }
        });
  }

  /**
   * Gets text of the selection of specified {@link CCombo}.
   *
   * @param ccombo custom combo to handle
   * @return text of specified selection of specified custom combo
   */
  public String getSelection(final CCombo ccombo) {
    return Display.syncExec(
        new ResultRunnable<String>() {

          @Override
          public String run() {
            Point selection = ccombo.getSelection();
            String comboText = ccombo.getText();
            String selectionText = "";
            if (selection.y > selection.x) {
              selectionText = comboText.substring(selection.x, selection.y);
            }
            return selectionText;
          }
        });
  }

  /**
   * Gets index of the selection of specified {@link CCombo}.
   *
   * @param ccombo custom combo to handle
   * @return index of the selection of specified custom combo
   */
  public int getSelectionIndex(final CCombo ccombo) {
    return Display.syncExec(
        new ResultRunnable<Integer>() {

          @Override
          public Integer run() {
            return ccombo.getSelectionIndex();
          }
        });
  }
}
/**
 * This singleton class is helper for adding/deploying projects and examples from JBoss Central or
 * via File->New->Project Examples
 *
 * @author rhopp
 */
public class ExamplesOperator {

  private static final Logger log = Logger.getLogger(ExamplesOperator.class);

  private static ExamplesOperator instance;

  public static ExamplesOperator getInstance() {
    if (instance == null) {
      instance = new ExamplesOperator();
    }
    return instance;
  }

  /**
   * Deploys existing project to given server.
   *
   * @param projectName
   * @param serverName
   */
  public void deployProject(String projectName, String serverName) {
    JBossServerView serversView = new JBossServerView();
    serversView.open();
    ModifyModulesDialog modulesDialog = serversView.getServer(serverName).addAndRemoveModules();
    String moduleName =
        new DefaultTreeItem(new TreeItemTextMatcher(new RegexMatcher(".*" + projectName + ".*")))
            .getText();
    new ModifyModulesPage().add(moduleName);
    modulesDialog.finish();
    new WaitUntil(new WaitForProjectToStartAndSynchronize(moduleName, serverName), TimePeriod.LONG);
  }

  /**
   * Imports archetype project from JBoss Central from section "Start from scratch"
   *
   * @param project
   */
  public void importArchetypeProject(ArchetypeProject project) {
    log.step("Import project start");
    JBossCentralProjectWizard dialog = new JBossCentralProjectWizard(project);
    dialog.open();
    NewProjectExamplesStacksRequirementsPage firstPage =
        new NewProjectExamplesStacksRequirementsPage();
    firstPage.setTargetRuntime(1);
    log.step("Import project first page");
    new DefaultLink();
    if (project.isBlank()) {
      firstPage.toggleBlank(project.isBlank());
    }
    checkRequirements(firstPage.getRequirements());
    dialog.next();
    ArchetypeExamplesWizardFirstPage secondPage = new ArchetypeExamplesWizardFirstPage();
    assertFalse("Project Name cannot be empty", secondPage.getProjectName().equals(""));
    dialog.next();
    ArchetypeExamplesWizardPage thirdPage = new ArchetypeExamplesWizardPage();
    assertFalse("Group ID cannot be empty", thirdPage.getGroupID().equals(""));
    NewProjectExamplesReadyPage projectReadyPage = dialog.finishAndWait();
    checkProjectReadyPage(projectReadyPage, project);
    projectReadyPage.finish();
    checkForErrors();
  }

  /**
   * Imports example project from JBoss Central from "Start from a sample" section
   *
   * @param project
   */
  public void importExampleProjectFromCentral(CentralExampleProject project) {
    NewProjectExamplesWizardDialogCentral dialog = new NewProjectExamplesWizardDialogCentral();
    dialog.open(project);
    MavenExamplesRequirementPage reqPage = new MavenExamplesRequirementPage();
    checkRequirements(reqPage.getRequirements());
    try {
      new WaitUntil(new MavenRepositoryNotFound());
      fail("Maven repository is not present. Link with message: " + new DefaultLink().getText());
    } catch (WaitTimeoutExpiredException ex) {
      // Do nothing
    }
    dialog.next();
    new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG);
    try {
      dialog.finish(project.getProjectName());
    } catch (WaitTimeoutExpiredException ex) { // waiting in dialog.finish()
      // is not enough!
      new WaitWhile(new ShellWithTextIsActive("New Project Example"), TimePeriod.VERY_LONG);
      new WaitWhile(new JobIsRunning(), TimePeriod.LONG);
    }
    checkForErrors();
  }

  /**
   * Checks whether is project deployed properly.
   *
   * @param projectName
   * @param serverNameLabel
   */
  public void checkDeployedProject(String projectName, String serverNameLabel) {
    if (!projectName.equals("jboss-ejb-timer")) {
      new WaitUntil(new ConsoleHasNoChange(), TimePeriod.LONG);
    }
    JBossServerView serversView = new JBossServerView();
    serversView.open();
    JBossServerModule module =
        (JBossServerModule)
            serversView
                .getServer(serverNameLabel)
                .getModule(new RegexMatcher(".*" + projectName + ".*"));
    module.openWebPage();
    final BrowserEditor browser = new BrowserEditor(new RegexMatcher(".*"));
    try {
      new WaitUntil(new BrowserIsnotEmpty(browser));
    } catch (WaitTimeoutExpiredException e) {
      // try to refresh browser and wait one more time.
      browser.refreshPage();
      new WaitUntil(new BrowserIsnotEmpty(browser));
    }

    // Now the browser should not be empty. Let's check for error messages
    // (strings like "404")
    checkBrowserForErrorPage(browser);
    checkConsoleForException();

    assertNotEquals("", browser.getText());
    new DefaultEditor().close();
  }

  private void checkConsoleForException() {
    ConsoleView consoleView = new ConsoleView();
    consoleView.open();
    assertFalse(
        "Console contains text 'Operation (\"deploy\") failed':\n" + consoleView.getConsoleText(),
        consoleView.getConsoleText().contains("Operation (\"deploy\") failed"));
  }

  private void checkBrowserForErrorPage(BrowserEditor browser) {
    ConsoleView consoleView = new ConsoleView();
    consoleView.open();
    assertFalse(
        "Browser contains text 'Status 404'\n Console output:\n" + consoleView.getConsoleText(),
        browser.getText().contains("Status 404"));
  }

  /**
   * Returns all warnings currently in workspace.
   *
   * @param project
   * @return
   */
  public List<String> getAllWarnings() {
    List<String> warnings = new ArrayList<String>();
    ProblemsView problemsView = new ProblemsView();
    problemsView.open();
    for (Problem warning : problemsView.getProblems(ProblemType.WARNING)) {
      warnings.add(warning.getDescription());
    }
    return warnings;
  }

  /** Returns all errors from Problems View as a List of Strings */
  public List<String> getAllErrors() {
    List<String> errors = new ArrayList<String>();
    ProblemsView problemsView = new ProblemsView();
    problemsView.open();
    for (Problem error : problemsView.getProblems(ProblemType.ERROR)) {
      errors.add(error.getDescription());
    }
    return errors;
  }

  /** Checks for errors in Problems View. Fails if there is some. */
  public void checkForErrors() {
    ProblemsView problemsView = new ProblemsView();
    problemsView.open();
    List<Problem> errors = problemsView.getProblems(ProblemType.ERROR);
    if (!errors.isEmpty()) {
      String failureMessage = "There are errors after importing project";
      for (Problem problem : errors) {
        failureMessage += problem.getDescription();
        failureMessage += System.getProperty("line.separator");
      }
      fail(failureMessage);
    }
  }

  private void checkProjectReadyPage(NewProjectExamplesReadyPage page, ArchetypeProject project) {
    assertFalse(page.isQuickFixEnabled());
    if (!project.isBlank()) {
      assertTrue(page.isShowReadmeEnabled());
    }
  }

  private void checkRequirements(List<ExampleRequirement> requirements) {
    for (ExampleRequirement requirement : requirements) {
      assertTrue("Requirement \"" + requirement.getName() + "\" is not met.", requirement.isMet());
    }
  }

  private class WaitForProjectToStartAndSynchronize implements WaitCondition {

    String projectName;
    String serverName;
    JBossServerModule module = null;

    public WaitForProjectToStartAndSynchronize(String projectName, String serverName) {
      this.projectName = projectName;
      this.serverName = serverName;
    }

    public boolean test() {
      boolean synch =
          getModule().getLabel().getPublishState().compareTo(ServerPublishState.SYNCHRONIZED) == 0;
      boolean started = getModule().getLabel().getState().compareTo(ServerState.STARTED) == 0;
      // return synch && started;
      // https://issues.jboss.org/browse/JBIDE-19288
      return synch;
    }

    public String description() {
      return "Waiting for module to be started-synchronized, but was "
          + getModule().getLabel().getState()
          + "-"
          + getModule().getLabel().getPublishState();
    }

    private JBossServerModule getModule() {
      int counter = 0;
      while (module == null && counter < 5) {
        JBossServerView serversView = new JBossServerView();
        serversView.open();
        try {
          module = serversView.getServer(serverName).getModule(projectName);
        } catch (EclipseLayerException ex) {
          // module not found
          counter++;
        }
      }
      return module;
    }
  }

  private class BrowserIsnotEmpty implements WaitCondition {

    BrowserEditor browser;

    public BrowserIsnotEmpty(BrowserEditor browser) {
      this.browser = browser;
    }

    public boolean test() {
      return !browser.getText().equals("");
    }

    public String description() {
      return "Browser is empty!";
    }
  }

  private class TreeItemTextMatcher extends TypeSafeMatcher<TreeItem> {

    Matcher<String> matcher;

    public TreeItemTextMatcher(Matcher<String> matcher) {
      this.matcher = matcher;
    }

    @Override
    public void describeTo(Description description) {
      // TODO Auto-generated method stub

    }

    @Override
    protected boolean matchesSafely(TreeItem item) {
      return matcher.matches(WidgetHandler.getInstance().getText(item));
    }
  }
}
@RunWith(RedDeerSuite.class)
@Database(name = "testdb")
public class ConsoleConfigurationFileTest extends HibernateRedDeerTest {

  private String PROJECT_NAME = "configurationtest";
  private String HIBERNATE_CFG_FILE = "hibernate.cfg.xml";
  private static final Logger log = Logger.getLogger(ConsoleConfigurationFileTest.class);

  @InjectRequirement private DatabaseRequirement dbRequirement;

  @Before
  public void prepare() {
    importProject(PROJECT_NAME);
  }

  @Test
  public void testCreateConfigurationFileWithoutConsole35() {
    testCreateConfigurationFile("3.5", false);
  }

  @Test
  public void testCreateConfigurationFileWithConsole35() {
    testCreateConfigurationFile("3.5", true);
  }

  @Test
  public void testCreateConfigurationFileFromDatasource35() {
    createConfigurationFileFromDatasource("3.5");
  }

  @Test
  public void testCreateConfigurationFileWithoutConsole36() {
    testCreateConfigurationFile("3.6", false);
  }

  @Test
  public void testCreateConfigurationFileWithConsole36() {
    testCreateConfigurationFile("3.6", true);
  }

  @Test
  public void testCreateConfigurationFileFromDatasource36() {
    createConfigurationFileFromDatasource("3.6");
  }

  @Test
  public void testCreateConfigurationFileWithoutConsole40() {
    testCreateConfigurationFile("4.0", false);
  }

  @Test
  public void testCreateConfigurationFileWithConsole40() {
    testCreateConfigurationFile("4.0", true);
  }

  @Test
  public void testCreateConfigurationFileFromDatasource40() {
    createConfigurationFileFromDatasource("4.0");
  }

  @Test
  public void testCreateConfigurationFileWithoutConsole43() {
    testCreateConfigurationFile("4.3", false);
  }

  @Test
  public void testCreateConfigurationFileWithConsole43() {
    testCreateConfigurationFile("4.3", true);
  }

  @Test
  public void testCreateConfigurationFileFromDatasource43() {
    createConfigurationFileFromDatasource("4.3");
  }

  private void createConfigurationFileFromDatasource(String hbVersion) {
    // Create datasource
    DatabaseConfiguration cfg = dbRequirement.getConfiguration();
    log.step("Create database driver definition");
    DriverDefinitionFactory.createDatabaseDriverDefinition(cfg);
    log.step("Create database connection profile");
    ConnectionProfileFactory.createConnectionProfile(cfg);

    log.step("Create Hibernate configuration file");
    NewHibernateConfigurationWizard wizard = new NewHibernateConfigurationWizard();
    wizard.open();

    NewConfigurationLocationPage p1 = new NewConfigurationLocationPage();
    p1.setLocation(PROJECT_NAME, "src");
    wizard.next();

    // Get values from connection
    log.step("Use created database connection profile for database details");
    Link link = new DefaultLink("Get values from Connection");
    link.click();
    new WaitUntil(new ShellWithTextIsActive("Select Connection Profile"));
    new DefaultCombo().setSelection(cfg.getProfileName());
    new OkButton().click();
    new WaitWhile(new ShellWithTextIsActive("Select Connection Profile"));

    new DefaultShell("");

    // Check values
    NewConfigurationSettingPage p2 = new NewConfigurationSettingPage();
    p2.setHibernateVersion(hbVersion);
    assertTrue("jdbc must match", p2.getConnectionURL().equals(cfg.getJdbcString()));
    assertTrue("driver must match", p2.getDriveClass().equals(cfg.getDriverClass()));
    assertTrue("username must match", p2.getUsername().equals(cfg.getUsername()));

    log.step("Finish the wizard");
    wizard.finish();

    checkFile(false);
  }

  public void testCreateConfigurationFile(String hbVersion, boolean generateConsole) {

    log.step("Create Hibernate configuration file");
    NewHibernateConfigurationWizard wizard = new NewHibernateConfigurationWizard();
    wizard.open();
    NewConfigurationLocationPage p1 = new NewConfigurationLocationPage();
    p1.setLocation(PROJECT_NAME, "src");
    wizard.next();

    DatabaseConfiguration cfg = dbRequirement.getConfiguration();
    NewConfigurationSettingPage p2 = new NewConfigurationSettingPage();
    p2.setHibernateVersion(hbVersion);
    p2.setConnectionURL(cfg.getJdbcString());
    p2.setUsername(cfg.getUsername());

    if (generateConsole) {
      p2.setCreateConsoleConfiguration(generateConsole);
    }
    log.step("Finish the wizard");
    wizard.finish();

    checkFile(generateConsole);
  }

  private void checkFile(boolean generateConsole) {
    PackageExplorer pe = new PackageExplorer();
    pe.open();
    DefaultTreeItem ti = new DefaultTreeItem(PROJECT_NAME, "src", HIBERNATE_CFG_FILE);
    ti.doubleClick();
    new DefaultEditor(HIBERNATE_CFG_FILE);

    if (generateConsole) {
      KnownConfigurationsView v = new KnownConfigurationsView();
      v.selectConsole(PROJECT_NAME);
    }
  }

  @After
  public void clean() {
    ProjectExplorer pe = new ProjectExplorer();
    pe.open();
    pe.getProject(PROJECT_NAME).delete(true);
  }
}
public class CreateDriverDialog extends AbstractDialog {

  private static final Logger log = Logger.getLogger(CreateDriverDialog.class);

  public CreateDriverDialog() {
    super("New Driver Definition");
    log.info("New Driver Definition dialog is opened");
  }

  public CreateDriverDialog selectTemplate(String type, String version) {
    new DefaultTabItem("Name/Type").activate();
    TreeItem root = new DefaultTree().getItems().get(0);
    for (TreeItem item : root.getItems()) {
      if (type.equals(item.getCell(0)) && version.equals(item.getCell(2))) {
        item.select();
        break;
      }
    }
    return this;
  }

  /** First must be run selectTemplate */
  public CreateDriverDialog setName(String name) {
    log.info("Set driver name to: '" + name + "'");
    activate();
    new LabeledText("Driver name:").setText(name);
    return this;
  }

  public CreateDriverDialog addDriver(String path) {
    log.info("Set driver path to: '" + path + "'");
    new DefaultTabItem("JAR List").activate();
    clearAllDriverLibraries();
    addItem(path);
    addItem(path);
    removeDriverLibrary(path);
    return this;
  }

  public CreateDriverDialog setDriverClassGeneric(String driverClass) {
    log.info("Set driver class to: '" + driverClass + "'");
    new DefaultTabItem("Properties").activate();
    new DefaultTreeItem(new DefaultTree(0), "General", "Driver Class").doubleClick();
    new PushButton("...").click();
    new DefaultShell("Available Classes from Jar List");
    new DefaultText().setText(driverClass);
    new PushButton("OK").click();
    activate();
    return this;
  }

  public CreateDriverDialog setDriverClass(String driverClass) {
    log.info("Set driver class to: '" + driverClass + "'");
    new DefaultTabItem("Properties").activate();
    new DefaultTreeItem(new DefaultTree(0), "General", "Driver Class").doubleClick();
    new DefaultText().setText(driverClass);
    activate();
    return this;
  }

  public CreateDriverDialog setConnectionUrl(String connectionUrl) {
    log.info("Set driver connection url to: '" + connectionUrl + "'");
    new DefaultTabItem("Properties").activate();
    new DefaultTreeItem(new DefaultTree(0), "General", "Connection URL").doubleClick();
    new DefaultText().setText(connectionUrl);
    activate();
    return this;
  }

  public CreateDriverDialog setDatabaseName(String databaseName) {
    log.info("Set driver database name to: '" + databaseName + "'");
    new DefaultTabItem("Properties").activate();
    new DefaultTreeItem(new DefaultTree(0), "General", "Database Name").doubleClick();
    new DefaultText().setText(databaseName);
    activate();
    return this;
  }

  @Override
  public void finish() {
    log.info("Finishing '" + title + "' Dialog");
    new PushButton("OK").click();
  }

  private void clearAllDriverLibraries() {
    if (new DefaultList().getListItems().length > 0) {
      new PushButton("Clear All").click();
    } else {
      log.info("No drivers to clean, skipped");
    }
  }

  public void removeDriverLibrary(String driverLocation) {
    new DefaultList().select(driverLocation);
    new PushButton("Remove JAR/Zip").click();
  }

  private void addItem(final String item) {
    Display.syncExec(
        new Runnable() {
          @Override
          public void run() {
            new DefaultList().getSWTWidget().add(item);
          }
        });
  }
}