Java tutorial
/******************************************************************************* * Copyright (c) 2008, 2009 SOPERA GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * SOPERA GmbH - initial API and implementation *******************************************************************************/ package org.eclipse.swordfish.tooling.test.util; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.io.IOUtils; import org.eclipse.osgi.util.ManifestElement; import org.eclipse.swordfish.tooling.target.platform.test.AllTests; import org.eclipse.swordfish.tooling.target.platform.test.TestConstants; import org.eclipse.swordfish.tooling.target.platform.test.ide.EclipseIDE; import org.eclipse.swordfish.tooling.target.platform.test.ide.MacEclipseIDE; import org.eclipse.swordfish.tooling.target.platform.test.ide.WinEclipseIDE; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Shell; import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.StringResult; import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.osgi.framework.BundleException; /** * Class contains a lot of util methods for SWTbot tests. * @author yshamin * */ public class Util { private static final int WAIT_INTERVAL = 50; /** * Eclipse IDE instance. Depends on os (win, mac) */ public static final EclipseIDE IDE; static { if (System.getProperty("os.name").toUpperCase().startsWith("MAC")) { IDE = new MacEclipseIDE(); } else { IDE = new WinEclipseIDE(); } } /** * Emulates key press in specified display * @param keyCode - ascii code of key to press * @param display - display */ public static void pressKey(final char keyCode, final Display display) { display.post(getKeyDownEvent(keyCode)); try { Thread.sleep(70); } catch (InterruptedException e) { ; /*nothing to do*/ } display.post(getKeyUpEvent(keyCode)); } /** * Emulates Enter key press in specified display * @param display - display */ public static void pressEnter(final Display display) { pressKey(SWT.CR, display); } private static Event getKeyDownEvent(char keyCode) { Event event = new Event(); event.type = SWT.KeyDown; event.keyCode = keyCode; event.character = keyCode; return event; } private static Event getKeyUpEvent(char keyCode) { Event event = new Event(); event.type = SWT.KeyUp; event.keyCode = keyCode; event.character = keyCode; return event; } /** * Convert inputStream to String. * @param in - input stream * @param ignoreWhiteSpaces - if true, ignore white spaces in comparison * @return string value of the input stream * @throws IOException - in case errors */ public static String asString(final InputStream in, boolean ignoreWhiteSpaces) throws IOException { StringBuilder sb = new StringBuilder(); if (in != null) { try { int c = in.read(); while (c > -1) { if (ignoreWhiteSpaces && !Character.isWhitespace(c)) { sb.append((char) c); } c = in.read(); } } finally { in.close(); } } return sb.toString(); } /** * Convert inputStream to String. * @param in - input stream * @return string value of the input stream * @throws IOException - in case errors */ public static String asString(final InputStream in) throws IOException { return asString(in, false); } /** * Return a normalized (sorted) String representation of a manifest * @param manifestStream - the manifest input stream * @param excludeHeader - a key to be excluded from the manifest * @return a String with sorted headers and removed excludeHeader * @throws IOException - in case of problems loading the stream. */ public static String getNormalizedManifest(InputStream manifestStream, String excludeHeader) throws IOException { StringBuilder sb = new StringBuilder(); try { Map<String, String> unsorted; unsorted = new LinkedHashMap<String, String>(); ManifestElement.parseBundleManifest(manifestStream, unsorted); unsorted.remove(excludeHeader); Map<String, String> sorted = new TreeMap<String, String>(unsorted); for (String key : sorted.keySet()) { sb.append(key); sb.append(": "); sb.append(sorted.get(key)); sb.append('\n'); } } catch (BundleException e) { throw new IOException(e.toString()); } finally { try { if (manifestStream != null) manifestStream.close(); } catch (IOException e1) { //Ignore } } return sb.toString(); } /** * Waits for specified amount of milliseconds the specified tester to return true * @param tester - IWaitTester instance * @param timeout - amount of milliseconds to wait * @param timeoutMessage - message of InterruptedException in case of timeout * @throws InterruptedException - in case waiting timed out */ public static void waitFor(IWaitTester tester, int timeout, final String timeoutMessage) throws InterruptedException { int counter = timeout / WAIT_INTERVAL; while ((counter > 0) && !(tester.test())) { Thread.sleep(WAIT_INTERVAL); counter--; } if (counter <= 0) { throw new InterruptedException(timeoutMessage); } } /** * Wait specified button to become enabled for specified amount of time * @param button - button to be waited for * @param timeout - amount of milliseconds to wait * @throws InterruptedException in case button failed to be enabled in specified timeout */ public static void waitForButtonToEnable(final SWTBotButton button, final int timeout) throws InterruptedException { waitFor(new IWaitTester() { public boolean test() { return button.isEnabled(); } }, timeout, button + "failed to became enabled"); } /** * Waits for specified amount of milliseconds the specified button to appear * @param bot - current SWTEclipseBot instance * @param buttonCaption - caption of button to wait * @param timeout - amount of milliseconds to wait * @throws InterruptedException - in case waiting timed out */ public static void waitForButtonToAppear(final SWTWorkbenchBot bot, final String buttonCaption, int timeout) throws InterruptedException { waitFor(new IWaitTester() { public boolean test() { try { System.setProperty("org.eclipse.swtbot.search.timeout", "200"); bot.button(buttonCaption); System.setProperty("org.eclipse.swtbot.search.timeout", "5000"); return true; //if button with the caption exists - we're done } catch (WidgetNotFoundException e) { return false; } } }, timeout, "Button with caption " + buttonCaption + " hasn't appear in " + timeout + " miliseconds"); } /** * Waits for specified amount of milliseconds the specified window to appear * @param bot - current SWTEclipseBot instance * @param windowName - Title of window to activate * @param timeout - amount of milliseconds to wait * @throws InterruptedException - in case waiting timed out */ public static void waitForWindowToAppear(SWTWorkbenchBot bot, final String windowName, int timeout) throws InterruptedException { waitForWindow(bot, windowName, true, timeout); } /** * Waits for specified amount of milliseconds the specified window to disappear * @param bot - current SWTEclipseBot instance * @param windowName - Title of window to activate * @param timeout - amount of milliseconds to wait * @throws InterruptedException - in case waiting timed out */ public static void waitForWindowToDisappear(SWTWorkbenchBot bot, final String windowName, int timeout) throws InterruptedException { waitForWindow(bot, windowName, false, timeout); } private static void waitForWindow(final SWTWorkbenchBot bot, final String windowName, final boolean waitForAppear, int timeout) throws InterruptedException { waitFor(new IWaitTester() { public boolean test() { bot.getFinder().setShouldFindInvisibleControls(true); final Shell[] shells = bot.getFinder().getShells(); bot.getFinder().setShouldFindInvisibleControls(false); String actualWindowName = UIThreadRunnable.syncExec(new StringResult() { public String run() { for (Shell shell : shells) { try { if (shell.getText().contains(windowName)) { return shell.getText(); } } catch (SWTException e) { //shell exists no more, no need to return it's caption ;) } } return null; } }); if (((null != actualWindowName) && waitForAppear) || ((null == actualWindowName) && !waitForAppear)) { if (waitForAppear) { bot.shell(actualWindowName).activate(); } return true; //we found it! } else { return false; } } }, timeout, "Window with caption " + windowName + " hasn't " + (waitForAppear ? "appeared" : "disappeared") + " in " + timeout + " milliseconds"); } /** * Maximize some view. * @param bot - current SWTEclipseBot instance * @param viewName - view name to maximize */ public static void maximizeView(SWTWorkbenchBot bot, String viewName) { bot.viewByTitle(viewName).setFocus(); bot.menu("Window").menu("Navigation").menu("Maximize Active View or Editor").click(); } /** * Maximize some view. * @param bot - current SWTEclipseBot instance * @param viewName - view name to minimize */ public static void minimizeView(SWTWorkbenchBot bot, String viewName) { bot.viewByTitle(viewName).setFocus(); bot.menu("Window").menu("Navigation").menu("Minimize Active View or Editor").click(); } /** * Open Closed Project, project should be imported to workspace before test execution * @param projectName */ public static void openProject(SWTWorkbenchBot bot, String projectName) throws Exception { Util.waitForWindowToAppear(bot, TestConstants.WINDOW_ECLIPSE_SDK, TestConstants.TIMEOUT_FOR_REFRESHING); Util.maximizeView(bot, TestConstants.VIEW_PACKAGE_EXPLORER); bot.viewByTitle(TestConstants.VIEW_PACKAGE_EXPLORER).show(); bot.viewByTitle(TestConstants.VIEW_PACKAGE_EXPLORER).setFocus(); bot.tree().select(0); bot.tree().expandNode(projectName).click(); bot.tree().expandNode(projectName).contextMenu("Open Project").click(); // bot.button(TestConstants.BUTTON_YES).click(); Util.waitForWindowToDisappear(bot, "Open Project", TestConstants.TIMEOUT_REMOTE); Util.waitForWindowToAppear(bot, TestConstants.WINDOW_ECLIPSE_SDK, TestConstants.TIMEOUT_FOR_REFRESHING); } public static List<String> readErrorConsole(SWTWorkbenchBot bot, boolean minimizeAfterRead) throws Exception { bot.viewByTitle("Error Log").show(); bot.viewByTitle("Error Log").setFocus(); SWTBotTreeItem[] items = bot.tree().getAllItems(); int currentLength = -1; int countIterations = 0; // if error console appeared we need to close it while (currentLength != items.length && countIterations < 20) { items = bot.tree().getAllItems(); currentLength = items.length; countIterations++; Thread.sleep(TestConstants.TIME_OUT_REFRESH_CONSOLE); } List<String> result = new ArrayList<String>(); for (SWTBotTreeItem item : items) { result.add(item.getText()); } if (minimizeAfterRead) { Util.minimizeView(bot, TestConstants.VIEW_PACKAGE_EXPLORER); } return result; } public static void editTestWSDLFile(SWTWorkbenchBot bot, String projectName, String fileName) throws Exception { Util.waitForWindowToAppear(bot, TestConstants.WINDOW_ECLIPSE_SDK, TestConstants.TIMEOUT_FOR_REFRESHING); Util.maximizeView(bot, TestConstants.VIEW_PACKAGE_EXPLORER); SWTBotTreeItem wsdlFile = null; while (!bot.activeView().getTitle().equals(TestConstants.VIEW_PACKAGE_EXPLORER)) { Thread.sleep(TestConstants.TIMEOUT_FOR_ENABLE); Util.maximizeView(bot, TestConstants.VIEW_PACKAGE_EXPLORER); } bot.tree().select(0); bot.tree().expandNode(projectName).click(); wsdlFile = bot.tree().expandNode(projectName).getNode(fileName); wsdlFile.select(); wsdlFile.contextMenu("Open").click(); //wsdlFile.doubleClick(); bot.editorByTitle(fileName).toTextEditor().setText(getWSDL(fileName)); bot.editorByTitle(fileName).save(); } private static String getWSDL(String templateName) throws IOException { InputStream url = AllTests.class.getResourceAsStream(templateName); String wsdl = IOUtils.toString(url); return wsdl; } }