index
int64
repo_id
string
file_path
string
content
string
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Annotation.java
package abbot.script; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import org.jdom.*; import org.jdom.Element; import abbot.*; import abbot.finder.*; import abbot.i18n.Strings; import abbot.util.Properties; /** Provides a method for communicating a message on the display. May display for a reasonable delay or require user input to continue.<p> Usage:<br> <blockquote><code> &lt;annotation [userDismiss="true"] &gt;Text or HTML message&lt;/annotation&gt;<br> </code></blockquote> <p> Properties:<br> abbot.annotation.min_delay: minimum time to display an annotation<br> abbot.annotation.delay: per-word time to display an annotation<br> */ public class Annotation extends Step { public static final String TAG_ANNOTATION = "annotation"; public static final String TAG_USER_DISMISS = "userDismiss"; private static final String USAGE = "<annotation [title=\"...\"] [component=\"<component ID>\"] [x=XX y=YY] [width=WWW height=HHH] [userDismiss=\"true\"]>Text or HTML message</annotation>"; private static final int WORD_SIZE = 6; private static final Color BACKGROUND = new Color((Color.yellow.getRed() + Color.white.getRed()*3)/4, (Color.yellow.getGreen() + Color.white.getGreen()*3)/4, (Color.yellow.getBlue() + Color.white.getBlue()*3)/4); private String title; private String componentID; private boolean userDismiss; private static int minDelay = 5000; private static int delayUnit = 250; private String text = ""; private int x = -1; private int y = -1; private int width = -1; private int height = -1; class WindowLock {} private transient Object WINDOW_LOCK = new WindowLock(); private transient volatile Frame frame; private transient volatile AnnotationWindow window; private transient Point anchorPoint; private transient boolean ignoreChanges; static { minDelay = Properties.getProperty("abbot.annotation.min_delay", minDelay, 0, 10000); delayUnit = Properties.getProperty("abbot.annotation.delay_unit", delayUnit, 1, 5000); } public Annotation(Resolver resolver, Element el, Map attributes) { super(resolver, attributes); componentID = (String)attributes.get(TAG_COMPONENT); userDismiss = attributes.get(TAG_USER_DISMISS) != null; setTitle((String)attributes.get(TAG_TITLE)); String xs = (String)attributes.get(TAG_X); String ys = (String)attributes.get(TAG_Y); if (xs != null && ys != null) { try { x = Integer.parseInt(xs); y = Integer.parseInt(ys); } catch(NumberFormatException nfe) { x = y = -1; } } String ws = (String)attributes.get(TAG_WIDTH); String hs = (String)attributes.get(TAG_HEIGHT); if (ws != null & hs != null) { try { width = Integer.parseInt(ws); height = Integer.parseInt(hs); } catch(NumberFormatException nfe) { width = height = -1; } } String text = null; Iterator iter = el.getContent().iterator(); while(iter.hasNext()) { Object obj = iter.next(); if (obj instanceof CDATA) { text = ((CDATA)obj).getText(); break; } } if (text == null) { text = el.getText(); } setText(text); } public Annotation(Resolver resolver, String description) { super(resolver, description); } public boolean isShowing() { synchronized(WINDOW_LOCK) { return window != null; } } private void showAnnotationWindow() { Window win = getWindow(); win.pack(); Point where = null; if (anchorPoint != null) { where = new Point(anchorPoint); } if (x != -1 && y != -1) { if (where != null) { where.x += x; where.y += y; } else { where = new Point(x, y); } } if (where != null) { win.setLocation(where); } if (width != -1 && height != -1) { win.setSize(new Dimension(width, height)); } win.setVisible(true); } public void showAnnotation() { dispose(); if (SwingUtilities.isEventDispatchThread()) { showAnnotationWindow(); } else try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { showAnnotationWindow(); } }); SwingUtilities.invokeAndWait(new Runnable() { public void run() { } }); } catch(Exception e) { Log.warn(e); } } public long getDelayTime() { long time = (getText().length() / WORD_SIZE) * delayUnit; return Math.max(time, minDelay); } /** Display a non-modal window. */ protected void runStep() throws Throwable { ignoreChanges = true; showAnnotation(); ignoreChanges = false; long start = System.currentTimeMillis(); while ((userDismiss && window != null && window.isShowing()) || (!userDismiss && System.currentTimeMillis() - start < getDelayTime())) { abbot.tester.Robot.delay(200); Thread.yield(); } if (!userDismiss) { dispose(); } } public Window getWindow() { synchronized(WINDOW_LOCK) { if (window == null) { window = createWindow(); } return window; } } // expects to have the WINDOW_LOCK private AnnotationWindow createWindow() { Component parent = null; AnnotationWindow w = null; Frame f = null; anchorPoint = null; if (componentID != null) { try { parent = (Component)ArgumentParser.eval(getResolver(), componentID, Component.class); Point loc = parent.getLocationOnScreen(); anchorPoint = new Point(loc.x, loc.y); while (!(parent instanceof Dialog) && !(parent instanceof Frame)) { parent = parent.getParent(); } w = (parent instanceof Dialog) ? (title != null ? new AnnotationWindow((Dialog)parent, title) : new AnnotationWindow((Dialog)parent)) : (title != null ? new AnnotationWindow((Frame)parent, title) : new AnnotationWindow((Frame)parent)); } catch(ComponentSearchException e) { // Ignore the exception and display it in global coords Log.warn(e); } catch(NoSuchReferenceException nsr) { // Ignore the exception and display it in global coords Log.warn(nsr); } } if (w == null) { f = new Frame(); w = (title != null) ? new AnnotationWindow(f, title) : new AnnotationWindow(f); } JPanel pane = (JPanel)w.getContentPane(); pane.setBackground(BACKGROUND); pane.setLayout(new BorderLayout()); pane.setBorder(new EmptyBorder(4,4,4,4)); JLabel label = new JLabel(replaceNewlines(text)); pane.add(label, BorderLayout.CENTER); if (userDismiss) { JPanel bottom = new JPanel(new BorderLayout()); bottom.setBackground(BACKGROUND); JButton close = new JButton(Strings.get("annotation.continue")); bottom.add(close, BorderLayout.EAST); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { dispose(); } }); pane.add(bottom, BorderLayout.SOUTH); } // If the user closes the window, make sure we continue execution w.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose(); } public void windowClosed(WindowEvent we) { dispose(); } }); frame = f; return w; } private void dispose() { Window w; Frame f; synchronized(WINDOW_LOCK) { w = window; f = frame; window = null; frame = null; } if (w != null) { if (f != null) { getResolver().getHierarchy().dispose(f); } getResolver().getHierarchy().dispose(w); } } private String replaceNewlines(String text) { boolean needsHTML = false; String[] breaks = { "\r\n", "\n" }; for (int i=0;i < breaks.length;i++) { int index = text.indexOf(breaks[i]); while (index != -1) { needsHTML = true; text = text.substring(0, index) + "<br>" + text.substring(index + breaks[i].length()); index = text.indexOf(breaks[i]); } } if (needsHTML && !text.startsWith("<html>")) { text = "<html>" + text + "</html>"; } return text; } private void updateWindowSize(Window win) { if (window != win) return; Dimension size = win.getSize(); width = size.width; height = size.height; } private void updateWindowPosition(Window win) { if (window != win) return; Point where = win.getLocation(); x = where.x; y = where.y; if (anchorPoint != null) { // Update the window location x -= anchorPoint.x; y -= anchorPoint.y; } } public String getDefaultDescription() { String desc = "Annotation"; if (!"".equals(getText())) { desc += ": " + getText(); } return desc; } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_ANNOTATION; } protected Element addContent(Element el) { return el.addContent(new CDATA(getText())); } public Map getAttributes() { Map map = super.getAttributes(); if (componentID != null) { map.put(TAG_COMPONENT, componentID); } if (userDismiss) { map.put(TAG_USER_DISMISS, "true"); } if (title != null) { map.put(TAG_TITLE, title); } if (x != -1 || y != -1) { map.put(TAG_X, String.valueOf(x)); map.put(TAG_Y, String.valueOf(y)); } if (width != -1 || height != -1) { map.put(TAG_WIDTH, String.valueOf(width)); map.put(TAG_HEIGHT, String.valueOf(height)); } return map; } public boolean getUserDismiss() { return userDismiss; } public void setUserDismiss(boolean state) { userDismiss = state; } public String getRelativeTo() { return componentID; } public void setRelativeTo(String id) { componentID = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } public void setDisplayLocation(Point pt) { if (pt != null) { x = pt.x; y = pt.y; } else { x = y = -1; } } public Point getDisplayLocation() { if (x != -1 || y != -1) return new Point(x, y); return null; } class AnnotationWindow extends JDialog { public AnnotationWindow(Dialog parent, String title) { super(parent, title); addListener(); } public AnnotationWindow(Dialog parent) { super(parent); addListener(); } public AnnotationWindow(Frame parent, String title) { super(parent, title); addListener(); } public AnnotationWindow(Frame parent) { super(parent); addListener(); } private void addListener() { addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent ce) { if (!ignoreChanges && AnnotationWindow.this.isShowing()) updateWindowSize(AnnotationWindow.this); } public void componentMoved(ComponentEvent ce) { if (!ignoreChanges && AnnotationWindow.this.isShowing()) updateWindowPosition(AnnotationWindow.this); } }); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/AppClassLoader.java
package abbot.script; import java.awt.*; import java.util.EmptyStackException; import javax.swing.SwingUtilities; import abbot.Log; import abbot.i18n.Strings; import abbot.util.*; /** * A custom class loader which installs itself as if it were the application * class loader. A classpath of null is equivalent to the system property * java.class.path.<p> * The class loader may optionally load a class <i>before</i> the parent class * loader gets a chance to look for the class (instead of the default * behavior, which always delegates to the parent class loader first). This * behavior enables the class to be reloaded simply by using a new instance of * this class loader with each launch of the app.<p> * This class mimics the behavior of sun.misc.Launcher$AppClassLoader as much * as possible.<p> * Bootstrap classes are always delegated to the bootstrap loader, with the * exception of the sun.applet package, which should never be delegated, since * it does not work properly unless it is reloaded.<p> * The parent of this class loader will be the normal, default AppClassLoader * (specifically, the class loader which loaded this class will be used). */ public class AppClassLoader extends NonDelegatingClassLoader { /** A new event queue installed for the lifetime of this class loader. */ private AppEventQueue eventQueue; /** This class loader is used to load bootstrap classes that must be * preloaded. */ private BootstrapClassLoader bootstrapLoader; /** For use in checking if a class is in the framework class path. */ private NonDelegatingClassLoader extensionsLoader; /** Whether the framework itself is being tested. */ private boolean frameworkIsUnderTest = false; /** Old class loader context for the thread where this loader was * installed. */ private ClassLoader oldClassLoader = null; private Thread installedThread = null; private String oldClassPath = null; private class InstallationLock {} private InstallationLock lock = new InstallationLock(); /** Constructs an AppClassLoader using the current classpath (as found in java.class.path). */ public AppClassLoader() { this(null); } /** * Constructs a AppClassLoader with a custom classpath, indicating * whether the class loader should delegate to its parent class loader * prior to searching for a given resource.<p> * The class path argument may use either a colon or semicolon to separate * its elements.<p> */ public AppClassLoader(String classPath) { super(classPath, AppClassLoader.class.getClassLoader()); bootstrapLoader = new BootstrapClassLoader(); // Use this one to look up extensions; we want to reload them, but may // need to look in the framework class path for them. // Make sure it *only* loads extensions, though, and defers all other // lookups to its parent. extensionsLoader = new NonDelegatingClassLoader(System.getProperty("java.class.path"), AppClassLoader.class. getClassLoader()) { protected boolean shouldDelegate(String name) { return !isExtension(name); } }; // Don't want to open a whole new can of class loading worms! /* // If we're testing the framework itself, then absolutely DO NOT // delegate those classes. if (getClassPath().indexOf("abbot.jar") != -1) { frameworkIsUnderTest = true; } */ } public boolean isEventDispatchThread() { return (eventQueue != null && Thread.currentThread() == eventQueue.thread) || (eventQueue == null && SwingUtilities.isEventDispatchThread()); } /** Should the parent class loader try to load this class first? */ // FIXME we should only need the delegate flag if stuff in the classpath // is also found on the system classpath, e.g. the framework itself // Maybe just set it internally in case the classpaths overlap? protected boolean shouldDelegate(String name) { return bootstrapLoader.shouldDelegate(name) && !isExtension(name) && !(frameworkIsUnderTest && isFrameworkClass(name)); } private boolean isFrameworkClass(String name) { return name.startsWith("abbot.") || name.startsWith("junit.extensions.abbot."); } private boolean isExtension(String name) { return name.startsWith("abbot.tester.extensions.") || name.startsWith("abbot.script.parsers.extensions."); } /** * Finds and loads the class with the specified name from the search * path. If the class is a bootstrap class and must be preloaded, use our * own bootstrap loader. If it is an extension class, use our own * extensions loader. * * @param name the name of the class * @return the resulting class * @exception ClassNotFoundException if the class could not be found */ public Class findClass(String name) throws ClassNotFoundException { if (isBootstrapClassRequiringReload(name)) { try { return bootstrapLoader.findClass(name); } catch(ClassNotFoundException cnf) { Log.warn(cnf); } } // Look for extensions first in the framework class path (with a // special loader), then in the app class path. // Extensions *must* have the same class loader as the corresponding // custom components try { return super.findClass(name); } catch(ClassNotFoundException cnf) { if (isExtension(name)) { return extensionsLoader.findClass(name); } throw cnf; } } /** Ensure that everything else subsequently loaded on the same thread or * any subsequently spawned threads uses the given class loader. Also * ensure that classes loaded by the event dispatch thread and threads it * spawns use the given class loader. */ public void install() { if (SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException(Strings.get("appcl.invalid_state")); } if (installedThread != null) { String msg = Strings.get("appcl.already_installed", new Object[] { installedThread }); throw new IllegalStateException(msg); } // Change the effective classpath, but make sure it's available if // someone needs to access it. oldClassPath = System.getProperty("java.class.path"); System.setProperty("abbot.class.path", oldClassPath); System.setProperty("java.class.path", getClassPath()); Log.debug("java.class.path set to " + System.getProperty("java.class.path")); // Install our own handler for catching exceptions on the event // dispatch thread. try { new EventExceptionHandler().install(); } catch(Exception e) { // ignore any exceptions, since they're not fatal } eventQueue = new AppEventQueue(); eventQueue.install(); Thread current = Thread.currentThread(); installedThread = current; oldClassLoader = installedThread.getContextClassLoader(); installedThread.setContextClassLoader(this); } public boolean isInstalled() { synchronized(lock) { return eventQueue != null; } } /** Reverse the effects of install. Has no effect if the class loader * has not been installed on any thread. */ public void uninstall() { // Ensure that no two threads attempt to uninstall synchronized(lock) { if (eventQueue != null) { eventQueue.uninstall(); eventQueue = null; } if (installedThread != null) { installedThread.setContextClassLoader(oldClassLoader); oldClassLoader = null; installedThread = null; System.setProperty("java.class.path", oldClassPath); oldClassPath = null; } } } private class AppEventQueue extends EventQueue { private Thread thread; /** Ensure the class loader for the event dispatch thread is the right one. */ public void install() { Runnable installer = new Runnable() { public void run() { Toolkit.getDefaultToolkit(). getSystemEventQueue().push(AppEventQueue.this); } }; // Avoid deadlock with the event queue, in case it has the tree // lock (pickens). AWT.invokeAndWait(installer); Runnable threadTagger = new Runnable() { public void run() { thread = Thread.currentThread(); thread.setContextClassLoader(AppClassLoader.this); thread.setName(thread.getName() + " (AppClassLoader)"); } }; AWT.invokeAndWait(threadTagger); } /** Pop this and any subsequently pushed event queues. */ public void uninstall() { Log.debug("Uninstalling AppEventQueue"); try { pop(); thread = null; } catch(EmptyStackException ese) { } Log.debug("AppEventQueue uninstalled"); } public String toString() { return "Abbot AUT Event Queue (thread=" + thread + ")"; } } /** List of bootstrap classes we most definitely want to be loaded by this * class loader, rather than any parent, or the bootstrap loader. */ private String[] mustReloadPrefixes = { "sun.applet.", // need the whole package, not just AppletViewer/Main }; /** Does the given class absolutely need to be preloaded? */ private boolean isBootstrapClassRequiringReload(String name) { for (int i=0;i < mustReloadPrefixes.length;i++) { if (name.startsWith(mustReloadPrefixes[i])) return true; } return false; } /** Returns the path to the primary JRE classes, not including any * extensions. This is primarily needed for loading * sun.applet.AppletViewer/Main, since most other classes in the bootstrap * path should <i>only</i> be loaded by the bootstrap loader. */ private static String getBootstrapPath() { return System.getProperty("sun.boot.class.path"); } /** Provide access to bootstrap classes that we need to be able to * reload. */ private class BootstrapClassLoader extends NonDelegatingClassLoader { public BootstrapClassLoader() { super(getBootstrapPath(), null); } protected boolean shouldDelegate(String name) { // Exclude all bootstrap classes, except for those we know we // *must* be reloaded on each run in order to have function // properly (e.g. applet) return !isBootstrapClassRequiringReload(name) && !"abbot.script.AppletSecurityManager".equals(name); } } public String toString() { return super.toString() + " (java.class.path=" + System.getProperty("java.class.path") + ")"; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/AppletSecurityManager.java
package abbot.script; import abbot.ExitException; import javax.swing.SwingUtilities; /** This security manager extends sun.applet.AppletSecurity b/c * AppletViewer does some casts that assume that is the only security * manager that will be installed. It has to permit everything, though, or * the framework will be hampered. Because of this, it isn't a reliable test * of an applet responding well to restricted permissions. */ // FIXME need to determine what causes the class circularity errors and then // defer to the AppletSecurity // NOTE: don't see the class circularity any more, maybe the class loading // restructuring in 0.9/0.10 has fixed it? public class AppletSecurityManager extends sun.applet.AppletSecurity { SecurityManager parent; boolean removeOnExit; public AppletSecurityManager(SecurityManager sm) { this(sm, false); } public AppletSecurityManager(SecurityManager sm, boolean removeOnExit) { parent = sm; this.removeOnExit = removeOnExit; } public void checkPermission(java.security.Permission perm, Object context) { if (parent != null) { parent.checkPermission(perm, context); } } public void checkPermission(java.security.Permission perm) { if (parent != null) { parent.checkPermission(perm); } } public void checkExit(int status) { if (removeOnExit) { System.setSecurityManager(parent); } throw new ExitException("Applet System.exit disallowed on " + Thread.currentThread(), status); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Appletviewer.java
package abbot.script; import java.awt.Component; import java.awt.Frame; import java.awt.event.*; import java.applet.*; import java.util.*; import java.io.*; import java.lang.reflect.*; import javax.swing.SwingUtilities; import abbot.Log; import abbot.NoExitSecurityManager; import abbot.finder.*; import abbot.finder.matchers.*; import abbot.i18n.Strings; import abbot.tester.ComponentTester; /** * Provides applet launch capability. Usage:<br> * <blockquote><code> * &lt;applet code="..." [codebase="..."] [params="..."] * [archive="..."]&gt;<br> * </code></blockquote><p> * The attributes are equivalent to those provided in the HTML * <code>applet</code> tag. The <code>params</code> attribute is a * comma-separated list of <code>name=value</code> pairs, which will be passed * to the applet within the <code>applet</code> tag as <code>param</code> * elements. * <p> * <em>WARNING: Closing the appletviewer window from the window manager * close button will result applet-spawned event dispatch threads being left * running. To avoid this situation, always use the appletviewer <b>Quit</b> * menu item or use the {@link #terminate()} method of this class.</em> */ public class Appletviewer extends Launch { private String code; private Map params; private String codebase; private String archive; private String width; private String height; private ClassLoader appletClassLoader; private Frame appletViewerFrame; private transient SecurityManager oldSM; private transient boolean terminating; private static final String DEFAULT_WIDTH = "100"; private static final String DEFAULT_HEIGHT = "100"; private static final String CLASS_NAME = "sun.applet.Main"; private static final String METHOD_NAME = "main"; private static final int LAUNCH_TIMEOUT = 30000; private static final String USAGE = "<appletviewer code=\"...\" [params=\"name1=value1,...\"] " + "[codebase=\"...\"] [archive=\"...\"]>"; protected void quitApplet(final Frame frame) { // FIXME: this isn't locale-safe // Don't need to wait for idle // get menu strings from resource(localized by Sun) String menuPath; try { ResourceBundle rb = ResourceBundle.getBundle("sun.applet.resources.MsgAppletViewer"); menuPath = rb.getString("appletviewer.menu.applet") + "|" + rb.getString("appletviewer.menuitem.quit"); } catch (MissingResourceException mre) { menuPath = "Applet|Quit"; Log.warn("Cannot access the sun applet resources, falling back to english version", mre); } Log.debug("applet quit menu path is '" + menuPath + "'."); // set UncaughtExceptionHandler. Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (e instanceof abbot.ExitException) { // without this, applet's main thread will report error. } else { Log.warn(e); } } }); new ComponentTester().selectAWTMenuItem(frame, menuPath); } private static Map patchAttributes(Map map) { map.put(TAG_CLASS, CLASS_NAME); map.put(TAG_METHOD, METHOD_NAME); return map; } /** Create an applet-launching step. */ public Appletviewer(Resolver resolver, Map attributes) { super(resolver, patchAttributes(attributes)); code = (String)attributes.get(TAG_CODE); params = parseParams((String)attributes.get(TAG_PARAMS)); codebase = (String)attributes.get(TAG_CODEBASE); archive = (String)attributes.get(TAG_ARCHIVE); width = (String)attributes.get(TAG_WIDTH); height = (String)attributes.get(TAG_HEIGHT); } /** Create an applet-launching step. */ public Appletviewer(Resolver resolver, String description, String code, Map params, String codebase, String archive, String classpath) { super(resolver, description, CLASS_NAME, METHOD_NAME, null, classpath, false); this.code = code; this.params = params; this.codebase = codebase; this.archive = archive; } /** Run this step. Causes the appropriate HTML file to be written for use by appletviewer and its path used as the sole argument. */ public void runStep() throws Throwable { File dir = new File(System.getProperty("user.dir")); File htmlFile = File.createTempFile("abbot-applet", ".html", dir); htmlFile.deleteOnExit(); try { FileOutputStream os = new FileOutputStream(htmlFile); os.write(generateHTML().getBytes()); os.close(); setArguments(new String[] { "[" + htmlFile.getName() + "]" }); super.runStep(); // Wait for the applet to become visible long start = System.currentTimeMillis(); ComponentFinder finder = new BasicFinder(getResolver().getHierarchy()); Matcher matcher = new ClassMatcher(Applet.class, true); while (true) { try { Component c = finder.find(matcher); appletViewerFrame = (Frame) SwingUtilities.getWindowAncestor(c); addCloseListener(appletViewerFrame); appletClassLoader = c.getClass().getClassLoader(); break; } catch(ComponentSearchException e) { } if (System.currentTimeMillis() - start > LAUNCH_TIMEOUT) { throw new RuntimeException(Strings.get("step.appletviewer.launch_timed_out")); } Thread.sleep(200); } } finally { htmlFile.delete(); } } private void addCloseListener(final Frame frame) { // Workaround for lockup when applet is closed via WM close button and // then relaunched. Can't figure out how to kill those extant threads. // This avoids the lockup, but leaves threads around. frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Log.debug("window closing"); quitApplet(frame); } }); } /** Generate HTML suitable for launching this applet. */ protected String generateHTML() { StringBuffer html = new StringBuffer(); html.append("<html><applet code=\"" + getCode() + "\""); html.append(" width=\"" + getWidth() + "\"" + " height=\"" + getHeight() + "\""); if (getCodebase() != null) { html.append(" codebase=\"" + getCodebase() + "\""); } if (getArchive() != null) { html.append(" archive=\"" + getArchive() + "\""); } html.append(">"); Iterator iter = params.keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); String value = (String)params.get(key); html.append("<param name=\"" + key + "\" value=\"" + value + "\">"); } html.append("</applet></html>"); return html.toString(); } public void setTargetClassName(String name) { if (CLASS_NAME.equals(name)) super.setTargetClassName(name); else throw new IllegalArgumentException(Strings.get("step.call.immutable_class")); } public void setMethodName(String name) { if (METHOD_NAME.equals(name)) super.setMethodName(name); else throw new IllegalArgumentException(Strings.get("step.call.immutable_method")); } public void setCode(String code) { this.code = code; } public String getCode() { return code; } public void setCodebase(String codebase) { this.codebase = codebase; } public String getCodebase() { return codebase; } public void setArchive(String archive) { this.archive = archive; } public String getArchive() { return archive; } public String getWidth() { return width != null ? width : DEFAULT_WIDTH; } public void setWidth(String width) { this.width = width; try { Integer.parseInt(width); } catch(NumberFormatException e) { this.width = null; } } public String getHeight() { return height != null ? height : DEFAULT_HEIGHT; } public void setHeight(String height) { this.height = height; try { Integer.parseInt(height); } catch(NumberFormatException e) { this.height = null; } } public Map getParams() { return params; } public void setParams(Map params) { this.params = params; } protected Map parseParams(String attribute) { Map map = new HashMap(); if (attribute != null) { String[] list = ArgumentParser.parseArgumentList(attribute); for (int i=0;i < list.length;i++) { String p = list[i]; int eq = p.indexOf("="); map.put(p.substring(0, eq), p.substring(eq + 1)); } } return map; } public String[] getParamsAsArray() { ArrayList list = new ArrayList(); // Ensure we always get a consistent order Iterator iter = new TreeMap(params).keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); String value = (String)params.get(key); list.add(key + "=" + value); } return (String[])list.toArray(new String[list.size()]); } public String getParamsAttribute() { return ArgumentParser.encodeArguments(getParamsAsArray()); } public Map getAttributes() { Map map = super.getAttributes(); map.put(TAG_CODE, getCode()); if (params.size() > 0) map.put(TAG_PARAMS, getParamsAttribute()); if (getCodebase() != null) map.put(TAG_CODEBASE, getCodebase()); if (getArchive() != null) map.put(TAG_ARCHIVE, getArchive()); if (!DEFAULT_WIDTH.equals(getWidth())) map.put(TAG_WIDTH, getWidth()); if (!DEFAULT_HEIGHT.equals(getHeight())) map.put(TAG_HEIGHT, getHeight()); // don't need to store these map.remove(TAG_CLASS); map.remove(TAG_METHOD); map.remove(TAG_THREADED); map.remove(TAG_ARGS); return map; } public String getDefaultDescription() { String desc = Strings.get("step.appletviewer", new Object[] { getCode() }); return desc; } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_APPLETVIEWER; } /** Returns the applet class loader. */ public ClassLoader getContextClassLoader() { // Maybe use codebase/archive to have an alternative classpath? return appletClassLoader != null ? appletClassLoader : super.getContextClassLoader(); } protected void install() { super.install(); // Appletviewer expects the security manager to be an instance of // AppletSecurity. Use the custom class loader, *not* the one for the // applet. installAppletSecurityManager(super.getContextClassLoader()); } /** Install a security manager if there is none; this is a workaround * to prevent sun's applet viewer's security manager from preventing * any classes from being loaded. */ private void installAppletSecurityManager(ClassLoader cl) { oldSM = System.getSecurityManager(); Log.debug("install security manager"); // NOTE: the security manager *must* be loaded with the same class // loader as the appletviewer. try { Class cls = Class.forName("abbot.script.AppletSecurityManager", true, cl); Constructor ctor = cls.getConstructor(new Class[] { SecurityManager.class, boolean.class, }); SecurityManager sm = (SecurityManager) ctor.newInstance(new Object[] { oldSM, new Boolean(removeSMOnExit()) }); System.setSecurityManager(sm); } catch(Exception exc) { Log.warn(exc); } } protected boolean removeSMOnExit() { return false; } protected Frame getFrame() { return appletViewerFrame; } /** To properly terminate, we need to invoke AppletViewer's appletQuit() * method (protected, but accessible). */ public void terminate() { synchronized(this) { // Avoid recursion, since we'll return here when the applet // invokes System.exit. if (terminating) return; terminating = true; } Frame frame = appletViewerFrame; appletViewerFrame = null; try { // FIXME: figure out why closing the appletviewer window causes an // EDT hangup. // Also figure out who's creating all the extra EDTs and dispose of // them properly, but it's probably not worth the effort. if (frame != null) { quitApplet(frame); } // Now clean up normally super.terminate(); while (System.getSecurityManager() != oldSM) { Thread.sleep(10); } Log.debug("SM restored"); appletClassLoader = null; oldSM = null; } catch(InterruptedException e) { Thread.currentThread().interrupt(); Log.warn(e); } finally { synchronized(this) { terminating = false; } } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/ArgumentParser.java
package abbot.script; import java.awt.Component; import java.lang.reflect.Array; import java.util.*; import abbot.*; import abbot.i18n.Strings; import abbot.finder.*; import abbot.script.parsers.Parser; import abbot.tester.*; import abbot.util.Condition; /** Provide parsing of a String into an array of appropriately typed * arguments. Arrays are indicated by square brackets, and arguments are * separated by commas, e.g.<br> * <ul> * <li>An empty String array (length zero): "[]" * <li>Three arguments "one,two,three" * <li>An array of length three: "[one,two,three]" * <li>A single-element array of integer: "[1]" * <li>A single null argument: "null" * <li>An array of two strings: "[one,two]" * <li>Commas must be escaped when they would otherwise be interpreted as an * argument separator:<br> * "one,two%2ctwo,three" (2nd argument is "two,two") */ public class ArgumentParser { private ArgumentParser() { } private static final String ESC_ESC_COMMA = "%%2C"; public static final String ESC_COMMA = "%2c"; public static final String NULL = "null"; public static final String DEFAULT_TOSTRING = "<default-tostring>"; /** Maps class names to their corresponding string parsers. */ private static Map parsers = new HashMap(); private static boolean isExtension(String name) { return name.indexOf(".extensions.") != -1; } private static Parser findParser(String name, Class targetClass) { Log.debug("Trying " + name + " for " + targetClass); try { Class cvtClass = isExtension(name) ? Class.forName(name, true, targetClass.getClassLoader()) : Class.forName(name); Parser parser = (Parser)cvtClass.newInstance(); if (cvtClass.getName().indexOf(".extensions.") == -1) parsers.put(targetClass, parser); return parser; } catch(InstantiationException ie) { Log.debug(ie); } catch(IllegalAccessException iae) { Log.debug(iae); } catch(ClassNotFoundException cnf) { Log.debug(cnf); } return null; } /** Set the parser for a given class. Returns the old one, if any. */ public static Parser setParser(Class cls, Parser parser) { Parser old = (Parser)parsers.get(cls); parsers.put(cls, parser); return old; } /** Find a string parser for the given class. Returns null if none * found. */ public static Parser getParser(Class cls) { Parser parser = (Parser)parsers.get(cls); // Load core testers with the current framework's class loader // context, and anything else in the context of the code under test if (parser == null) { String base = ComponentTester.simpleClassName(cls); String pkg = Parser.class.getPackage().getName(); parser = findParser(pkg + "." + base + "Parser", cls); if (parser == null) { parser = findParser(pkg + ".extensions." + base + "Parser", cls); } } return parser; } private static boolean isBounded(String s) { return s.startsWith("[") && s.endsWith("]") || s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'"); } public static String escapeCommas(String s) { return replace(replace(s, ESC_COMMA, ESC_ESC_COMMA), ",", ESC_COMMA); } private static String unescapeCommas(String s) { return replace(replace(s, ESC_COMMA, ","), ESC_ESC_COMMA, ESC_COMMA); } public static String encodeArguments(String[] args) { return joinArguments(args, true); } public static String rawArguments(String[] args) { return joinArguments(args, false); } private static String joinArguments(String[] args, boolean encode) { StringBuffer sb = new StringBuffer(); if (args.length > 0) { if (!encode || isBounded(args[0])) { sb.append(args[0]); } else { sb.append(escapeCommas(args[0])); } for (int i=1;i < args.length;i++) { sb.append(","); if (isBounded(args[i])) { sb.append(args[i]); } else { sb.append(escapeCommas(args[i])); } } } return sb.toString(); } private static class Tokenizer extends ArrayList { public Tokenizer(String input) { while (true) { int index = input.indexOf(","); if (index == -1) { add(input); break; } add(input.substring(0, index)); input = input.substring(index + 1); } } } /** Convert the given encoded String into an array of Strings. * Interprets strings of the format "[el1,el2,el3]" to be a single (array) * argument (such commas do not need escaping). <p> * Explicit commas and square brackets in arguments must be escaped by * preceding the character with a backslash ('\'). The strings * '(null)' and 'null' are interpreted as the value null.<p> * Explicit spaces should be protected by double quotes, e.g. * " an argument bounded by spaces ". */ public static String[] parseArgumentList(String encodedArgs) { ArrayList alist = new ArrayList(); if (encodedArgs == null || "".equals(encodedArgs)) return new String[0]; // handle old method of escaped commas encodedArgs = replace(encodedArgs, "\\,", ESC_COMMA); Iterator iter = new Tokenizer(encodedArgs).iterator(); while (iter.hasNext()) { String str = (String)iter.next(); if (str.trim().startsWith("[") && !str.trim().endsWith("]")) { while (iter.hasNext()) { String next = (String)iter.next(); str += "," + next; if (next.trim().endsWith("]")) { break; } } } else if (str.trim().startsWith("\"") && !str.trim().endsWith("\"")) { while (iter.hasNext()) { String next = (String)iter.next(); str += "," + next; if (next.trim().endsWith("\"")) { break; } } } else if (str.trim().startsWith("'") && !str.trim().endsWith("'")) { while (iter.hasNext()) { String next = (String)iter.next(); str += "," + next; if (next.trim().endsWith("'")) { break; } } } if (NULL.equals(str.trim())) { alist.add(null); } else { // If it's an array, don't unescape the commas yet if (!str.startsWith("[")) { str = unescapeCommas(str); } alist.add(str); } } return (String[])alist.toArray(new String[alist.size()]); } /** Performs property substitutions on the argument priort to evaluating * it. Substitutions are not recursive. */ public static String substitute(Resolver resolver, String arg) { if (arg == null) { return arg; } int i = 0; int marker = 0; StringBuffer sb = new StringBuffer(); while ((i = arg.indexOf("${", marker)) != -1) { if (marker < i) { sb.append(arg.substring(marker, i)); marker = i; } int end = arg.indexOf("}", i); if (end == -1) { break; } String name = arg.substring(i + 2, end); Object value = resolver.getProperty(name); if (value == null) { value = System.getProperty(name); } if (value == null) { value = arg.substring(i, end + 1); } sb.append(toString(value)); marker = end + 1; } sb.append(arg.substring(marker)); return sb.toString(); } /** Convert the given string into the given class, if possible, * using any available parsers if conversion to basic types fails. * The Resolver could be a parser, but it would need to adapt * automatically to whatever is the current context.<p> * Performs property substitution on the argument prior to evaluating it. * Spaces are only trimmed from the argument if spaces have no meaning for * the target class. */ public static Object eval(Resolver resolver, String arg, Class cls) throws IllegalArgumentException, NoSuchReferenceException, ComponentSearchException { // Perform property substitution arg = substitute(resolver, arg); Parser parser; Object result = null; try { if (arg == null || arg.equals(NULL)) { result = null; } else if (cls.equals(Boolean.class) || cls.equals(boolean.class)) { result = Boolean.valueOf(arg.trim()); } else if (cls.equals(Short.class) || cls.equals(short.class)) { result = Short.valueOf(arg.trim()); } else if (cls.equals(Integer.class) || cls.equals(int.class)) { result = Integer.valueOf(arg.trim()); } else if (cls.equals(Long.class) || cls.equals(long.class)) { result = Long.valueOf(arg.trim()); } else if (cls.equals(Float.class) || cls.equals(float.class)) { result = Float.valueOf(arg.trim()); } else if (cls.equals(Double.class) || cls.equals(double.class)) { result = Double.valueOf(arg.trim()); } else if (cls.equals(ComponentReference.class)) { ComponentReference ref = resolver.getComponentReference(arg.trim()); if (ref == null) throw new NoSuchReferenceException("The resolver " + resolver + " has no reference '" + arg + "'"); result = ref; } else if (Component.class.isAssignableFrom(cls)) { ComponentReference ref = resolver.getComponentReference(arg.trim()); if (ref == null) throw new NoSuchReferenceException("The resolver " + resolver + " has no reference '" + arg + "'"); // Avoid requiring the user to wait for a component to become // available, in most cases. In those cases where the // component creation is particularly slow, an explicit wait // can be added. // Note that this is not necessarily a wait for the component // to become visible, since menu items are not normally // visible even if they're available. result = waitForComponentAvailable(ref); } else if (cls.equals(String.class)) { result = arg; } else if (cls.isArray() && arg.trim().startsWith("[")) { arg = arg.trim(); String[] args = parseArgumentList(arg.substring(1, arg.length()-1)); Class base = cls.getComponentType(); Object arr = Array.newInstance(base, args.length); for (int i=0;i < args.length;i++) { Object obj = eval(resolver, args[i], base); Array.set(arr, i, obj); } result = arr; } else if ((parser = getParser(cls)) != null) { result = parser.parse(arg.trim()); } else if (cls.equals(Object.class)) { // This fix in put in place to make sure that in FileComparator // that we can invoke the Object,Object compare method // result = arg; } else { String msg = Strings.get("parser.conversion_error", new Object[] { arg.trim(), cls.getName() }); throw new IllegalArgumentException(msg); } return result; } catch(NumberFormatException nfe) { String msg = Strings.get("parser.conversion_error", new Object[] { arg.trim(), cls.getName() }); throw new IllegalArgumentException(msg); } } /** Evaluate the given set of arguments into the given set of types. */ public static Object[] eval(Resolver resolver, String[] args, Class[] params) throws IllegalArgumentException, NoSuchReferenceException, ComponentSearchException { Object[] plist = new Object[params.length]; for(int i=0;i < plist.length;i++) { plist[i] = eval(resolver, args[i], params[i]); } return plist; } /** Replace all instances in the given String of s1 with s2. */ public static String replace(String str, String s1, String s2) { StringBuffer sb = new StringBuffer(str); int index = 0; while ((index = sb.toString().indexOf(s1, index)) != -1) { sb.delete(index, index + s1.length()); sb.insert(index, s2); index += s2.length(); } return sb.toString(); } // TODO: move this somewhere more appropriate; make public static, maybe // in ComponentReference private static Component waitForComponentAvailable(final ComponentReference ref) throws ComponentSearchException { try { ComponentTester tester = ComponentTester.getTester(Component.class); tester.wait(new Condition() { public boolean test() { try { ref.getComponent(); } catch(ComponentNotFoundException e) { return false; } catch(MultipleComponentsFoundException m) { } return true; } public String toString() { return ref + " to become available"; } }, ComponentTester.componentDelay); } catch(WaitTimedOutException wto) { String msg = "Could not find " + ref + ": " + Step.toXMLString(ref); throw new ComponentNotFoundException(msg); } return ref.getComponent(); } /** Convert a value into a String representation. Handles null values and arrays. Returns null if the String representation is the default class@pointer format. */ public static String toString(Object value) { if (value == null) return NULL; if (value.getClass().isArray()) { StringBuffer sb = new StringBuffer(); sb.append("["); for (int i=0;i < Array.getLength(value);i++) { Object o = Array.get(value, i); if (i > 0) sb.append(","); sb.append(toString(o)); } sb.append("]"); return sb.toString(); } String s = value.toString(); if (s == null) return NULL; if (isDefaultToString(s)) return DEFAULT_TOSTRING; return s; } /** Returns whether the given String is the default toString() * implementation for the given Object. */ public static boolean isDefaultToString(String s) { if (s == null) return false; int at = s.indexOf("@"); if (at != -1) { String hash = s.substring(at + 1, s.length()); try { Integer.parseInt(hash, 16); return true; } catch(NumberFormatException e) { } } return false; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Assert.java
package abbot.script; import java.util.Map; import javax.swing.tree.TreePath; import abbot.*; import abbot.i18n.Strings; import abbot.tester.ComponentTester; import abbot.util.ExtendedComparator; import abbot.util.Properties; /** Encapsulate an assertion (or a wait). Usage:<br> * <blockquote><code> * &lt;assert method="[!]assertXXX" args="..." [class="..."]&gt;<br> * &lt;assert method="[!](get|is|has)XXX" component="component_id" value="..."&gt;<br> * &lt;assert method="[!]XXX" args="..." class="..."&gt;<br> * <br> * &lt;wait ... [timeout="..."] [pollInterval="..."]&gt;<br> * </code></blockquote> * The first example above invokes a core assertion provided by the * {@link abbot.tester.ComponentTester} class; the class tag is required for * assertions based on a class derived from * {@link abbot.tester.ComponentTester}; the class tag indicates the * {@link java.awt.Component} class, not the Tester class (the appropriate * tester class will be derived automatically).<p> * The second format indicates a property check on the given component, and an * expected value must be provided; the method name must start with "is", * "get", or "has". Finally, any arbitrary static boolean method may be used * in the assertion; you must specify the class and arguments.<p> * You can invert the sense of either form of assertion by inserting a '!' * character before the method name, or adding an <code>invert="true"</code> * attribute. * <p> * The default timeout for a wait is ten seconds; the default poll interval * (sleep time between checking the assertion) is 1/10 second. Both may be * set as XML attributes (<code>pollInterval</code> and <code>timeout</code>). */ public class Assert extends PropertyCall { /** Default interval between checking the assertion in a wait. */ public static final int DEFAULT_INTERVAL = Properties.getProperty("abbot.assert.default_interval", 100, 0, 1000); /** Default timeout before a wait will indicate failure. */ public static final int DEFAULT_TIMEOUT = Properties.getProperty("abbot.assert.default_timeout", 10000, 1000, 100000); private static final String ASSERT_USAGE = "<assert component=... method=... value=... [invert=true]/>\n" + "<assert method=[!]... [class=...]/>"; private static final String WAIT_USAGE = "<wait component=... method=... value=... [invert=true] " + "[timeout=...] [pollInterval=...]/>\n" + "<wait method=[!]... [class=...] [timeout=...] [pollInterval=...]/>"; private String expectedResult = "true"; private boolean invert; private boolean wait; private long interval = DEFAULT_INTERVAL; private long timeout = DEFAULT_TIMEOUT; /** Construct an assert step from XML. */ public Assert(Resolver resolver, Map attributes) { super(resolver, patchAttributes(attributes)); wait = attributes.get(TAG_WAIT) != null; String to = (String)attributes.get(TAG_TIMEOUT); if (to != null) { try { timeout = Integer.parseInt(to); } catch(NumberFormatException exc) { } } String pi = (String)attributes.get(TAG_POLL_INTERVAL); if (pi != null) { try { interval = Integer.parseInt(pi); } catch(NumberFormatException exc) { } } init(Boolean.valueOf((String)attributes.get(TAG_INVERT)). booleanValue(), (String)attributes.get(TAG_VALUE)); } /** Assertion provided by the ComponentTester class, or an arbitrary static call. */ public Assert(Resolver resolver, String desc, String targetClassName, String methodName, String[] args, String expectedResult, boolean invert) { super(resolver, desc, targetClassName != null ? targetClassName : ComponentTester.class.getName(), methodName, args); init(invert, expectedResult); } /** Assertion provided by a ComponentTester subclass which operates on a * Component subclass. */ public Assert(Resolver resolver, String desc, String methodName, String[] args, Class testedClass, String expectedResult, boolean invert) { super(resolver, desc, testedClass.getName(), methodName, args); init(invert, expectedResult); } /** Property assertion on Component subclass. */ public Assert(Resolver resolver, String desc, String methodName, String componentID, String expectedResult, boolean invert) { super(resolver, desc, methodName, componentID); init(invert, expectedResult); } /** The canonical form for a boolean assertion is to return true, and set * the invert flag if necessary. */ private void init(boolean inverted, String value) { if ("false".equals(value)) { inverted = !inverted; value = "true"; } expectedResult = value != null ? value : "true"; invert = inverted; } /** Changes the behavior of this step between failing if the condition is not met and waiting for the condition to be met. @param wait If true, this step returns from its {@link #runStep()} method only when its condition is met, throwing a {@link WaitTimedOutError} if the condition is not met within the timeout interval. @see #setPollInterval(long) @see #getPollInterval() @see #setTimeout(long) @see #getTimeout() */ public void setWait(boolean wait) { this.wait = wait; } public boolean isWait() { return wait; } public void setPollInterval(long interval) { this.interval = interval; } public long getPollInterval() { return interval; } public void setTimeout(long timeout) { this.timeout = timeout; } public long getTimeout() { return timeout; } public String getExpectedResult() { return expectedResult; } public void setExpectedResult(String result) { init(invert, result); } public boolean isInverted() { return invert; } public void setInverted(boolean invert) { init(invert, expectedResult); } /** Strip inversion from the method name. */ private static Map patchAttributes(Map map) { String method = (String)map.get(TAG_METHOD); if (method != null && method.startsWith("!")) { map.put(TAG_METHOD, method.substring(1)); map.put(TAG_INVERT, "true"); } // If no class is specified, default to ComponentTester String cls = (String)map.get(TAG_CLASS); if (cls == null) { map.put(TAG_CLASS, "abbot.tester.ComponentTester"); } return map; } public String getXMLTag() { return wait ? TAG_WAIT : TAG_ASSERT; } public String getUsage() { return wait ? WAIT_USAGE : ASSERT_USAGE; } public String getDefaultDescription() { String mname = getMethodName(); // assert/is/get doesn't really add any information, so drop it if (mname.startsWith("assert")) mname = mname.substring(6); else if (mname.startsWith("get") || mname.startsWith("has")) mname = mname.substring(3); else if (mname.startsWith("is")) mname = mname.substring(2); // FIXME this is cruft; really only need i18n for wait for X/assert X // [!][$.]m [==|!= v] String expression = mname + getArgumentsDescription(); if (getComponentID() != null) expression = "${" + getComponentID() + "}." + expression; if (invert && "true".equals(expectedResult)) expression = "!" + expression; if (!"true".equals(expectedResult)) { expression += invert ? " != " : " == "; expression += expectedResult; } if (wait && timeout != DEFAULT_TIMEOUT) { expression += " " + Strings.get((timeout > 5000 ? "wait.seconds" : "wait.milliseconds"), new Object[] { String.valueOf(timeout > 5000 ? timeout / 1000 : timeout) }); } return Strings.get((wait ? "wait.desc" : "assert.desc"), new Object[] { expression }); } public Map getAttributes() { Map map = super.getAttributes(); if (invert) { map.put(TAG_INVERT, "true"); } if (!expectedResult.equalsIgnoreCase("true")) { map.put(TAG_VALUE, expectedResult); } if (timeout != DEFAULT_TIMEOUT) map.put(TAG_TIMEOUT, String.valueOf(timeout)); if (interval != DEFAULT_INTERVAL) map.put(TAG_POLL_INTERVAL, String.valueOf(interval)); return map; } /** Check the assertion. */ protected void evaluateAssertion() throws Throwable { Object expected, actual; Class type = getMethod().getReturnType(); boolean compareStrings = false; try { expected = ArgumentParser.eval(getResolver(), expectedResult, type); } catch (IllegalArgumentException iae) { // If we can't convert the string to the expected type, // match the string against the result's toString method instead expected = expectedResult; compareStrings = true; } actual = invoke(); // Special-case TreePaths; we want to string-compare the underlying // objects rather than the TreePaths themselves. // If this comes up again we'll look for a generalized solution. if (expected instanceof TreePath && actual instanceof TreePath) { expected = ArgumentParser.toString(((TreePath)expected).getPath()); actual = ArgumentParser.toString(((TreePath)actual).getPath()); } if (compareStrings || expected instanceof String) { actual = ArgumentParser.toString(actual); } if (invert) { assertNotEquals(toString(), expected, actual); } else { assertEquals(toString(), expected, actual); } } /** Use our own comparison, to get the extended array comparisons. */ private void assertEquals(String message, Object expected, Object actual) { if (!ExtendedComparator.equals(expected, actual)) { String msg = Strings.get("assert.comparison_failed", new Object[] { (message != null ? message + " " : ""), ArgumentParser.toString(actual) }); throw new AssertionFailedError(msg, this); } } /** Use our own comparison, to get the extended array comparisons. */ private void assertNotEquals(String message, Object expected, Object actual) { if (ExtendedComparator.equals(expected, actual)) { String msg = message != null ? message : ""; throw new AssertionFailedError(msg, this); } } /** Run this step. */ protected void runStep() throws Throwable { if (!wait) { evaluateAssertion(); } else { long now = System.currentTimeMillis(); long remaining = timeout; while (remaining > 0) { long start = now; try { try { evaluateAssertion(); return; } catch(AssertionFailedError exc) { // keep waiting Log.debug(exc); } Thread.sleep(interval); } catch(InterruptedException ie) { throw new InterruptedAbbotException("Interrupted assert"); } now = System.currentTimeMillis(); remaining -= now - start; } throw new WaitTimedOutException(Strings.get("wait.timed_out", new Object[] { String.valueOf(timeout), toString() })); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Call.java
package abbot.script; import java.lang.reflect.*; import java.util.*; import abbot.Log; import abbot.i18n.Strings; import abbot.tester.FailedException; import abbot.tester.Robot; import java.awt.Component; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; /** Class for script steps that want to invoke a method on a class. * Subclasses may override getMethod and getTarget to customize behavior. * <blockquote><code> * &lt;call method="..." args="..." class="..."&gt;<br> * </code></blockquote> */ public class Call extends Step { private String targetClassName = null; private String methodName; private String[] args; private static final String USAGE = "<call class=\"...\" method=\"...\" args=\"...\" [property=\"...\"]/>"; public Call(Resolver resolver, Map attributes) { super(resolver, attributes); methodName = (String)attributes.get(TAG_METHOD); if (methodName == null) usage(Strings.get("call.method_missing")); targetClassName = (String)attributes.get(TAG_CLASS); if (targetClassName == null) usage(Strings.get("call.class_missing")); String argList = (String)attributes.get(TAG_ARGS); if (argList == null) argList = ""; args = ArgumentParser.parseArgumentList(argList); } public Call(Resolver resolver, String description, String className, String methodName, String[] args) { super(resolver, description); this.targetClassName = className; this.methodName = methodName; this.args = args != null ? args : new String[0]; } public String getDefaultDescription() { return getMethodName() + getArgumentsDescription(); } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_CALL; } /** Convert our argument vector into a single String. */ public String getEncodedArguments() { return ArgumentParser.encodeArguments(args); } protected String getArgumentsDescription() { return "(" + ArgumentParser.rawArguments(args) + ")"; } /** Set the String representation of the arguments for this Call step. */ public void setArguments(String[] args) { if (args == null) args = new String[0]; this.args = args; } /** Designate the arguments for this Call step. The format of this String is a comma-separated list of String representations. See the abbot.parsers package for supported String representations. <p> @see ArgumentParser#parseArgumentList for a description of the format. @see #setArguments(String[]) for the preferred method of indicating the argument list. */ public void setArguments(String encodedArgs) { if (encodedArgs == null) args = new String[0]; else args = ArgumentParser.parseArgumentList(encodedArgs); } public void setMethodName(String mn) { if (mn == null) { throw new NullPointerException("Method name may not be null"); } methodName = mn; } /** Method name to save in script. */ public String getMethodName() { return methodName; } public String getTargetClassName() { return targetClassName; } public void setTargetClassName(String cn) { if (cn == null) usage(Strings.get("call.class_missing")); targetClassName = cn; } /** Attributes to save in script. */ public Map getAttributes() { Map map = super.getAttributes(); map.put(TAG_CLASS, getTargetClassName()); map.put(TAG_METHOD, getMethodName()); if (args.length != 0) { map.put(TAG_ARGS, getEncodedArguments()); } return map; } /** Return the arguments as an array of String. @deprecated use getArguments(). */ public String[] getArgs() { return getArguments(); } /** Return the arguments as an array of String. */ public String[] getArguments() { return args; } protected void runStep() throws Throwable { try { invoke(); } catch(Exception e) { Log.debug(e); throw e; } } protected Object evaluateParameter(Method m, String param, Class type) throws Exception { return ArgumentParser.eval(getResolver(), param, type); } /** Convert the String representation of the arguments into actual * arguments. */ protected Object[] evaluateParameters(Method m, String[] params) throws Exception { Object[] args = new Object[params.length]; Class[] types = m.getParameterTypes(); for (int i=0;i < args.length;i++) { args[i] = evaluateParameter(m, params[i], types[i]); } return args; } /** Make the target method invocation. This uses <code>evaluateParameters</code> to convert the String representation of the arguments into actual arguments. Tries all matching methods of N arguments. */ protected Object invoke() throws Throwable { boolean retried = false; Method[] m = getMethods(); for (int i=0;i < m.length;i++) { try { final Object[] params = evaluateParameters(m[i], args); try { Object target = getTarget(m[i]); Log.debug("Invoking " + m[i] + " on " + target + getEncodedArguments() + "'"); if (target != null && !m[i].getDeclaringClass(). isAssignableFrom(target.getClass())) { // If the class loader mismatches, try to resolve it if (retried) { String msg = "Class loader mismatch? target " + target.getClass().getClassLoader() + " vs. method " + m[i].getDeclaringClass().getClassLoader(); throw new IllegalArgumentException(msg); } retried = true; m = resolveMethods(m[i].getName(), target.getClass(), null); i=-1; continue; } if ((m[i].getModifiers()&Modifier.PUBLIC) == 0 || (m[i].getDeclaringClass().getModifiers() & Modifier.PUBLIC) == 0) { Log.debug("Bypassing compiler access restrictions on " + "method " + m[i]); m[i].setAccessible(true); } final Object targetObject = getTarget(m[i]); final Method method = m[i]; if (Component.class.isAssignableFrom(m[i].getDeclaringClass())) { try { return Robot.callAndWait( targetObject instanceof Component ? (Component)targetObject:null, new Callable<Object>() { public Object call() throws Exception { return method.invoke(targetObject, params); } }); } catch (FailedException ee) { // Catch the failed exception and un-wrap if required throw ee.getCause(); } } else { return method.invoke(targetObject, params); } } catch(java.lang.reflect.InvocationTargetException ite) { throw ite.getTargetException(); } } catch(IllegalArgumentException e) { if (i == m.length - 1) throw e; } } throw new IllegalArgumentException("Can't invoke method " + m[0].getName()); } /** Return matching methods to be used for invocation. */ public Method getMethod() throws ClassNotFoundException, NoSuchMethodException { return resolveMethod(getMethodName(), getTargetClass(), null); } /** Return matching methods to be used for invocation. */ protected Method[] getMethods() throws ClassNotFoundException, NoSuchMethodException { return resolveMethods(getMethodName(), getTargetClass(), null); } /** Get the class of the target of the method invocation. This is public * to provide editors access to the class being used (for example, * providing a menu of all available methods). */ public Class getTargetClass() throws ClassNotFoundException { return resolveClass(getTargetClassName()); } /** Return the target of the invocation. The default implementation * always returns null for static methods; it will attempt to instantiate * a target for non-static methods. */ protected Object getTarget(Method m) throws Throwable { if ((m.getModifiers() & Modifier.STATIC) == 0) { try { return getTargetClass().newInstance(); } catch(Exception e) { setScriptError(new InvalidScriptException("Can't create an object instance of class " + getTargetClassName() + " for non-static method " + m.getName())); } } return null; } /** Look up all methods in the given class with the given name and return type, having the number of arguments in this step. @see #getArguments() @throws NoSuchMethodException if no matching method is found */ protected Method[] resolveMethods(String name, Class cls, Class returnType) throws NoSuchMethodException { // use getDeclaredMethods to include class methods Log.debug("Resolving methods on " + cls); Method[] mlist = cls.getMethods(); ArrayList<Method> found = new ArrayList<Method>(); for (int i=0;i < mlist.length;i++) { Method m = mlist[i]; Class[] params = m.getParameterTypes(); if (m.getName().equals(name) && params.length == args.length && (returnType == null || m.getReturnType().equals(returnType))) { found.add(m); } } if (found.size() == 0) { throw new NoSuchMethodException(Strings.get("call.no_matching_method", new Object[] { name, (returnType == null ? "*" : returnType.toString()), String.valueOf(args.length), cls })); } // Now sort according to restrictiveness of method arguments // We can assume that the methods are the same name, we just need // to prioritized boolean and scalar numbers over other objects Collections.sort(found, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return score(o1) - score(o2); } @Override public boolean equals(Object obj) { return super.equals(obj); } private int score(Method method) { int score = 0; for (Class parameterType : method.getParameterTypes()) { score += score(parameterType); } return score; } /** * So basically scalar types need to be processed first, then numbers * then strings. */ private int score(Class class1) { if (class1 == boolean.class) { return 1; } else if (class1.isPrimitive()) { return 2; } else if (Number.class.isAssignableFrom(class1)) { return 4; } else if (String.class.isAssignableFrom(class1)) { return 8; } else { // Just any old object return 16; } } }); Method[] list = (Method[])found.toArray(new Method[found.size()]); //Arrays.sort(list); return list; } /** Look up the given method name in the given class with the requested return type, having the number of arguments in this step. @throws IllegalArgumentException if not exactly one match exists @see #getArguments() */ protected Method resolveMethod(String name, Class cls, Class returnType) throws NoSuchMethodException { Method[] methods = resolveMethods(name, cls, returnType); if (methods.length != 1) { return disambiguateMethod(methods); } return methods[0]; } /** Try to distinguish betwenn the given methods. @throws IllegalArgumentException indicating the appropriate target method can't be distinguished. */ protected Method disambiguateMethod(Method[] methods){ String msg = Strings.get("call.multiple_methods", new Object[] { methods[0].getName(), methods[0].getDeclaringClass() }); throw new IllegalArgumentException(msg); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Comment.java
package abbot.script; import java.util.Map; import org.jdom.Element; /** Represents a comment. No other function. */ public class Comment extends Step { private static final String USAGE = "<!-- [text] -->"; public Comment(Resolver resolver, Map attributes) { super(resolver, attributes); } public Comment(Resolver resolver, String description) { super(resolver, description); } /** Default to whitespace. */ public String getDefaultDescription() { return ""; } public String toString() { return "# " + getDescription(); } public String getUsage() { return USAGE; } /** This is only used to generate the title label for the editor. */ public String getXMLTag() { return TAG_COMMENT; } public Element toXML() { throw new RuntimeException("Comments are not elements"); } /** Main run step. */ protected void runStep() { } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/ComponentReference.java
package abbot.script; import java.applet.Applet; import java.awt.*; import java.io.*; import java.lang.ref.WeakReference; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.accessibility.*; import org.jdom.*; import org.jdom.input.SAXBuilder; import abbot.Log; import abbot.i18n.Strings; import abbot.finder.*; import abbot.tester.*; import abbot.tester.Robot; import abbot.util.ExtendedComparator; import abbot.util.AWT; /** Encapsulate as much information as is available to identify a GUI * component. Usage:<br> * <blockquote><code> * &lt;component id="..." class="..." [...]&gt;<br> * </code></blockquote> * The component reference ID may be used in scripts in place of the actual * component to which this reference refers. The conversion will be made when * the actual component is needed. The ID is arbitrary, and may be changed in * scripts to any unique string (just remember to change all references to the * ID in other places in the script as well).<p> * A number of optional tags are supported to provide an increasingly precise * specification of the desired component:<br> * <ul> * <li><b><code>weighted</code></b> refers to the name of an available * attribute which should be weighted more heavily in comparisons, e.g. the * label on a JButton.<br> * <li><b><code>parent</code></b> the reference id of this component's * parent.<br> * </ul> * <p> * ComponentReferences may be created in one of three ways, each of which has * slightly different implications. * <ul> * <li>Resolver.addComponent(Component) - creates a reference if one doesn't * already exist and modifiers the Resolver to include it. * <li>getReference(Resolver, Component, Map) - create a reference only if a * matching one does not exist, but does not modify the Resolver. * <li>ComponentReference<init> - create a new reference. * </ul> */ // TODO: lose exact hierarchy match, cf Xt resource specifier, e.g. // TODO: add window appearance order // JRootPane.<name>|<class>.*.JPanel // Other attributes that might be useful: getAccessibleRole, // getAccessibleDescription, tooltip, accessibleRelation, selection start/end /* To extend, probably want to make a static function here that stores attributes and a lookup interface to read that attribute. Do this only if it is directly needed. Should the JRE class be used instead of a custom class? pros: doesn't save custom classes, which might change cons: ? Should class mismatches be allowed? cons: can't change classes pros: exact (or derived) class matching eliminates a lot of comparisons */ /* Optimization note: All lookups are cached, so that at most we have to traverse the hierarchy once. Successful lookups are cached until the referenced ocmponent is GCd, removed from the hierarchy, or otherwise marked invalid. Unsuccessful lookups are cached for the duration of a particular lookup. These happen in several places. 1) when resolving a cref into a component (getComponent()) 2) when a script is checking for existing references prior to creating a new one (getReference()). 3) when creating a new reference (ComponentReference(). 4) when looking for a matching, existing reference (matchExisting()). In these cases, the failed lookup cache is cleared only after the entire operation is complete. see also NOTES */ public class ComponentReference implements XMLConstants, XMLifiable, Comparable { public static final String SHARED_FRAME_ID = "shared frame"; // Matching weights for various attributes private static final int MW_NAME = 100; private static final int MW_ROOT = 25; //private static final int MW_WEIGHTED = 50; private static final int MW_TAG = 50; private static final int MW_PARENT = 25; // private static final int MW_WINDOW = 25; private static final int MW_INVOKER = 25; private static final int MW_TITLE = 25; private static final int MW_BORDER_TITLE = 25; private static final int MW_LABEL = 25; private static final int MW_TEXT = 25; // private static final int MW_ICON = 25; private static final int MW_INDEX = 10; // private static final int MW_CLASS = 1; // Pretty much for applets only, or other embedded frames private static final int MW_PARAMS = 1; private static final int MW_DOCBASE = 1; // Mostly for distinguishing between multiple components that would // otherwise all match private static final int MW_HORDER = 1; private static final int MW_VORDER = 1; //private static final int MW_ENABLED = 1; //private static final int MW_FOCUSED = 1; private static final int MW_SHOWING = 1; /** Match weight corresponding to no possible match. */ public static final int MW_FAILURE = 0; static final String ANON_INNER_CLASS = "/^.*\\$[0-9]+$/"; private Resolver resolver; private Map attributes = new HashMap(); // This helps component reference creation by an order of magnitude, // especially when dealing with ordered attributes. private WeakReference cachedLookup; /** This ThreadLocal allows us to keep track of unresolved components on a * per-thread (basically per-lookup) basis. */ private static ThreadLocal lookupFailures = new ThreadLocal() { protected synchronized Object initialValue() { return new HashMap(); } }; /** This ThreadLocal allows us to keep track of non-showing, resolved * components on a per-thread (basically per-lookup) basis. */ private static ThreadLocal nonShowingMatches = new ThreadLocal() { protected synchronized Object initialValue() { return new HashMap(); } }; /** Keep track of which ComponentReference ctor is the first one. */ private static ThreadLocal ownsFailureCache = new ThreadLocal() { protected synchronized Object initialValue() { return Boolean.TRUE; } }; /** Cached XML representation. */ private String xml; /** Disable immediate cacheing of components when a reference is created based on a Component. Cacheing will first be done when the reference is resolved for the first time after creation. For testing purposes only. */ static boolean cacheOnCreation = true; /** For creation from XML. */ public ComponentReference(Resolver resolver, Element el) throws InvalidScriptException { this.resolver = resolver; fromXML(el, true); } /** Create a reference to an instance of the given class, given an array of name/value pairs of attributes. */ public ComponentReference(Resolver r, Class cls, String[][] attributes) { this(r, cls, createAttributeMap(attributes)); } /** Create a reference to an instance of the given class, given a Map of attributes. */ public ComponentReference(Resolver resolver, Class cls, Map attributes) { // sort of a hack to provide a 'default' resolver this.resolver = resolver; this.attributes.putAll(attributes); this.attributes.put(TAG_CLASS, Robot.getCanonicalClass(cls).getName()); if (resolver != null) { if (this.attributes.get(TAG_ID) == null) { this.attributes.put(TAG_ID, getUniqueID(new HashMap())); } resolver.addComponentReference(this); } } /** Create a reference based on the given component. Will not use or create any ancestor components/references. */ public ComponentReference(Resolver resolver, Component comp) { this(resolver, comp, false, new HashMap()); } /** Create a reference based on the given component. May recursively create other components required to identify this one. */ public ComponentReference(Resolver resolver, Component comp, Map newReferences) { this(resolver, comp, true, newReferences); } /** Create a reference based on the given component. May recursively create other components required to identify this one if <code>includeHierarchy</code> is true. If <code>newReferences</code> is non-null, new ancestor references will be added to it; if null, they will be added to the resolver instead. */ private ComponentReference(Resolver resolver, Component comp, boolean includeHierarchyAttributes, Map newReferences) { // This method may be called recursively (indirectly through // Resolver.addComponent) in order to add references for parent // components. Make note of whether this instantiation needs // to clear the failure cache when it's done. boolean cleanup = ((Boolean)ownsFailureCache.get()).booleanValue(); ownsFailureCache.set(Boolean.FALSE); Log.debug("ctor: " + comp); this.resolver = resolver; if (AWT.isSharedInvisibleFrame(comp)) { setAttribute(TAG_ID, SHARED_FRAME_ID); setAttribute(TAG_CLASS, comp.getClass().getName()); } else { Class refClass = Robot.getCanonicalClass(comp.getClass()); setAttribute(TAG_CLASS, refClass.getName()); } String name = Robot.getName(comp); if (name != null) setAttribute(TAG_NAME, name); // Only generate a tag attribute for custom components; using a tag // attribute for standard components is deprecated. String cname = comp.getClass().getName(); if (!(cname.startsWith("java.awt.") || cname.startsWith("javax.swing."))) { String tag = ComponentTester.getTag(comp); if (tag != null) setAttribute(TAG_TAG, tag); } // only take the title on a Frame/Dialog // using the window title for other components is obsolete String title = Robot.getTitle(comp); if (title != null) setAttribute(TAG_TITLE, title); String borderTitle = Robot.getBorderTitle(comp); if (borderTitle != null) setAttribute(TAG_BORDER_TITLE, borderTitle); String label = Robot.getLabel(comp); if (label != null) setAttribute(TAG_LABEL, label); String text = Robot.getText(comp); if (text != null) setAttribute(TAG_TEXT, text); String icon = Robot.getIconName(comp); if (icon != null) setAttribute(TAG_ICON, icon); if (comp instanceof Applet) { Applet applet = (Applet)comp; setAttribute(TAG_PARAMS, encodeParams(applet)); java.net.URL url = applet.getDocumentBase(); setAttribute(TAG_DOCBASE, url != null ? url.toString() : "null"); } // Work the the unique name based on the previous values String id = getUniqueID(newReferences); setAttribute(TAG_ID, id); Log.debug("Unique ID is " + id); // Populate the new reference now with this ID, this needs to be before // the parent lookup to prevent some repetition of values in certain // complex UI cases. // newReferences.put(id, this); // Finally work out the parent Container parent = resolver.getHierarchy().getParent(comp); if (null != parent) { // Don't save window indices, they're not sufficiently reliable if (!(comp instanceof Window)) { int index = Robot.getIndex(parent, comp); if (index != -1) setAttribute(TAG_INDEX, String.valueOf(index)); } } else if (comp instanceof Window) { setAttribute(TAG_ROOT, "true"); } try { if (includeHierarchyAttributes) { // Provide either the invoker or the window boolean needWindow = !(comp instanceof Window); Component invoker = null; if (comp instanceof JPopupMenu) { invoker = ((JPopupMenu)comp).getInvoker(); ComponentReference ref = getReference(resolver, invoker, newReferences); setAttribute(TAG_INVOKER, ref.getID()); needWindow = false; } else if (parent != null) { needWindow = !(parent instanceof Window); addParent(parent, newReferences); } if (needWindow && !(comp instanceof Window)) { Window win = AWT.getWindow(comp); if (win != null) { ComponentReference wref = getReference(resolver, win, newReferences); setAttribute(TAG_WINDOW, wref.getID()); } } validate(comp, newReferences); } } finally { if (cleanup) { getLookupFailures().clear(); getNonShowingMatches().clear(); ownsFailureCache.set(Boolean.TRUE); } } // Set the cache immediately if (cacheOnCreation || AWT.isSharedInvisibleFrame(comp)) { Log.debug("Cacheing initial match"); cachedLookup = new WeakReference(comp); } else { cachedLookup = null; } } /** Return the component in the current Hierarchy that best matches this reference. */ public Component getComponent() throws ComponentNotFoundException, MultipleComponentsFoundException { if (resolver == null) throw new ComponentNotFoundException("No default hierarchy has been provided"); return getComponent(resolver.getHierarchy()); } /** Return the component in the given Hierarchy that best matches this reference. */ public Component getComponent(Hierarchy hierarchy) throws ComponentNotFoundException, MultipleComponentsFoundException { try { return findInHierarchy(null, hierarchy, 1, new HashMap()); } finally { // never called recursively, so we can clear the cache here getLookupFailures().clear(); getNonShowingMatches().clear(); } } private void addParent(Container parent, Map newReferences) { ComponentReference ref = getReference(resolver, parent, newReferences); setAttribute(TAG_PARENT, ref.getID()); } /** Returns whether the given component is reachable from the root of the * current hierarchy. * Popups' transient elements may already have gone away, and will be * unreachable. */ private boolean reachableInHierarchy(Component c) { Window w = AWT.getWindow(c); if (w == null) return false; Window parent = (Window)resolver.getHierarchy().getParent(w); return (parent == null) ? resolver.getHierarchy().getRoots().contains(w) : reachableInHierarchy(parent); } /** Ensure the reference can be used to actually look up the given * component. This can be a compute-intensive search, and thus is omitted * from the basic constructor. */ private void validate(Component comp, Map newReferences) { // Under certain situations where we know the component is // unreachable from the root of the hierarchy, or if a lookup will // fail for other reasons, simply check for a match. // WARNING: this leaves a hole if the component actually needs an // ORDER attribute, but the ORDER attribute is intended for applets // only. if (!reachableInHierarchy(comp)) { int wt = getMatchWeight(comp, newReferences); int exact = getExactMatchWeight(); if (wt < exact) { String msg = Strings.get("component.creation_mismatch", new Object[] { toXMLString(), comp.toString(), new Integer(wt), new Integer(exact), }); throw new Error(msg); } } else { try { Log.debug("Finding in hierarchy (" + resolver.getHierarchy() + ")"); findInHierarchy(null, resolver.getHierarchy(), getExactMatchWeight(), newReferences); } catch (MultipleComponentsFoundException multiples) { try { // More than one match found, so add more information Log.debug("Disambiguating"); disambiguate(comp, multiples.getComponents(), newReferences); } catch(ComponentSearchException e) { if (!(e instanceof MultipleComponentsFoundException)) Log.warn(e); throw new Error("Reverse lookup failed to uniquely match " + Robot.toString(comp) + ": " + e); } } catch (ComponentNotFoundException e) { // This indicates a failure in the reference recording // mechanism, and requires a fix. throw new Error("Reverse lookup failed looking for " + Robot.toString(comp) + " using " + toXMLString() + ": " + e); } } } /** Return a descriptive name for the given component for use in UI * text (may be localized if appropriate and need not be re-usable * across locales. * @deprecated Use {@link Robot#getDescriptiveName(Component)} instead */ public static String getDescriptiveName(Component c) { return Robot.getDescriptiveName(c); } /** Return a suitably descriptive name for this reference, for use as an ID (returns the ID itself if already set). Will never return an empty String. */ public String getDescriptiveName() { String id = getAttribute(TAG_ID); if (id == null) { String[] attributes = { TAG_NAME, TAG_TITLE, TAG_TEXT, TAG_LABEL, TAG_ICON, }; for (int i=0;i < attributes.length;i++) { String att = getAttribute(attributes[i]); if (att != null && !"".equals(att)) { id = att; break; } } // Fall back to "<classname> Instance" if all else fails if (id == null) { String cname = getAttribute(TAG_CLASS); cname = cname.substring(cname.lastIndexOf(".") + 1); id = cname + " Instance"; } } return id; } public String getID() { return getAttribute(TAG_ID); } public String getRefClassName() { return getAttribute(TAG_CLASS); } public String getAttribute(String key) { return (String)attributes.get(key); } public Map getAttributes() { return new TreeMap(attributes); } public void setAttribute(String key, String value) { xml = null; attributes.put(key, value); } /** Return whether a cast to the given class name from the given class would work. */ private boolean isAssignableFrom(String refClassName, Class cls) { return refClassName.equals(cls.getName()) || (!Component.class.equals(cls) && isAssignableFrom(refClassName, cls.getSuperclass())); } /** Return whether this reference has the same class or is a superclass of * the given component's class. Simply compare class names to avoid class * loader conflicts. Note that this does not take into account interfaces * (which is okay, since with GUI components we're only concerned with * class inheritance). */ public boolean isAssignableFrom(Class cls) { return cls != null && Component.class.isAssignableFrom(cls) && isAssignableFrom(getAttribute(TAG_CLASS), cls); } public ComponentReference getParentReference(Map newRefs) { String parentID = getAttribute(TAG_PARENT); ComponentReference pref = null; if (parentID != null) { pref = resolver.getComponentReference(parentID); if (pref == null) pref = (ComponentReference)newRefs.get(parentID); } return pref; } /** Reference ID of this component's parent window (optional). */ public ComponentReference getWindowReference(Map newReferences) { String windowID = getAttribute(TAG_WINDOW); ComponentReference wref = null; if (windowID != null) { wref = resolver.getComponentReference(windowID); if (wref == null) wref = (ComponentReference)newReferences.get(windowID); } return wref; } public ComponentReference getInvokerReference(Map newReferences) { String invokerID = getAttribute(TAG_INVOKER); ComponentReference iref = null; if (invokerID != null) { iref = resolver.getComponentReference(invokerID); if (iref == null) iref = (ComponentReference)newReferences.get(invokerID); } return iref; } /** Set all options based on the given XML. @deprecated */ // This is only used when editing scripts, since we don't want to have to // hunt down existing references public void fromXML(String input) throws InvalidScriptException, IOException { StringReader reader = new StringReader(input); try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(reader); Element el = doc.getRootElement(); if (el == null) throw new InvalidScriptException("Invalid ComponentReference" + " XML '" + input + "'"); fromXML(el, false); } catch(JDOMException e) { throw new InvalidScriptException(e.getMessage() + " (when parsing " + input + ")"); } } /** Parse settings from the given XML. Only overwrite the ID if useGivenID is set. @throws InvalidScriptException if the given Element is not valid XML for a ComponentReference. */ private void fromXML(Element el, boolean useIDFromXML) throws InvalidScriptException { Iterator iter = el.getAttributes().iterator(); while (iter.hasNext()) { Attribute att = (Attribute)iter.next(); String nodeName = att.getName(); String value = att.getValue(); if (nodeName.equals(TAG_ID) && !useIDFromXML) continue; setAttribute(nodeName, value); } if (getAttribute(TAG_CLASS) == null) { throw new InvalidScriptException("Class must be specified", el); } String id = getID(); if (useIDFromXML) { // Make sure the ID we read in is not already in use by the manager if (id != null) { if (resolver.getComponentReference(id) != null) { String msg = "Persistent ID '" + id + "' is already in use"; throw new InvalidScriptException(msg, el); } } } if (id == null) { Log.warn("null ID"); setAttribute(TAG_ID, getUniqueID(new HashMap())); } } /** Generate an XML representation of this object. */ public Element toXML() { Element el = new Element(TAG_COMPONENT); Iterator iter = new TreeMap(attributes).keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); String value = getAttribute(key); if (value != null) el.setAttribute(key, value); } return el; } /** @deprecated Used to be used to edit XML in a text editor. */ public String toEditableString() { return toXMLString(); } /** Two ComponentReferences with identical XML representations should be equal. */ public boolean equals(Object obj) { return this == obj || (obj instanceof ComponentReference) && toXMLString(). equals(((ComponentReference)obj).toXMLString()); } /** Return a human-readable representation. */ public String toString() { String id = getID(); String cname = getAttribute(TAG_CLASS); if (cname.startsWith("javax.swing.")) cname = cname.substring(12); else if (cname.startsWith("java.awt.")) cname = cname.substring(9); StringBuffer buf = new StringBuffer(id != null ? id : (cname + " (no id yet)")); if (id != null && id.indexOf("Instance") == -1) { buf.append(" ("); buf.append(cname); buf.append(")"); } return buf.toString(); } public String toXMLString() { if (xml == null) xml = Step.toXMLString(this); return xml; } /** Return which of the otherwise indistinguishable components provides * the best match, or throw a MultipleComponentsFoundException if no * distinction is possible. Assumes that all given components return an * equivalent match weight. */ private Component bestMatch(Set set) throws MultipleComponentsFoundException { Component[] matches = (Component[]) set.toArray(new Component[set.size()]); int weights[] = new int[matches.length]; for (int i=0;i < weights.length;i++) { // Prefer showing to non-showing Window w = AWT.getWindow(matches[i]); if (w != null && w.isShowing() && matches[i].isShowing()) { weights[i] = MW_SHOWING; } else { weights[i] = 0; } // Preferring one enabled/focused state is dangerous to do: // An enabled component might be preferred over a disabled one, // but it will fail if you're trying to examine state on the // disabled component. Ditto for focused. } String horder = getAttribute(TAG_HORDER); if (horder != null) { for (int i=0;i < matches.length;i++) { String order = getOrder(matches[i], matches, true); if (horder.equals(order)) { weights[i] += MW_HORDER; } } } String vorder = getAttribute(TAG_VORDER); if (vorder != null) { for (int i=0;i < matches.length;i++) { String order = getOrder(matches[i], matches, false); if (vorder.equals(order)) { weights[i] += MW_VORDER; } } } // Figure out the best match, if any ArrayList best = new ArrayList(); best.add(matches[0]); int max = 0; for (int i=1;i < weights.length;i++) { if (weights[i] > weights[max]) { max = i; best.clear(); best.add(matches[i]); } else if (weights[i] == weights[max]) { best.add(matches[i]); } } if (best.size() == 1) { return (Component)best.get(0); } // Finally, see if any match the old cached value Component cache = getCachedLookup(resolver.getHierarchy()); if (cache != null) { Iterator iter = best.iterator(); while (iter.hasNext()) { Component c = (Component)iter.next(); if (cache == c) { return cache; } } } String msg = Strings.get("reference.multiple_found_reference", best.size(),toXMLString()); matches = (Component[])best.toArray(new Component[best.size()]); throw new MultipleComponentsFoundException(msg, matches); } /** Return the order of the given component among the array given, sorted * by horizontal or vertical screen position. All components with the * same effective value will have the same order. */ static String getOrder(Component original, Component[] matchList, boolean horizontal) { Comparator c = horizontal ? HORDER_COMPARATOR : VORDER_COMPARATOR; Component[] matches = (Component[])matchList.clone(); Arrays.sort(matches, c); int order = 0; for (int i=0;i < matches.length;i++) { // Only change the order magnitude if there is a difference // between consecutive objects. if (i > 0 && c.compare(matches[i-1], matches[i]) != 0) ++order; if (matches[i] == original) { return String.valueOf(order); } } return null; } /** Add sufficient information to the reference to distinguish it among the given components. Note that the ordering attributes can only be evaluated when looking at several otherwise identical components. */ private void disambiguate(Component original, Component[] matches, Map newReferences) throws ComponentNotFoundException, MultipleComponentsFoundException { Log.debug("Attempting to disambiguate multiple matches"); Container parent = resolver.getHierarchy().getParent(original); boolean retryOnFailure = false; String order = null; try { String cname = original.getClass().getName(); // Use the inner class name unless it's numeric (numeric values // can easily change). if (!cname.equals(getAttribute(TAG_CLASS)) && !expressionMatch(ANON_INNER_CLASS, cname)) { setAttribute(TAG_CLASS, original.getClass().getName()); retryOnFailure = true; } else if (parent != null && getAttribute(TAG_PARENT) == null && !(original instanceof JPopupMenu)) { Log.debug("Adding parent"); addParent(parent, newReferences); retryOnFailure = true; } else if (getAttribute(TAG_HORDER) == null && (order = getOrder(original, matches, true)) != null) { Log.debug("Adding horder"); setAttribute(TAG_HORDER, order); retryOnFailure = true; } else if (getAttribute(TAG_VORDER) == null && (order = getOrder(original, matches, false)) != null) { Log.debug("Adding vorder"); setAttribute(TAG_VORDER, order); retryOnFailure = true; } // Try the lookup again to make sure it works this time Log.debug("Retrying lookup with new values"); // Remove this cref and its ancestors from the failure // cache so we don't automatically fail getLookupFailures().remove(this); findInHierarchy(null, resolver.getHierarchy(), getExactMatchWeight(), newReferences); Log.debug("Success!"); } catch(MultipleComponentsFoundException multiples) { if (retryOnFailure) { disambiguate(original, multiples.getComponents(), newReferences); } else throw multiples; } } // Removed as in some cases it mean we were not taking into account new references. // /** Return a measure of how well the given component matches the given // * component reference. The weight performs two functions; one is to // * loosely match so that we can find a component even if some of its // * attributes have changed. The other is to distinguish between similar // * components. <p> // * In general, we want to match if we get any weight at all, and there's // * only one component that matches. // */ // int getMatchWeight(Component comp) { // return getMatchWeight(comp, new HashMap()); // } /** Return a measure of how well the given component matches the given * component reference. The weight performs two functions; one is to * loosely match so that we can find a component even if some of its * attributes have changed. The other is to distinguish between similar * components. <p> * In general, we want to match if we get any weight at all, and there's * only one component that matches. */ private int getMatchWeight(Component comp, Map newReferences) { // Match weights may be positive or negative. They should only be // negative if the attribute is highly unlikely to change. int weight = MW_FAILURE; if (null == comp) { return MW_FAILURE; } // FIXME might want to allow changing the class? or should we just // ask the user to fix the script by hand? if (!isAssignableFrom(comp.getClass())) { return MW_FAILURE; } weight += MW_CLASS; // Exact class matches are better than non-exact matches if (getAttribute(TAG_CLASS).equals(comp.getClass().getName())) weight += MW_CLASS; String refTag = getAttribute(TAG_TAG); String compTag = null; if (null != refTag) { compTag = ComponentTester.getTag(comp); if (compTag != null && expressionMatch(refTag, compTag)) { weight += MW_TAG; } } String refName = getAttribute(TAG_NAME); String compName = Robot.getName(comp); if (null != refName) { if (compName != null && expressionMatch(refName, compName)) { weight += MW_NAME; } else { weight -= MW_NAME; } } else { Log.log("Component name set as " + compName + "but the reference name was null"); } if (null != getAttribute(TAG_INVOKER)) { ComponentReference iref = getInvokerReference(newReferences); Component invoker = (comp instanceof JPopupMenu) ? ((JPopupMenu)comp).getInvoker() : null; if (invoker != null && iref != null && invoker == iref.resolveComponent(invoker, newReferences)) { weight += MW_INVOKER; } else { // Invoking components aren't likely to change weight -= MW_INVOKER; } } if (null != getAttribute(TAG_PARENT)) { ComponentReference pref = getParentReference(newReferences); Component parent = resolver.getHierarchy().getParent(comp); if (parent == pref.resolveComponent(parent, newReferences)) { weight += MW_PARENT; } // Don't detract on parent mismatch, since changing a parent is // not that big a change (e.g. adding a scroll pane) } // ROOT and PARENT are mutually exclusive else if (null != getAttribute(TAG_ROOT)) { weight += MW_ROOT; } if (null != getAttribute(TAG_WINDOW)) { ComponentReference wref = getWindowReference(newReferences); Window w = AWT.getWindow(comp); if (w == wref.resolveComponent(w, newReferences)) { weight += MW_WINDOW; } else if (w != null) { // Changing windows is a big change and not very likely weight -= MW_WINDOW; } } // TITLE is no longer used except by Frames, Dialogs, and // JInternalFrames, being superseded by the ancestor window // reference. For other components, it represents an available // ancestor window title (deprecated usage only). String title = getAttribute(TAG_TITLE); if (null != title) { String title2 = (comp instanceof Frame || comp instanceof Dialog || comp instanceof JInternalFrame) ? Robot.getTitle(comp) : getComponentWindowTitle(comp); if (title2 != null && expressionMatch(title, title2)) { weight += MW_TITLE; } // Don't subtract on mismatch, since title changes are common } String borderTitle = getAttribute(TAG_BORDER_TITLE); if (null != borderTitle) { String bt2 = Robot.getBorderTitle(comp); if (bt2 != null && expressionMatch(borderTitle, bt2)) { weight += MW_BORDER_TITLE; } } String label = getAttribute(TAG_LABEL); if (null != label) { String label2 = Robot.getLabel(comp); if (label2 != null && expressionMatch(label, label2)) { weight += MW_LABEL; } } String text = getAttribute(TAG_TEXT); if (null != text) { String text2 = Robot.getText(comp); if (text2 != null && expressionMatch(text, text2)) { weight += MW_TEXT; } } String icon = getAttribute(TAG_ICON); if (null != icon) { String icon2 = Robot.getIconName(comp); if (icon2 != null && expressionMatch(icon, icon2)) { weight += MW_ICON; } } String idx = getAttribute(TAG_INDEX); if (null != idx) { Container parent = resolver.getHierarchy().getParent(comp); if (null != parent) { int i = Robot.getIndex(parent, comp); if (expressionMatch(idx, String.valueOf(i))) { weight += MW_INDEX; } } // Don't subtract for index mismatch, since ordering changes are // common. } if (comp instanceof Applet) { Applet applet = (Applet)comp; String params = getAttribute(TAG_PARAMS); if (null != params) { String params2 = encodeParams(applet); if (expressionMatch(params, params2)) weight += MW_PARAMS; } String docBase = getAttribute(TAG_DOCBASE); if (null != docBase) { java.net.URL url = applet.getDocumentBase(); if (url != null && expressionMatch(docBase, url.toString())) weight += MW_DOCBASE; } // No negative weighting here } if (Log.isClassDebugEnabled(ComponentReference.class)) Log.debug("Compared " + Robot.toString(comp) + " to " + toXMLString() + " weight is " + weight); return weight; } /** Return the total weight required for an exact match. */ private int getExactMatchWeight() { int weight = MW_CLASS; if (getAttribute(TAG_NAME) != null) weight += MW_NAME; if (getAttribute(TAG_TAG) != null) weight += MW_TAG; if (getAttribute(TAG_INVOKER) != null) weight += MW_INVOKER; if (getAttribute(TAG_ROOT) != null) weight += MW_ROOT; if (getAttribute(TAG_PARENT) != null) weight += MW_PARENT; if (getAttribute(TAG_WINDOW) != null) weight += MW_WINDOW; if (getAttribute(TAG_TITLE) != null) weight += MW_TITLE; if (getAttribute(TAG_BORDER_TITLE) != null) weight += MW_BORDER_TITLE; if (getAttribute(TAG_INDEX) != null) weight += MW_INDEX; if (getAttribute(TAG_LABEL) != null) weight += MW_LABEL; if (getAttribute(TAG_TEXT) != null) weight += MW_TEXT; if (getAttribute(TAG_ICON) != null) weight += MW_ICON; if (getAttribute(TAG_PARAMS) != null) weight += MW_PARAMS; if (getAttribute(TAG_DOCBASE) != null) weight += MW_DOCBASE; if (Log.isClassDebugEnabled(ComponentReference.class)) Log.debug("Exact match weight for " + toXMLString() + " is " + weight); return weight; } /** Returns an existing component which matches this reference; the given Component is the one that is expected to match. Returns null if no match or multiple matches are found and the preferred Component is not among them.<p> This method is used in two instances: <ul> <li>Resolving a component's ancestors (window, parent, or invoker), the ancestor reference is checked against the ancestor of the Component currently being compared. <li>When referring to a component, determining if a reference to it already exists, all references are resolved to see if any resolves to the preferred Component. </ul> While there is a subtle difference between the two cases (when running a test it is expected that there will be some match, whereas when creating a new reference there may or may not be a match, based on the current script contents), it is not a useful distinction. */ private Component resolveComponent(Component preferred, Map newReferences) { // This call should be equivalent to getComponent(), but without // clearing the lookup failure cache on completion if (Log.isClassDebugEnabled(ComponentReference.class)) Log.debug("Looking up " + toXMLString() + " in hierarchy"); Component found = null; try { found = findInHierarchy(null, resolver.getHierarchy(), 1, newReferences); } catch(MultipleComponentsFoundException e) { Component[] list = e.getComponents(); for (int i=0;i < list.length;i++) { if (list[i] == preferred) return preferred; } //Log.warn("Preferred not found among many"); } catch(ComponentNotFoundException e) { // If the preferred component is not reachable in the hierarchy // (if it has just been removed from the hierarchy, or an ancestor // pane was replaced), require an exact match to avoid // spurious matches. int minWeight = getExactMatchWeight(); if (getAttribute(TAG_WINDOW) != null) minWeight -= MW_WINDOW; if (getAttribute(TAG_PARENT) != null) minWeight -= MW_PARENT; if (AWT.getWindow(preferred) == null && getMatchWeight(preferred, newReferences) >= minWeight) { Log.debug("Using preferred component: " + Robot.toString(preferred)); found = preferred; } } return found; } /** Returns a reference to the given component, preferring an existing * reference if a matching one is available or creating a new one if not. * The new references are <i>not</i> added to the resolver. */ // FIXME: keep newly-created ancestors in a collection and let the // resolver add them. (maybe create everything, then let the resolver // sort out duplicates when adding). // TODO: require exact matches, otherwise create a new ref; this means // that we need to provide a method to repair refs. public static ComponentReference getReference(Resolver r, Component comp, Map newReferences) { Log.debug("Looking for a reference for " + Robot.toString(comp)); // Preserve the failure cache across both lookup and creation boolean cleanup = ((Boolean)ownsFailureCache.get()).booleanValue(); ownsFailureCache.set(Boolean.FALSE); // Allow the resolver to do cacheing if it needs to; otherwise we'd // call matchExisting directly. ComponentReference ref = r.getComponentReference(comp); try { // In the case where we are looking at a window we might find // that window property has been populated if (ref==null && comp instanceof Window) { ref = ComponentReference.matchExisting( comp, newReferences.values(), newReferences); if (ref!=null) { // check tha match is a good one int exactMatch = ref.getExactMatchWeight(); // Make sure that newReferences are passed in int componentMatch = ref.getMatchWeight(comp,newReferences); if (componentMatch < exactMatch) { ref = null; } } } // if (ref == null) { Log.debug("No existing reference found, creating a new one"); ref = new ComponentReference(r, comp, newReferences); } } finally { if (cleanup) { getLookupFailures().clear(); getNonShowingMatches().clear(); ownsFailureCache.set(Boolean.TRUE); } } return ref; } /** Match the given component against an existing set of references. */ public static ComponentReference matchExisting(final Component comp, Collection existing) { return matchExisting(comp, existing, Collections.EMPTY_MAP); } /** Match the given component against an existing set of references. * Extended method that also takes in a list of new references that * might have been created in this cycle */ public static ComponentReference matchExisting(final Component comp, Collection existing, final Map newReferences) { Log.debug("Matching " + Robot.toString(comp) + " against existing refs"); // This method might be called recursively (indirectly through // Resolver.addComponent) in order to add references for parent // components. Make note of whether this level of invocation needs // to clear the failure cache when it's done. boolean cleanup = ((Boolean)ownsFailureCache.get()).booleanValue(); ownsFailureCache.set(Boolean.FALSE); ComponentReference match = null; Iterator iter = existing.iterator(); // Sort such that the best match comes first Map matches = new TreeMap(new Comparator() { public int compare(Object o1, Object o2) { // Ensure newReferences are used otherwise some parents won't match // return ((ComponentReference)o2).getMatchWeight(comp, newReferences) - ((ComponentReference)o1).getMatchWeight(comp, newReferences); } }); while (iter.hasNext()) { ComponentReference ref = (ComponentReference)iter.next(); if (comp == ref.getCachedLookup(ref.resolver.getHierarchy()) || comp == ref.resolveComponent(comp, newReferences)) { matches.put(ref, Boolean.TRUE); } } if (matches.size() > 0) { match = (ComponentReference)matches.keySet().iterator().next(); } if (cleanup) { // Clear failures only after we've attempted a match for *all* refs getLookupFailures().clear(); getNonShowingMatches().clear(); ownsFailureCache.set(Boolean.TRUE); } Log.debug(match != null ? "Found" : "Not found"); return match; } /** Return whether the given pattern matches the given string. Performs * variable substitution on the pattern. */ boolean expressionMatch(String pattern, String actual) { pattern = ArgumentParser.substitute(resolver, pattern); return ExtendedComparator.stringsMatch(pattern, actual); } /** Convert the given applet's parameters into a simple String. */ private String encodeParams(Applet applet) { // TODO: is there some other way of digging out the full set of // parameters that were passed the applet? b/c here we rely on the // applet having been properly written to tell us about supported // parameters. StringBuffer sb = new StringBuffer(); String[][] info = applet.getParameterInfo(); if (info == null) { // Default implementation of applet returns null return "null"; } for (int i=0;i < info.length;i++) { sb.append(info[i][0]); sb.append("="); String param = applet.getParameter(info[i][0]); sb.append(param != null ? param : "null"); sb.append(";"); } return sb.toString(); } /** Return the cached component match, if any. */ Component getCachedLookup(Hierarchy hierarchy) { if (cachedLookup != null) { Component c = (Component)cachedLookup.get(); // Discard if the component has been gc'd, is no longer in the // hierarchy, or is no longer reachable from a Window. if (c != null && hierarchy.contains(c) && AWT.getWindow(c) != null) { return c; } Log.debug("Discarding cached value: " + Robot.toString(c)); cachedLookup = null; } return null; } /** Compare this ComponentReference against each component below the given * root in the given hierarchy whose match weight exceeds the given * minimum. If a valid cached lookup exists, that is returned * immediately. */ // TODO: refactor this to extract the finder/lookup logic into a separate // class. the ref should only store attributes. private Component findInHierarchy(Container root, Hierarchy hierarchy, int weight, Map newReferences) throws ComponentNotFoundException, MultipleComponentsFoundException { Component match = null; ComponentSearchException cse = (ComponentSearchException) getLookupFailures().get(this); if (cse instanceof ComponentNotFoundException) { Log.debug("lookup already failed: " + cse); throw (ComponentNotFoundException)cse; } if (cse instanceof MultipleComponentsFoundException) { Log.debug("lookup already failed: " + cse); throw (MultipleComponentsFoundException)cse; } Set set = new HashSet(); match = getCachedLookup(hierarchy); if (match != null) { // This is always valid if (AWT.isSharedInvisibleFrame(match)) return match; // TODO: always use the cached lookup; since TestHierarchy // auto-disposes, only improperly disposed components will still // match. Codify this behavior with an explicit test. // Normally, we'd always want to use the cached lookup, but there // are instances where a component hierarchy may be used in a // transient way, so a given reference may need to match more than // one object without the first having been properly disposed. // Consider a createDialog() method, which creates an identical // dialog on each invocation, with an OK button. Every call of // the method is semantically providing the same component, // although the implementation may create a new one each time. If // previous instances have not been properly disposed, we need a // way to prefer a brand new instance over an old one. We do that // by checking the cache window's showing state. // A showing match will trump a non-showing one, // but if there are multiple, non-showing matches, the cached // lookup will win. // We check the window, not the component itself, because some // components hide their children. Window w = AWT.getWindow(match); if (w != null && (w.isShowing() || getNonShowingMatches().get(this) == match)) { Log.debug("Using cached lookup for " + getID() + " (hierarchy=" + hierarchy + ")"); return match; } Log.debug("Skipping non-showing match (once) " + hashCode()); } weight = findMatchesInHierarchy(root, hierarchy, weight, set, newReferences); Log.debug("Found " + set.size() + " matches for " + toXMLString()); if (set.size() == 1) { match = (Component)set.iterator().next(); } else if (set.size() > 0) { // Distinguish between more than one match with the exact same // weight try { match = bestMatch(set); } catch(MultipleComponentsFoundException e) { getLookupFailures().put(this, e); throw e; } } if (match == null) { String msg = "No component found which matches " + toXMLString(); ComponentNotFoundException e = new ComponentNotFoundException(msg); getLookupFailures().put(this, e); throw e; } // This provides significant speedup when many similar components are // in play. Log.debug("Cacheing match: " + Integer.toHexString(match.hashCode())); cachedLookup = new WeakReference(match); if (!match.isShowing()) { getNonShowingMatches().put(this, match); } return match; } /** Return the the set of all components under the given component's * hierarchy (inclusive) which match the given reference. */ private int findMatchesInHierarchy(Component root, Hierarchy hierarchy, int currentMaxWeight, Set currentSet, Map newReferences) { if (root == null) { // Examine all top-level components and their owned windows. Iterator iter = hierarchy.getRoots().iterator(); while (iter.hasNext()) { currentMaxWeight = findMatchesInHierarchy((Window)iter.next(), hierarchy, currentMaxWeight, currentSet, newReferences); } return currentMaxWeight; } if (!hierarchy.contains(root)) { Log.debug("Component not in hierarchy"); return currentMaxWeight; } int weight = getMatchWeight(root, newReferences); if (weight > currentMaxWeight) { currentSet.clear(); currentMaxWeight = weight; currentSet.add(root); } else if (weight == currentMaxWeight) { currentSet.add(root); } // TODO: don't check window contents in the hierarchy if the cref is a // Window. oops, how do you tell the cref is a Window? // (no window tag, parent tag or root tag, no index tag) // no guarantee, though Collection kids = hierarchy.getComponents(root); Iterator iter = kids.iterator(); while (iter.hasNext()) { Component child = (Component)iter.next(); currentMaxWeight = findMatchesInHierarchy(child, hierarchy, currentMaxWeight, currentSet, newReferences); } return currentMaxWeight; } /** Given an array of name, value pairs, generate a map suitable for creating a ComponentReference. */ private static Map createAttributeMap(String[][] values) { Map map = new HashMap(); for (int i=0;i < values.length;i++) { map.put(values[i][0], values[i][1]); } return map; } private static final Comparator HORDER_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { Component c1 = (Component)o1; Component c2 = (Component)o2; int x1 = -100000; int x2 = -100000; try { x1 = c1.getLocationOnScreen().x; } catch(Exception e) { } try { x2 = c2.getLocationOnScreen().x; } catch(Exception e) { } return x1 - x2; } }; private static final Comparator VORDER_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { Component c1 = (Component)o1; Component c2 = (Component)o2; int y1 = -100000; int y2 = -100000; try { y1 = c1.getLocationOnScreen().y; } catch(Exception e) { } try { y2 = c2.getLocationOnScreen().y; } catch(Exception e) { } return y1 - y2; } }; public int compareTo(Object o) { return getID().compareTo(((ComponentReference)o).getID()); } private String getComponentWindowTitle(Component c) { Component parent = c; while (!(c instanceof Frame || c instanceof Dialog) && (c = resolver.getHierarchy().getParent(parent)) != null) { parent = c; } String title = null; if (parent instanceof Frame) { title = ((Frame)parent).getTitle(); } else if (parent instanceof Dialog) { title = ((Dialog)parent).getTitle(); } return title; } private static Map getLookupFailures() { return (Map)lookupFailures.get(); } private static Map getNonShowingMatches() { return (Map)nonShowingMatches.get(); } public String getUniqueID(Map refs) { String id = getDescriptiveName(); String ext = ""; int count = 2; while (refs.get(id + ext) != null || resolver.getComponentReference(id + ext) != null) { ext = " " + count++; } return id + ext; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Condition.java
package abbot.script; /** @deprecated Use abbot.util.Condition instead. */ public interface Condition extends abbot.util.Condition { }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Event.java
package abbot.script; import java.awt.*; import java.awt.event.*; import java.util.*; import abbot.*; import abbot.finder.*; import abbot.tester.ComponentTester; import abbot.util.AWT; /** Script step to generate a single AWT event to a component. Currently * used for key down/up and mouse motion. */ // TODO: Save mouse motion/enter/leave as relative to containing window/frame, // in case frame moves public class Event extends Step { private static final String USAGE = "<event type=\"...\" kind=\"...\" [...]/>"; private String componentID = null; private String type = null; private String kind = null; private Map eventAttributes = new HashMap(); public Event(Resolver resolver, Map attributes) { super(resolver, attributes); componentID = (String)attributes.get(TAG_COMPONENT); // can't create events without a component, so creation of the event // is deferred. we do check for validity, though. parseEvent(attributes); } /** Create one based on the given event. */ public Event(Resolver resolver, String desc, AWTEvent event) { super(resolver, desc); int id = event.getID(); type = simpleClassName(event.getClass()); kind = ComponentTester.getEventID(event); Component comp = ((ComponentEvent)event).getComponent(); if (event instanceof MouseEvent) { MouseEvent me = (MouseEvent)event; ComponentReference ref = resolver.addComponent(comp); componentID = ref.getID(); eventAttributes.put(TAG_X, String.valueOf(me.getX())); eventAttributes.put(TAG_Y, String.valueOf(me.getY())); // Convert enter/exit to mouse moved if (id == MouseEvent.MOUSE_ENTERED || id == MouseEvent.MOUSE_EXITED || id == MouseEvent.MOUSE_DRAGGED) kind = "MOUSE_MOVED"; // No need to include modifiers in a captured event; it is assumed // that the modifiers are captured separately if (me.isPopupTrigger()) eventAttributes.put(TAG_TRIGGER, "true"); } else if (event instanceof KeyEvent) { KeyEvent ke = (KeyEvent)event; ComponentReference ref = resolver.addComponent(comp); componentID = ref.getID(); if (ke.getModifiers() != 0) { eventAttributes.put(TAG_MODIFIERS, AWT. getModifiers(ke)); } if (id == KeyEvent.KEY_TYPED) { // Must encode keychars (e.g. '<') eventAttributes.put(TAG_KEYCHAR, String.valueOf(ke.getKeyChar())); } else { eventAttributes.put(TAG_KEYCODE, AWT. getKeyCode(ke.getKeyCode())); } } else { throw new IllegalArgumentException("Unimplemented event type " + event); } } public String getDefaultDescription() { String desc = type + "." + kind; if (type.equals("KeyEvent")) desc += " (" + eventAttributes.get(TAG_KEYCODE) + ")"; if (componentID != null) desc += " on ${" + componentID + "}"; return desc; } public String getXMLTag() { return TAG_EVENT; } public String getUsage() { return USAGE; } public Map getAttributes() { Map map = super.getAttributes(); map.put(TAG_COMPONENT, componentID); map.put(TAG_TYPE, type); if (kind != null) map.put(TAG_KIND, kind); map.putAll(eventAttributes); return map; } /** Send our event to the component's event queue. */ public void runStep() throws Throwable { ComponentTester.getTester(java.awt.Component.class). sendEvent(createEvent(System.currentTimeMillis())); } /** Validate the attributes are sufficient to construct an event. */ private void parseEvent(Map map) { type = (String)map.get(TAG_TYPE); componentID = (String)map.get(TAG_COMPONENT); kind = (String)map.get(TAG_KIND); if (type == null) usage("AWT event type missing"); if (type.endsWith("MouseEvent")) { String modifiers = (String)map.get(TAG_MODIFIERS); String x = (String)map.get(TAG_X); String y = (String)map.get(TAG_Y); String count = (String)map.get(TAG_COUNT); String trigger = (String)map.get(TAG_TRIGGER); if (kind == null) usage("MouseEvent must specify a kind"); if (modifiers != null) eventAttributes.put(TAG_MODIFIERS, modifiers); if (x != null) eventAttributes.put(TAG_X, x); if (y != null) eventAttributes.put(TAG_Y, y); if (count != null) eventAttributes.put(TAG_COUNT, count); if (trigger != null) eventAttributes.put(TAG_TRIGGER, trigger); if (type.equals("MenuDragMouseEvent")) { // FIXME } } else if (type.equals("KeyEvent")) { if (kind == null) usage("KeyEvent must specify a kind"); String keyCode = (String)map.get(TAG_KEYCODE); String modifiers = (String)map.get(TAG_MODIFIERS); // Saved characters might be XML-encoded String keyChar = (String)map.get(TAG_KEYCHAR); if (keyCode == null) { if (!kind.equals("KEY_TYPED")) usage("KeyPress/Release require a keyCode"); } else if (!kind.equals("KEY_TYPED")) eventAttributes.put(TAG_KEYCODE, keyCode); if (keyChar == null) { if (kind.equals("KEY_TYPED")) usage("KeyTyped requires a keyChar"); } else if (kind.equals("KEY_TYPED")) { eventAttributes.put(TAG_KEYCHAR, keyChar); } if (modifiers != null && !"".equals(modifiers)) { eventAttributes.put(TAG_MODIFIERS, modifiers); } } // FIXME what others are important? window events? else { Log.warn("Unimplemented event type '" + type + "', placeholder"); //usage("Unimplemented event type '" + type + "'"); } } /** Resolve the given name into a component. */ protected java.awt.Component resolve(String name) throws NoSuchReferenceException, ComponentNotFoundException, MultipleComponentsFoundException { ComponentReference ref = getResolver().getComponentReference(name); if (ref != null) { return ref.getComponent(); } throw new NoSuchReferenceException(name); } /** Create an event based on the parameters we've collected */ private AWTEvent createEvent(long timestamp) throws ComponentSearchException, NoSuchReferenceException { Component comp = null; if (componentID != null) { comp = resolve(componentID); } long when = timestamp; if (type.endsWith("MouseEvent")) { int x = (comp.getSize().width + 1)/2; int y = (comp.getSize().height + 1)/2; int count = 1; boolean trigger = false; String modifiers = (String)eventAttributes.get(TAG_MODIFIERS); int mods = modifiers != null ? AWT.getModifiers(modifiers) : 0; try { x = Integer.parseInt((String)eventAttributes.get(TAG_X)); } catch(Exception exc) {} try { y = Integer.parseInt((String)eventAttributes.get(TAG_Y)); } catch(Exception exc) {} try { count = Integer.parseInt((String)eventAttributes.get(TAG_COUNT)); } catch(Exception exc) {} try { trigger = Boolean.getBoolean((String)eventAttributes.get(TAG_TRIGGER)); } catch(Exception exc) {} int id = ComponentTester.getEventID(MouseEvent.class, kind); return new MouseEvent(comp, id, when, mods, x, y, count, trigger); } else if (type.equals("KeyEvent")) { String modifiers = (String)eventAttributes.get(TAG_MODIFIERS); int mods = modifiers != null ? AWT.getModifiers(modifiers) : 0; int code = AWT.getKeyCode((String)eventAttributes.get(TAG_KEYCODE)); String ch = (String)eventAttributes.get(TAG_KEYCHAR); char keyChar = ch != null ? ch.charAt(0) : (char)code; int id = ComponentTester.getEventID(KeyEvent.class, kind); return new KeyEvent(comp, id, when, mods, code, keyChar); } throw new IllegalArgumentException("Bad event type " + type); } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getComponentID() { return componentID; } public void setComponentID(String id) { componentID = id; } public String getAttribute(String tag) { return (String)eventAttributes.get(tag); } public void setAttribute(String tag, String value) { eventAttributes.put(tag, value); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/EventExceptionHandler.java
package abbot.script; import abbot.*; import abbot.util.EventDispatchExceptionHandler; public class EventExceptionHandler extends EventDispatchExceptionHandler { protected void exceptionCaught(Throwable thr) { if (thr.getClass().getName(). equals(ExitException.class.getName())) { Log.debug("Application attempted exit from the event " + "dispatch thread, ignoring it"); Log.debug(thr); } else if (thr instanceof NullPointerException && Log.getStack(Log.FULL_STACK, thr). indexOf("createHierarchyEvents") != -1) { // java 1.3 hierarchy listener bug, most likely Log.debug("Apparent hierarchy NPE bug:\n" + Log.getStack(Log.FULL_STACK, thr)); } else { Log.warn("Unexpected exception while dispatching events:"); Log.warn(thr); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Expression.java
package abbot.script; import java.util.Iterator; import java.util.Map; import javax.script.ScriptException; import org.jdom.CDATA; import org.jdom.Element; /** Provides evaluation of arbitrary Java expressions. Any Java expression is supported, with a more loose syntax if desired. See the <a href="http://groovy.codehaus.org">groovey documentation</a> for complete details of the extended features available in this evaluator. <p> Note that any variables declared or assigned will be available to any subsequent steps in the same Script. */ public class Expression extends Step { public static final String TAG_EXPRESSION = "expression"; private static final String USAGE = "<expression>{java/groovey expression}</expression>"; private String expression = ""; public Expression(Resolver resolver, Element el, Map attributes) { super(resolver, attributes); String expr = null; Iterator iter = el.getContent().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof CDATA) { expr = ((CDATA)o).getText(); break; } } if (expr == null) expr = el.getText(); setExpression(expr); } public Expression(Resolver resolver, String description) { super(resolver, description); } public String getDefaultDescription() { return getExpression(); } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_EXPRESSION; } protected Element addContent(Element el) { return el.addContent(new CDATA(getExpression())); } public void setExpression(String text) { expression = text; } public String getExpression() { return expression; } /** Evaluates the expression. */ protected void runStep() throws Throwable { Interpreter sh = (Interpreter) getResolver().getProperty(Script.INTERPRETER); try { sh.eval(ArgumentParser.substitute(getResolver(), getExpression())); } catch(ScriptException e) { throw e; } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Fixture.java
package abbot.script; import java.util.Map; import abbot.Log; import abbot.finder.Hierarchy; import abbot.i18n.Strings; import abbot.util.SystemState; /** Provides a method of defining a single script as the UI application test * context for multiple scripts. A script which uses a fixture step (as * opposed to an explicit launch) will only instantiate the fixture if it does * not already exist.<p> * A Fixture will only be run once for any consecutive group of * <code>Script</code>s that refer to it. The {@link StepRunner} class is * normally used to control execution and will manage fixture setup/teardown * as needed. */ public class Fixture extends Script implements UIContext { private static Fixture currentFixture = null; public Fixture(String filename, Hierarchy h) { super(filename, h); } /** Construct a <code>Fixture</code> from its XML attributes. */ public Fixture(Resolver parent, Map attributes) { super(parent, attributes); setHierarchy(parent.getHierarchy()); } /** Run the entire fixture, using the given runner as a controller/monitor. */ public void launch(StepRunner runner) throws Throwable { runner.run(this); } /** @return Whether this fixture is currently launched. */ public boolean isLaunched() { return equivalent(currentFixture); } /** Don't re-run if already launched. */ protected void runStep(StepRunner runner) throws Throwable { if (!isLaunched()) { if (currentFixture != null) currentFixture.terminate(); currentFixture = this; super.runStep(runner); } } public void terminate() { Log.debug("fixture terminate"); if (equivalent(currentFixture)) { if (currentFixture != this) { currentFixture.terminate(); } else { UIContext context = getUIContext(); if (context != null) context.terminate(); currentFixture = null; } } } public String getXMLTag() { return TAG_FIXTURE; } public String getDefaultDescription() { String ext = isForked() ? " &" : ""; String desc = Strings.get("fixture.desc", new Object[] { getFilename(), ext }); return desc.indexOf(UNTITLED_FILE) != -1 ? UNTITLED : desc; } /** Two fixtures are equivalent if they have the same XML representation. */ public boolean equivalent(UIContext f) { return f instanceof Fixture && (equals(f) || getFullXMLString().equals(((Fixture)f).getFullXMLString())); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/ForkedStepRunner.java
package abbot.script; import java.io.*; import java.net.*; import java.util.*; import abbot.*; import abbot.finder.AWTHierarchy; import abbot.i18n.Strings; import abbot.util.*; import abbot.util.Properties; /** * A StepRunner that runs the step in a separate VM. Behavior should be * indistinguishable from the base StepRunner. */ public class ForkedStepRunner extends StepRunner { int LAUNCH_TIMEOUT = Properties.getProperty("abbot.runner.launch_delay", 60000, 0, 300000); int TERMINATE_TIMEOUT = Properties.getProperty("abbot.runner.terminate_delay", 30000, 0, 300000); private static ServerSocket serverSocket = null; private Process process = null; private Socket connection = null; /** When actually within the separate VM, this is what gets run. */ protected static class SlaveStepRunner extends StepRunner { private Socket connection = null; private Script script = null; /** Notify the master when the application exits. */ protected SecurityManager createSecurityManager() { return new ExitHandler() { public void checkExit(int status) { // handle application exit; send something back to // the master if called from System.exit String msg = Strings.get("runner.slave_premature_exit", new Object[] { new Integer(status) }); fireStepError(script, new Error(msg)); } }; } /** Translate the given event into something we can send back to the * master. */ private void forwardEvent(StepEvent event) { Step step = event.getStep(); final StringBuffer sb = new StringBuffer(encodeStep(script, step)); sb.append("\n"); sb.append(event.getType()); sb.append("\n"); sb.append(event.getID()); Throwable thr = event.getError(); if (thr != null) { sb.append("\nMSG:"); sb.append(thr.getMessage()); sb.append("\nSTR:"); sb.append(thr.toString()); sb.append("\nTRC:"); StringWriter writer = new StringWriter(); thr.printStackTrace(new PrintWriter(writer)); sb.append(writer.toString()); } try { writeMessage(connection, sb.toString()); } catch(IOException io) { // nothing we can do } } /** Handle running a script as a forked process. */ public void launchSlave(int port) { // make connection back to originating port try { InetAddress local = InetAddress.getLocalHost(); connection = new Socket(local, port); } catch(Throwable thr) { // Can't communicate so the only option is to quit Log.warn(thr); System.exit(1); } script = new Script(new AWTHierarchy()); try { String dirName = readMessage(connection); // Make sure the relative directory of this script is set // properly. script.setFile(new File(new File(dirName), script.getFile().getName())); String contents = readMessage(connection); script.load(new StringReader(contents)); Log.debug("Successfully loaded script, dir=" + dirName); // Make sure we only fork once! script.setForked(false); } catch(IOException io) { Log.warn(io); System.exit(2); } catch(Throwable thr) { Log.debug(thr); StepEvent event = new StepEvent(script, StepEvent.STEP_ERROR, 0, thr); forwardEvent(event); } // add listener to send messages back to the master addStepListener(new StepListener() { public void stateChanged(StepEvent ev) { forwardEvent(ev); } }); // Run the script like we normally would. The listener handles // all events and communication back to the launching process try { SlaveStepRunner.this.run(script); } catch(Throwable thr) { // Listener catches all events and forwards them, so no one // else is interested. just quit. Log.debug(thr); } try { connection.close(); } catch(IOException io) { // not much we can do Log.warn(io); } // Return zero even on failure/error, since the script run itself // worked, regardless of test results. System.exit(0); } } public ForkedStepRunner() { this(null); } public ForkedStepRunner(StepRunner parent) { super(parent != null ? parent.helper : null); if (parent != null) { setStopOnError(parent.getStopOnError()); setStopOnFailure(parent.getStopOnFailure()); setTerminateOnError(parent.getTerminateOnError()); } } Process fork(String vmargs, String[] cmdArgs) throws IOException { String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; ArrayList args = new ArrayList(); args.add(java); args.add("-cp"); String cp = System.getProperty("java.class.path"); // Ensure the framework is included in the class path String acp = System.getProperty("abbot.class.path"); if (acp != null) { cp += System.getProperty("path.separator") + acp; } args.add(cp); if (vmargs != null) { StringTokenizer st = new StringTokenizer(vmargs); while (st.hasMoreTokens()) { args.add(st.nextToken()); } } args.addAll(Arrays.asList(cmdArgs)); if (Log.isClassDebugEnabled(getClass())) { args.add("--debug"); args.add(getClass().getName()); } cmdArgs = (String[])args.toArray(new String[args.size()]); Process p = Runtime.getRuntime().exec(cmdArgs); return p; } /** Launch a new process, using this class as the main class. */ Process fork(String vmargs) throws UnknownHostException, IOException { if (serverSocket == null) { serverSocket = new ServerSocket(0); } int localPort = serverSocket.getLocalPort(); String[] args = { getClass().getName(), String.valueOf(localPort), String.valueOf(getStopOnFailure()), String.valueOf(getStopOnError()), String.valueOf(getTerminateOnError()) }; Process p = fork(vmargs, args); new ProcessOutputHandler(p) { public void handleOutput(byte[] buf, int count) { System.out.println("[out] " + new String(buf, 0, count)); } public void handleError(byte[] buf, int count) { System.err.println("[err] " + new String(buf, 0, count)); } }; return p; } /** Running the step in a separate VM should be indistinguishable from * running a regular script. When running as master, nothing actually * runs locally. We just fork a subprocess and run the script in that, * reporting back its progress as if it were running locally. */ public void runStep(Step step) throws Throwable { Log.debug("run step " + step); // Fire the start event prior to forking, then ignore the subsequent // forked script start event when we get it. fireStepStart(step); process = null; try { Script script = (Script)step; process = forkProcess(script.getVMArgs()); sendScript(script); try { trackScript(script); try { process.waitFor(); } catch(InterruptedException e) { throw new InterruptedAbbotException("Interrupted when waiting for process"); } try { process.exitValue(); } catch(IllegalThreadStateException its) { try { Thread.sleep(TERMINATE_TIMEOUT); } catch(InterruptedException ie) { throw new InterruptedAbbotException("Interrupted when waiting for process to terminate"); } // check again? } } catch(IOException io) { fireStepError(script, io); if (getStopOnError()) throw io; } } catch(junit.framework.AssertionFailedError afe) { fireStepFailure(step, afe); if (getStopOnFailure()) throw afe; } catch(Throwable thr) { fireStepError(step, thr); if (getStopOnError()) throw thr; } finally { // Destroy it whether it's terminated or not. if (process != null) process.destroy(); } fireStepEnd(step); } private Process forkProcess(String vmargs) throws Throwable { try { // fork new VM // wait for connection Process p = fork(vmargs); serverSocket.setSoTimeout(LAUNCH_TIMEOUT); connection = serverSocket.accept(); Log.debug("Got slave connection on " + connection); return p; } catch(InterruptedIOException ie) { Log.warn(ie); throw new RuntimeException(Strings.get("runner.slave_timed_out")); } } private void sendScript(Script script) throws IOException { // send script data StringWriter writer = new StringWriter(); script.save(writer); writeMessage(connection, script.getDirectory().toString()); writeMessage(connection, writer.toString()); } private void trackScript(Script script) throws IOException, ForkedFailure, ForkedError { StepEvent ev; while (!stopped() && (ev = receiveEvent(script)) != null) { Log.debug("Forked event received: " + ev); // If it's the script start event, ignore it since we // already sent one prior to launching the process if (ev.getStep() == script && (StepEvent.STEP_START.equals(ev.getType()) || StepEvent.STEP_END.equals(ev.getType()))) { continue; } Log.debug("Replaying forked event locally " + ev); Throwable err = ev.getError(); if (err != null) { setError(ev.getStep(), err); fireStepEvent(ev); if (err instanceof junit.framework.AssertionFailedError) { if (getStopOnFailure()) throw (ForkedFailure)err; } else { if (getStopOnError()) throw (ForkedError)err; } } else { fireStepEvent(ev); } } } static Step decodeStep(Sequence root, String code) { if (code.equals("-1")) return root; int comma = code.indexOf(","); if (comma == -1) { // Let number format exceptions propagate up, since it's a fatal // script error. int index = Integer.parseInt(code); return root.getStep(index); } String ind = code.substring(0, comma); code = code.substring(comma + 1); return decodeStep((Sequence)root.getStep(Integer.parseInt(ind)), code); } /** Encode the given step into a set of indices. */ static String encodeStep(Sequence root, Step step) { if (root.equals(step)) return "-1"; synchronized(root.steps()) { int index = root.indexOf(step); if (index != -1) return String.valueOf(index); index = 0; Iterator iter = root.steps().iterator(); while (iter.hasNext()) { Step seq = (Step)iter.next(); if (seq instanceof Sequence) { String encoding = encodeStep((Sequence)seq, step); if (encoding != null) { return index + "," + encoding; } } ++index; } return null; } } /** Receive a serialized event on the connection and convert it back into * a real event, setting the local representation of the given step's * exception/error if necessary. */ private StepEvent receiveEvent(Script script) throws IOException { String buf = readMessage(connection); if (buf == null) { Log.debug("End of stream"); return null; // end of stream } StringTokenizer st = new StringTokenizer(buf, "\n"); String code = st.nextToken(); String type = st.nextToken(); String id = st.nextToken(); Step step = decodeStep(script, code); Throwable thr = null; if (st.hasMoreTokens()) { String msg = st.nextToken(); String string; String trace; msg = msg.substring(4); String next = st.nextToken(); while (!next.startsWith("STR:")) { msg += next; next = st.nextToken(); } string = next.substring(4); next = st.nextToken(); while (!next.startsWith("TRC:")) { string += next; next = st.nextToken(); } trace = next.substring(4); while (st.hasMoreTokens()) { trace = trace + "\n" + st.nextToken(); } if (type.equals(StepEvent.STEP_FAILURE)) { Log.debug("Creating local forked step failure"); thr = new ForkedFailure(msg, string, trace); } else { Log.debug("Creating local forked step error"); thr = new ForkedError(msg, string, trace); } } StepEvent event = new StepEvent(step, type, Integer.parseInt(id), thr); return event; } private static void writeMessage(Socket connection, String msg) throws IOException { OutputStream os = connection.getOutputStream(); byte[] buf = msg.getBytes(); int len = buf.length; for (int i=0;i < 4;i++) { byte val = (byte)(len >> 24); os.write(val); len <<= 8; } os.write(buf, 0, buf.length); os.flush(); } private static String readMessage(Socket connection) throws IOException { InputStream is = connection.getInputStream(); // FIXME probably want a socket timeout, in case the slave script // hangs int len = 0; for (int i=0;i < 4;i++) { int data = is.read(); if (data == -1) { return null; } len = (len << 8) | data; } byte[] buf = new byte[len]; int offset = 0; while (offset < len) { int count = is.read(buf, offset, buf.length - offset); if (count == -1) { return null; } offset += count; } String msg = new String(buf, 0, len); return msg; } /** An exception that looks almost exactly like some other exception, without actually having access to the instance of the original exception. */ class ForkedFailure extends AssertionFailedError { private String msg; private String str; private String trace; public ForkedFailure(String msg, String str, String trace) { this.msg = msg + " (forked)"; this.str = str + " (forked)"; this.trace = trace + " (forked)"; } public String getMessage() { return msg; } public String toString() { return str; } public void printStackTrace(PrintWriter writer) { synchronized(writer) { writer.print(trace); } } public void printStackTrace(PrintStream s) { synchronized(s) { s.print(trace); } } public void printStackTrace() { printStackTrace(System.err); } } /** An exception that for all purposes looks like another exception. */ class ForkedError extends RuntimeException { private String msg; private String str; private String trace; public ForkedError(String msg, String str, String trace) { this.msg = msg + " (forked)"; this.str = str + " (forked)"; this.trace = trace + " (forked)"; } public String getMessage() { return msg; } public String toString() { return str; } public void printStackTrace(PrintWriter writer) { synchronized(writer) { writer.print(trace); } } public void printStackTrace(PrintStream s) { synchronized(s) { s.print(trace); } } public void printStackTrace() { printStackTrace(System.err); } } /** Provide means to control execution and feedback of a script in a separate process. */ public static void main(String[] args) { args = Log.init(args); try { final int port = Integer.parseInt(args[0]); final SlaveStepRunner runner = new SlaveStepRunner(); runner.setStopOnFailure("true".equals(args[1])); runner.setStopOnError("true".equals(args[2])); runner.setTerminateOnError("true".equals(args[3])); new Thread(new Runnable() { public void run() { runner.launchSlave(port); } }, "Forked script").start(); } catch(Throwable e) { System.err.println("usage: abbot.script.ForkedStepRunner <port>"); System.exit(1); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Interpreter.java
package abbot.script; import abbot.Log; import abbot.finder.BasicFinder; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** Provides a Groovy interpreter customized for the Costello scripting * environment. */ public class Interpreter { private static ScriptEngineManager MANAGER = new ScriptEngineManager(); private ScriptEngine engine; public Interpreter(Resolver r) { try { engine = MANAGER.getEngineByName("groovy"); //Bindings bindings = se.getBindings(ScriptEngine.) engine.put("finder", new BasicFinder(r.getHierarchy())); engine.put("resolver", r); engine.put("script", r); engine.put("engine", engine); InputStream is = getClass().getResourceAsStream("init.groovy"); engine.eval(new BufferedReader(new InputStreamReader(is))); } catch(ScriptException e) { Log.warn("Error initializing interpreter: ",e); } } /** * Evaluate the groovy expression * @throws ScriptException */ public Object eval(String expression) throws ScriptException { return engine.eval(expression); } /** * @return A bound value */ public Object get(String value) { return engine.get(value); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/InvalidScriptException.java
package abbot.script; import org.jdom.Element; /** Exception to indicate the script being parsed is invalid. */ public class InvalidScriptException extends RuntimeException { public InvalidScriptException(String msg) { super(msg); } public InvalidScriptException(String msg, Element el) { super(msg + " (when parsing " + el.toString() + ")"); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Launch.java
package abbot.script; import java.awt.Window; import java.lang.reflect.*; import java.util.Map; import java.util.Iterator; import abbot.finder.Hierarchy; import abbot.*; import abbot.i18n.Strings; /** * Provides scripted static method invocation. Usage:<br> * <blockquote><code> * &lt;launch class="package.class" method="methodName" args="..." * classpath="..." [threaded=true]&gt;<br> * </code></blockquote><p> * The args attribute is a comma-separated list of arguments to pass to the * class method, and may use square brackets to denote an array, * e.g. "[one,two,three]" will be interpreted as an array length 3 * of String. The square brackets may be escaped ('\[' or '\]') to include * them literally in an argument. * <p> * The class path attribute may use either colon or semicolon as a path * separator, but should preferably use relative paths to avoid making the * containing script platform- and location-dependent.<p> * In most cases, the classes under test will <i>only</i> be found under the * custom class path, and so the parent class loader will fail to find them. * If this is the case then the classes under test will be properly discarded * on each launch when a new class loader is created. * <p> * The 'threaded' attribute is provided in case your code under test requires * GUI event processing prior to returning from its invoked method. An * example might be a main method which invokes dialog and waits for the * response before continuing. In general, it's better to refactor the code * if possible so that the main method turns over control to the event * dispatch thread as soon as possible. Otherwise, if the application under * test is background threaded by the Launch step, any runtime exceptions * thrown from the launch code will cause errors in the launch step out of * sequence with the other script steps. While this won't cause any problems * for the Abbot framework, it can be very confusing for the user.<p> * Note that if the "reload" attribute is set true (i.e. Abbot's class loader * is used to reload code under test), ComponentTester extensions must also be * loaded by that class loader, so the path to extensions should be included * in the Launch class path.<p> */ public class Launch extends Call implements UIContext { /** Allow only one active launch at a time. */ private static Launch currentLaunch = null; private String classpath = null; private boolean threaded = false; private transient AppClassLoader classLoader; private transient ThreadedLaunchListener listener; private static final String USAGE = "<launch class=\"...\" method=\"...\" args=\"...\" " + "[threaded=true]>"; public Launch(Resolver resolver, Map attributes) { super(resolver, attributes); classpath = (String)attributes.get(TAG_CLASSPATH); String thr = (String)attributes.get(TAG_THREADED); if (thr != null) threaded = Boolean.valueOf(thr).booleanValue(); } public Launch(Resolver resolver, String description, String className, String methodName, String[] args) { this(resolver, description, className, methodName, args, null, false); } public Launch(Resolver resolver, String description, String className, String methodName, String[] args, String classpath, boolean threaded) { super(resolver, description, className, methodName, args); this.classpath = classpath; this.threaded = threaded; } public String getClasspath() { return classpath; } public void setClasspath(String cp) { classpath = cp; // invalidate class loader classLoader = null; } public boolean isThreaded() { return threaded; } public void setThreaded(boolean thread) { threaded = thread; } protected AppClassLoader createClassLoader() { return new AppClassLoader( // Make sure we allow variable subsitution on the classpath ArgumentParser.substitute(getResolver(), classpath)); } /** Install the class loader context for the code being launched. The * context class loader for the current thread is modified. */ protected void install() { ClassLoader loader = getContextClassLoader(); // Everything else loaded on the same thread as this // launch should be loaded by this custom loader. if (loader instanceof AppClassLoader && !((AppClassLoader)loader).isInstalled()) { ((AppClassLoader)loader).install(); } } protected void synchronizedRunStep() throws Throwable { // A bug in pre-1.4 VMs locks the toolkit prior to notifying AWT event // listeners. This causes a deadlock when the main method invokes // "show" on a component which triggers AWT events for which there are // listeners. To avoid this, grab the toolkit lock first so that the // locks are acquired in the same order by either sequence. // (Unfortunately, some swing code locks the tree prior to // grabbing the toolkit lock, so there's still opportunity for // deadlock). One alternative (although very heavyweight) is to // always fork a separate VM. // // If threaded, take the danger of deadlock over the possibility that // the main method will never return and leave the lock forever held. // NOTE: this is guaranteed to deadlock if "main" calls // EventQueue.invokeAndWait. if (Platform.JAVA_VERSION < Platform.JAVA_1_4 && !isThreaded()) { synchronized(java.awt.Toolkit.getDefaultToolkit()) { super.runStep(); } } else { super.runStep(); } } /** Perform steps necessary to remove any setup performed by * this <code>Launch</code> step. */ public void terminate() { Log.debug("launch terminate"); if (currentLaunch == this) { // Nothing special to do, dispose windows normally Iterator iter = getHierarchy().getRoots().iterator(); while (iter.hasNext()) getHierarchy().dispose((Window)iter.next()); if (classLoader != null) { classLoader.uninstall(); classLoader = null; } currentLaunch = null; } } /** Launches the UI described by this <code>Launch</code> step, * using the given runner as controller/monitor. */ public void launch(StepRunner runner) throws Throwable { runner.run(this); } /** @return Whether the code described by this launch step is currently active. */ public boolean isLaunched() { return currentLaunch == this; } public Hierarchy getHierarchy() { return getResolver().getHierarchy(); } public void runStep() throws Throwable { if (currentLaunch != null) currentLaunch.terminate(); currentLaunch = this; install(); System.setProperty("abbot.framework.launched", "true"); if (isThreaded()) { Thread threaded = new Thread("Threaded " + toString()) { public void run() { try { synchronizedRunStep(); } catch(AssertionFailedError e) { if (listener != null) listener.stepFailure(Launch.this, e); } catch(Throwable t) { if (listener != null) listener.stepError(Launch.this, t); } } }; threaded.setDaemon(true); threaded.setContextClassLoader(classLoader); threaded.start(); } else { synchronizedRunStep(); } } /** Overrides the default implementation to always use the class loader * defined by this step. This works in cases where the Launch step has * not yet been added to a Script; otherwise the Script will provide an * implementation equivalent to this one. */ public Class resolveClass(String className) throws ClassNotFoundException { return Class.forName(className, true, getContextClassLoader()); } /** Return the class loader that uses the classpath defined in this * step. */ public ClassLoader getContextClassLoader() { if (classLoader == null) { // Use a custom class loader so that we can provide additional // classpath and also optionally reload the class on each run. // FIXME maybe classpath should be relative to the script? In this // case, it's relative to user.dir classLoader = createClassLoader(); } return classLoader; } public Class getTargetClass() throws ClassNotFoundException { Class cls = resolveClass(getTargetClassName()); Log.debug("Target class is " + cls.getName()); return cls; } /** Return the target for the method invocation. All launch invocations * must be static, so this always returns null. */ protected Object getTarget(Method m) { return null; } /** Return the method to be used for invocation. */ public Method getMethod() throws ClassNotFoundException, NoSuchMethodException { return resolveMethod(getMethodName(), getTargetClass(), null); } public Map getAttributes() { Map map = super.getAttributes(); if (classpath != null) { map.put(TAG_CLASSPATH, classpath); } if (threaded) { map.put(TAG_THREADED, "true"); } return map; } public String getDefaultDescription() { String desc = Strings.get("launch.desc", new Object[] { getTargetClassName() + "." + getMethodName() + "(" + getEncodedArguments() + ")"}); return desc; } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_LAUNCH; } /** Set a listener to respond to events when the launch step is * threaded. */ public void setThreadedLaunchListener(ThreadedLaunchListener l) { listener = l; } public interface ThreadedLaunchListener { public void stepFailure(Launch launch, AssertionFailedError error); public void stepError(Launch launch, Throwable throwable); } /** No two launches are ever considered equivalent. If you want * a shared {@link UIContext}, use a {@link Fixture}. * @see abbot.script.UIContext#equivalent(abbot.script.UIContext) * @see abbot.script.StepRunner#run(Step) */ public boolean equivalent(UIContext context) { return false; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/NoSuchReferenceException.java
package abbot.script; /** Exception to indicate a Component reference does not exist. */ public class NoSuchReferenceException extends RuntimeException { public NoSuchReferenceException() { } public NoSuchReferenceException(String msg) { super(msg); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/PropertyCall.java
package abbot.script; import java.awt.Component; import java.lang.reflect.Method; import java.util.Map; import abbot.tester.ComponentTester; /** Provides support for using property-like methods, including select * non-static method access to Components. Specifically, allows specification * of a ComponentReference to be used as the method invocation target. If a * ComponentReference is given, then the class of the component reference is * used as the target class.<p> */ public abstract class PropertyCall extends Call { private String componentID = null; /** Create a PropertyCall based on loaded XML attributes. */ public PropertyCall(Resolver resolver, Map attributes) { super(resolver, patchAttributes(resolver, attributes)); componentID = (String)attributes.get(TAG_COMPONENT); } /** Create a PropertyCall based on a static invocation on an arbitrary class. */ public PropertyCall(Resolver resolver, String description, String className, String methodName, String[] args) { super(resolver, description, className, methodName, args); componentID = null; } /** Create a PropertyCall with a Component target. The target class name is derived from the given component reference ID. */ public PropertyCall(Resolver resolver, String description, String methodName, String id) { super(resolver, description, getRefClass(resolver, id), methodName, null); componentID = id; } /** Return the component reference ID used by this method invocation. */ public String getComponentID() { return componentID; } /** Set the component reference ID used by method invocation. The class * of the component referenced by the component reference will replace the * current target class. */ public void setComponentID(String id) { if (id == null) { componentID = null; } else { ComponentReference ref = getResolver().getComponentReference(id); if (ref != null) { componentID = id; setTargetClassName(ref.getRefClassName()); } else throw new NoSuchReferenceException(id); } } /** Save attributes specific to this Step class. */ public Map getAttributes() { Map map = super.getAttributes(); if (componentID != null) { map.remove(TAG_CLASS); map.put(TAG_COMPONENT, componentID); } return map; } /** Return the target of the method invocation. */ protected Object getTarget(Method m) throws Throwable { if (componentID != null) { return ArgumentParser.eval(getResolver(), componentID, Component.class); } return super.getTarget(m); } /** Insert default values if necessary. */ private static Map patchAttributes(Resolver resolver, Map map) { String id = (String)map.get(TAG_COMPONENT); if (id != null) { map.put(TAG_CLASS, getRefClass(resolver, id)); } return map; } private final static String[] prefixes = { "is", "has", "get" }; private final static Class[] returnTypes = { boolean.class, boolean.class, null, }; /** Returns whether the given method is a property accessor. In addition * to standard is/get/has property accessors, this includes * pseudo-property methods on ComponentTester objects. */ public static boolean isPropertyMethod(Method m) { String name = m.getName(); Class rt = m.getReturnType(); Class[] params = m.getParameterTypes(); Class dc = m.getDeclaringClass(); for (int i=0;i < prefixes.length;i++) { if (name.startsWith(prefixes[i]) && name.length() > prefixes[i].length() && Character.isUpperCase(name.charAt(prefixes[i].length())) && ((ComponentTester.class.isAssignableFrom(dc) && params.length == 1 && Component.class.isAssignableFrom(params[0])) || params.length == 0) && (returnTypes[i] == null || returnTypes[i].equals(rt))) { return true; } } return false; } public String getDefaultDescription() { String desc = super.getDefaultDescription(); if (getComponentID() != null) { desc = getComponentID() + "." + desc; } return desc; } /** Obtain the class of the given reference's component, or return * java.awt.Component if not found. */ private static String getRefClass(Resolver r, String id) { ComponentReference ref = r.getComponentReference(id); return ref == null ? Component.class.getName() : ref.getRefClassName(); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Resolver.java
package abbot.script; import java.awt.Component; import java.util.Collection; import java.io.File; import abbot.finder.Hierarchy; // TODO: extract reference management // o hierarchy // o refs collection // o name generation /** Interface to provide a general context in which tests are run. * Includes ComponentReferences, current gui hierarchy, properties, and a * working directory. */ public interface Resolver { /** Return the existing reference for the given component, or null if none exists. */ ComponentReference getComponentReference(Component comp); /** Add a new component to the existing collection. */ ComponentReference addComponent(Component comp); /** Add a new component reference to the existing collection. */ void addComponentReference(ComponentReference ref); /** Returns a collection of all the existing references. */ Collection getComponentReferences(); /** Return the ComponentReference matching the given id, or null if none exists. */ ComponentReference getComponentReference(String refid); /** Get Hierarchy used by this Resolver. */ Hierarchy getHierarchy(); /** Return the class loader for use in this context. */ ClassLoader getContextClassLoader(); /** Provide a working directory context for relative pathnames. */ File getDirectory(); /** Provide temporary storage of String values. */ void setProperty(String name, Object value); /** Provide retrieval of values from temporary storage. */ Object getProperty(String name); /** Provide a human-readable string that describes the given step's context. */ // TODO: this belongs in UIContext String getContext(Step step); }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Sample.java
package abbot.script; import java.util.Map; /** Encapsulate capture of a value. Usage:<br> * <blockquote><code> * &lt;sample property="..." method="assertXXX" [class="..."]&gt;<br> * &lt;sample property="..." method="(get|is|has)XXX" component="component_id"&gt;<br> * </code></blockquote> * The <b>sample</b> step stores the value found from the given method * {@link abbot.tester.ComponentTester} class; the class tag is required for * methods based on a class derived from {@link abbot.tester.ComponentTester}; * the class tag indicates the {@link java.awt.Component} class, not the * Tester class (the appropriate tester class will be derived automatically). * The second format indicates a property sample on the given component. * In both cases, the result of the invocation will be saved in the current * {@link abbot.script.Resolver} as a property with the given property name. */ public class Sample extends PropertyCall { private static final String USAGE = "<sample property=... component=... method=.../>\n" + "<sample property=... method=... [class=...]/>"; private String propertyName = null; public Sample(Resolver resolver, Map attributes) { super(resolver, attributes); propertyName = (String)attributes.get(TAG_PROPERTY); } /** Component property sample. */ public Sample(Resolver resolver, String description, String methodName, String id, String propName) { super(resolver, description, methodName, id); propertyName = propName; } /** Static method property sample. */ public Sample(Resolver resolver, String description, String className, String methodName, String[] args, String propName) { super(resolver, description, className, methodName, args); propertyName = propName; } public Map getAttributes() { Map map = super.getAttributes(); if (propertyName != null) { map.put(TAG_PROPERTY, propertyName); } return map; } public String getDefaultDescription() { return getPropertyName() + "=" + super.getDefaultDescription(); } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_SAMPLE; } public void setPropertyName(String name) { propertyName = name; } public String getPropertyName() { return propertyName; } /** Store the results of the invocation in the designated property as a String-encoded value. */ protected Object invoke() throws Throwable { Object obj = super.invoke(); if (propertyName != null) { getResolver().setProperty(propertyName, obj); } return obj; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Script.java
package abbot.script; import java.awt.Component; import java.io.*; import java.net.URL; import java.util.*; import org.jdom.*; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; import abbot.Log; import abbot.Platform; import abbot.finder.*; import abbot.i18n.Strings; import abbot.script.parsers.*; import abbot.tester.Robot; import abbot.util.Properties; /** * Provide a structure to encapsulate actions invoked on GUI components and * tests performed on those components. Scripts need to be short and concise * (and therefore easy to read/write). Extensions don't have to be.<p> * This takes a single filename as a constructor argument.<p> * Use {@link junit.extensions.abbot.ScriptFixture} and * {@link junit.extensions.abbot.ScriptTestSuite} * to generate a suite by auto-generating a collection of {@link Script}s.<p> * @see StepRunner * @see Fixture * @see Launch */ public class Script extends Sequence implements Resolver { public static final String INTERPRETER = "bsh"; private static final String USAGE = "<AWTTestScript [desc=\"\"] [forked=\"true\"] [slow=\"true\"]" + " [awt=\"true\"] [vmargs=\"...\"]>...</AWTTestScript>\n"; /** Robot delay for slow playback. */ private static int slowDelay = 250; static boolean validate = true; private String filename; private File relativeDirectory; private boolean fork; private boolean slow; private boolean awt; private int lastSaved; private String vmargs; private Map properties = new HashMap(); private Hierarchy hierarchy; public static final String UNTITLED_FILE = Strings.get("script.untitled_filename"); protected static final String UNTITLED = Strings.get("script.untitled"); /** Read-only map of ref IDs into ComponentReferences. */ private Map refs = Collections.unmodifiableMap(new HashMap()); /** Maps components to references. This cache provides a 20% speedup when * adding new references. */ private Map components = new WeakHashMap(); static { slowDelay = Properties.getProperty("abbot.script.slow_delay", slowDelay, 0, 60000); String defValue = Platform.JAVA_VERSION < Platform.JAVA_1_4 ? "false" : "true"; validate = "true".equals(System.getProperty("abbot.script.validate", defValue)); } protected static Map createDefaultMap(String filename) { Map map = new HashMap(); map.put(TAG_FILENAME, filename); return map; } /** Create a new, empty <code>Script</code>. Used as a temporary * {@link Resolver}, uses the default {@link Hierarchy}. * @deprecated Use an explicit {@link Hierarchy} instead. */ public Script() { // This is roughly equivalent to what // DefaultComponentFinder.getFinder() used to do this(AWTHierarchy.getDefault()); } /** Create a <code>Script</code> from the given filename. Uses the default {@link Hierarchy}. @deprecated Use an explicit {@link Hierarchy} instead. */ public Script(String filename) { // This is roughly equivalent to what // DefaultComponentFinder.getFinder() used to do this(filename, AWTHierarchy.getDefault()); } public Script(Hierarchy h) { this(null, new HashMap()); setHierarchy(h); } /** Create a <code>Script</code> from the given file. */ public Script(String filename, Hierarchy h) { this(null, createDefaultMap(filename)); setHierarchy(h); } public Script(Resolver parent, Map attributes) { super(parent, attributes); String filename = (String)attributes.get(TAG_FILENAME); File file = filename != null ? new File(filename) : getTempFile(parent != null ? parent.getDirectory() : null); // If this file is not absolute setFile is going to convert to a connoical // path so we actually need this to be relative to the parent, use useDir // if parent is not set as per bug 1922380 // if (!file.isAbsolute()) { file = new File( parent!=null ? parent.getDirectory() : getUserDir(), filename); } // Configure the file // setFile(file); if (parent != null) { setRelativeTo(parent.getDirectory()); } try { load(); } catch(IOException e) { setScriptError(e); } } /** Since we allow ComponentReference IDs to be changed, make sure our map * is always up to date. */ private synchronized void synchReferenceIDs() { HashMap map = new HashMap(); Iterator iter = refs.values().iterator(); while (iter.hasNext()) { ComponentReference ref = (ComponentReference)iter.next(); map.put(ref.getID(), ref); } if (!refs.equals(map)) { // atomic update of references map refs = Collections.unmodifiableMap(map); } } public void setHierarchy(Hierarchy h) { hierarchy = h; components.clear(); } private File getTempFile(File dir) { File file; try { file = (dir != null ? File.createTempFile(UNTITLED_FILE, ".xml", dir) : File.createTempFile(UNTITLED_FILE, ".xml")); // We don't actually need the file on disk file.delete(); } catch(IOException io) { file = (dir != null ? new File(dir, UNTITLED_FILE + ".xml") : new File(UNTITLED_FILE + ".xml")); } return file; } public String getName() { return filename; } public void setForked(boolean fork) { this.fork = fork; } public boolean isForked() { return fork; } public void setVMArgs(String args) { if (args != null && "".equals(args)) args = null; vmargs = args; } public String getVMArgs() { return vmargs; } public boolean isSlowPlayback() { return slow; } public void setSlowPlayback(boolean slow) { this.slow = slow; } public boolean isAWTMode() { return awt; } public void setAWTMode(boolean awt) { this.awt = awt; } /** Return the file where this script is saved. Will always be an * absolute path. */ public File getFile() { File file = new File(filename); if (!file.isAbsolute()) { String path = getRelativeTo().getPath() + File.separator + filename; file = new File(path); file = resolveRelativeReferences(file); } return file; } /** Change the file system basis for the current script. Does not affect the script contents. @deprecated Use {@link #setFile(File)}. */ public void changeFile(File file) { setFile(file); } /** Set the file system basis for this script object. Use this to set the file from which the existing script will be loaded. */ public void setFile(File file) { Log.debug("Script file set to " + file); if (file == null) throw new IllegalArgumentException("File must not be null"); if (filename == null || !file.equals(getFile())) { // Convert to full absolute version // file = resolveRelativeReferences(file); filename = file.getPath(); Log.debug("Script filename set to " + filename); if (relativeDirectory != null) setRelativeTo(relativeDirectory); } lastSaved = getHash() + 1; } /** Typical xml header, so we can know about how much file prefix to * skip. */ private static final String XML_INFO = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; /** Flag to indicate whether emitted XML should contain the script contents. Sometimes we just want a one-liner (like when displaying in the script editor), and sometimes we want the full contents (when writing to file). */ private boolean formatForSave = false; /** Write the current state of the script to file. */ public void save(Writer writer) throws IOException { formatForSave = true; Element el = toXML(); formatForSave = false; el.setName(TAG_AWTTESTSCRIPT); Document doc = new Document(el); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(doc, writer); } /** Only thing directly editable on a script is its file path. */ public String toEditableString() { return getFilename(); } /** Has this script changed since the last save. */ public boolean isDirty() { return getHash() != lastSaved; } /** Write the script to file. Note that this differs from the toXML for the script, which simply indicates the file on which it is based. */ public void save() throws IOException { File file = getFile(); Log.debug("Saving script to '" + file + "' " + hashCode()); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); save(new BufferedWriter(writer)); writer.close(); lastSaved = getHash(); } /** Ensure that all referenced components are actually in the components * list. */ private synchronized void verify() throws InvalidScriptException { Log.debug("verifying all referenced refs exist"); Iterator iter = refs.values().iterator(); while (iter.hasNext()) { ComponentReference ref = (ComponentReference)iter.next(); String id = ref.getAttribute(TAG_PARENT); if (id != null && refs.get(id) == null) { String msg = Strings.get("script.parent_missing", new Object[] { id }); throw new InvalidScriptException(msg); } id = ref.getAttribute(TAG_WINDOW); if (id != null && refs.get(id) == null) { String msg = Strings.get("script.window_missing", new Object[] { id }); throw new InvalidScriptException(msg); } } } /** Make the path to the given child script relative to this one. */ private void updateRelativePath(Step child) { // Make sure included scripts are located relative to this one if (child instanceof Script) { ((Script)child).setRelativeTo(getDirectory()); } } /**Parse XML attributes for the Script. */ protected void parseAttributes(Map map) { super.parseAttributes(map); fork = Boolean.valueOf((String)map.get(TAG_FORKED)).booleanValue(); slow = Boolean.valueOf((String)map.get(TAG_SLOW)).booleanValue(); awt = Boolean.valueOf((String)map.get(TAG_AWT)).booleanValue(); vmargs = (String)map.get(TAG_VMARGS); } protected void parseChild(Element el) throws InvalidScriptException { if (el.getName().equals(TAG_COMPONENT)) { addComponentReference(el); } else { synchronized(steps()) { super.parseChild(el); updateRelativePath((Step)steps().get(size()-1)); } } } /** Loads the XML test script. Performs a check against the XML schema. @param reader Provides the script data @throws InvalidScriptException @throws IOException */ public void load(Reader reader) throws InvalidScriptException, IOException { // Clear existing messages clear(); //Create the children from the reader createChildrenFromReader(reader, validate); // Make sure we have all referenced components synchronized(this) { synchReferenceIDs(); verify(); } lastSaved = getHash(); } public void addStep(int index, Step step) { super.addStep(index, step); updateRelativePath(step); } public void addStep(Step step) { super.addStep(step); updateRelativePath(step); } /** Replaces the step at the given index. */ public void setStep(int index, Step step) { super.setStep(index, step); updateRelativePath(step); } /** Read the script from the currently set file. */ public void load() throws IOException { File file = getFile(); if (!file.exists()) { if (getFilename().indexOf(Script.UNTITLED_FILE) == -1) Log.warn("Script " + this + " does not exist, ignoring it"); return; } if (!file.isFile()) throw new InvalidScriptException("Path " + getFilename() + " refers to a directory"); // Removed this check because on some windows 7 systems an // interaction with symlinks means that the file length is reported // as zero even though the final file when resolved does have bytes // in it, // // See issue 3396893 if (true) { //file.length() != 0) { try { final FileInputStream fis = new FileInputStream(file); try { // Give up if the file is empty if (fis.available()==0) { return; } Reader reader = new InputStreamReader(fis, "UTF-8"); load(new BufferedReader(reader)); } finally { try { fis.close(); } catch(IOException e) { } } } catch(FileNotFoundException e) { // should have been detected Log.warn("File '" + file + "' exists but is not found"); } } else { Log.warn("Script file " + this + " is empty"); } } protected String getFullXMLString() { try { formatForSave = true; return toXMLString(this); } finally { formatForSave = false; } } private int getHash() { return getFullXMLString().hashCode(); } public String getXMLTag() { return TAG_SCRIPT; } /** Save component references in addition to everything else. */ public Element addContent(Element el) { // Only save content if writing to disk if (formatForSave) { synchReferenceIDs(); Iterator iter = new TreeSet(refs.values()).iterator(); while (iter.hasNext()) { ComponentReference cref = (ComponentReference)iter.next(); el.addContent(cref.toXML()); } // Now collect our child steps return super.addContent(el); } return el; } /** Return the (possibly relative) path to this script. */ public String getFilename() { return filename; } /** Provide XML attributes for this Step. This class adds its filename. */ public Map getAttributes() { Map map; if (!formatForSave) { map = new HashMap(); // Ensure that any relative references are using // forward slashed for multiplatform compatibility. String f = getFilename(); if (f!=null && !new File(f).isAbsolute()) { f = f.replace('\\', '/'); } map.put(TAG_FILENAME, f); } else { map = super.getAttributes(); // default is no fork if (fork) { map.put(TAG_FORKED, "true"); if (vmargs != null) { map.put(TAG_VMARGS, vmargs); } } if (slow) { map.put(TAG_SLOW, "true"); } if (awt) { map.put(TAG_AWT, "true"); } } return map; } protected void runStep(StepRunner runner) throws Throwable { components.clear(); properties.clear(); // Make all files relative to this script Parser fc = new FileParser() { public String relativeTo() { Log.debug("All file references will be relative to " + getDirectory().getAbsolutePath()); return getDirectory().getAbsolutePath(); } }; Parser oldfc = ArgumentParser.setParser(File.class, fc); int oldDelay = Robot.getAutoDelay(); int oldMode = Robot.getEventMode(); if (slow) { Robot.setAutoDelay(slowDelay); } if (awt) { Robot.setEventMode(Robot.EM_AWT); } try { super.runStep(runner); } finally { Robot.setAutoDelay(oldDelay); Robot.setEventMode(oldMode); ArgumentParser.setParser(File.class, oldfc); } } /** Set up a blank script, discarding any current state. */ public void clear() { setScriptError(null); refs = Collections.unmodifiableMap(new HashMap()); components.clear(); super.clear(); } public String getUsage() { return USAGE; } /** Return a default description for this <code>Script</code>. */ public String getDefaultDescription() { String ext = fork ? " &" : ""; String desc = Strings.get("script.desc", new Object[] { getFilename(), ext }); return desc.indexOf(UNTITLED_FILE) != -1 ? UNTITLED : desc; } /** Return whether this <code>Script</code> is launchable. */ public boolean hasLaunch() { // First step might be a Launch or a Fixture return size() > 0 && (((Step)steps().get(0)) instanceof UIContext); } /** @return The {@link UIContext} responsible for setting up * a UI context for this script, or * <code>null</code> if the script has no UI to speak of. */ public UIContext getUIContext() { synchronized(steps()) { if (hasLaunch()) { return (UIContext)steps().get(0); } } return null; } /** Defer to the {@link UIContext} to obtain a * {@link ClassLoader}, or use the current {@link Thread}'s * context class loader. * @see Thread#getContextClassLoader() */ public ClassLoader getContextClassLoader() { UIContext context = getUIContext(); return context != null ? context.getContextClassLoader() : Thread.currentThread().getContextClassLoader(); } public boolean hasTerminate() { return size() > 0 && (((Step)steps().get(size()-1)) instanceof Terminate); } /** By default, all pathnames are relative to the current working directory. */ public File getRelativeTo() { if (relativeDirectory == null) return getUserDir(); return relativeDirectory; } /** Return the user directory for use whent he parent dir is null */ private static File getUserDir() { return new File(System.getProperty("user.dir")); } /** Indicate that when invoking toXML, a path relative to the given one * should be shown. Note that this is a runtime setting only and never * shows up in saved XML. */ public void setRelativeTo(File dir) { Log.debug("Want relative dir " + dir); // If the old relatative directory is not null then convert the // filename back to a non relative path // if (relativeDirectory!=null) { File file = new File(filename); if (!file.isAbsolute()) { file = new File(relativeDirectory, filename); try { filename = file.getCanonicalPath(); } catch (IOException ioe) { filename = file.getPath(); } } } // relativeDirectory = dir; if (dir != null) { // More robust relative path examples File currentParent = resolveRelativeReferences(dir); StringBuffer relativePath = new StringBuffer(); searchParents: do { String relPath = currentParent.getAbsolutePath(); if (filename.startsWith(relPath) && relPath.length() < filename.length()) { char ch = filename.charAt(relPath.length()); if (ch == '/' || ch == '\\') { // We have found a match relativePath.append(filename.substring(relPath.length() + 1)); filename = relativePath.toString().replace('\\', '/'); break searchParents; } } // Do the loop again // currentParent = currentParent.getParentFile(); relativePath.append("../"); } while (currentParent != null); } Log.debug("Relative dir set to " + relativeDirectory + " for " + this); } /** * It turns out that getAbsolutePath doesn't remove any relative path * entries such as .. the alternative getCannonicalPath can cause problems * with version control systems that make a lot of use of symolic links. * For example a directory in a source control view might contain local * checked out files and symlinks to un-checked out files (These files * might be located on another machine in some cases). This means that * files that are next to each other in the view appear to be in quite * different paths when resolved using getCannonicalPath. Therefore we are * reduced to tidying up the paths manually. * * @param file The input file to tidy up. * @return An absolute path with all . and .. removed * @throws IllegalArgumentException If the number of ".." entries outnumber * those of the normal path entries. */ public static File resolveRelativeReferences(File file) { StringBuffer fixAbsolutePath = new StringBuffer(); String originalPath = file.getAbsolutePath(); String parts[] = originalPath.split("(\\\\|/)"); // Work backwards // int dirDebt = 0; for (int i = parts.length-1; i >= 0; i--) { String part = parts[i]; if (part.length() == 0) { ; // ignore this } else if (".".equals(part)) { ; // ignore dot paths } else if ("..".equals(part)) { dirDebt ++; // Record an path we have to run out } else { if (dirDebt > 0){ dirDebt --; } else { fixAbsolutePath.insert(0, part); fixAbsolutePath.insert(0, File.separatorChar); } } } if (dirDebt > 0) { throw new IllegalArgumentException("Run out of path"); } return new File(fixAbsolutePath.toString()); } /** Return whether the given file looks like a valid AWT script. */ public static boolean isScript(File file) { // See issue 3396893 // Remove file length checks because of windows 7 at least File.length // for synlinks returns 0 in all cases which means that these tests are bogus // if (file.length() == 0) // return true; if (!file.exists() || !file.isFile()) // || file.length() < TAG_AWTTESTSCRIPT.length() * 2 + 5) return false; InputStream is = null; try { int len = XML_INFO.length() + TAG_AWTTESTSCRIPT.length() + 15; is = new BufferedInputStream(new FileInputStream(file)); byte[] buf = new byte[len]; is.read(buf, 0, buf.length); String str = new String(buf, 0, buf.length); return str.indexOf(TAG_AWTTESTSCRIPT) != -1; } catch(Exception exc) { return false; } finally { if (is != null) try { is.close(); } catch(Exception exc) { } } } /** All relative files should be accessed relative to this directory, which is the directory where the script resides. It will always return an absolute path. */ public File getDirectory() { return getFile().getParentFile(); } /** Returns a sorted collection of ComponentReferences. */ public Collection getComponentReferences() { return new TreeSet(refs.values()); } /** Add a component reference directly, replacing any existing one with the same ID. */ public void addComponentReference(ComponentReference ref) { Log.debug("adding " + ref); synchReferenceIDs(); HashMap map = new HashMap(refs); map.put(ref.getID(), ref); // atomic update of references map refs = Collections.unmodifiableMap(map); } /** Add a new component reference for the given component. */ // FIXME: a repaint (tree locked) which accesses the refs list // deadlocks with cref creation (locks refs, asks for tree lock) // Either get tree lock first or don't require refs lock on read public ComponentReference addComponent(Component comp) { synchReferenceIDs(); Log.debug("look up existing for " + Robot.toString(comp)); Map newRefs = new HashMap(); ComponentReference ref = ComponentReference.getReference(this, comp, newRefs); Log.debug("adding " + Robot.toString(comp)); Map map = new HashMap(refs); map.putAll(newRefs); Iterator iter = newRefs.values().iterator(); while (iter.hasNext()) { ComponentReference r = (ComponentReference)iter.next(); Component c = r.getCachedLookup(getHierarchy()); if (c != null) components.put(c, r); } // atomic update of references map refs = Collections.unmodifiableMap(map); return ref; } /** Add a new component reference to the script. For use only when * parsing a script. */ ComponentReference addComponentReference(Element el) throws InvalidScriptException { synchReferenceIDs(); ComponentReference ref = new ComponentReference(this, el); Log.debug("adding " + el); Map map = new HashMap(refs); map.put(ref.getID(), ref); // atomic update of references map refs = Collections.unmodifiableMap(map); return ref; } /** Return the reference for the given component, or null if none yet * exists. */ public ComponentReference getComponentReference(Component comp) { if (!getHierarchy().contains(comp)) { String msg = Strings.get("script.not_in_hierarchy", new Object[] { comp.toString() }); throw new IllegalArgumentException(msg); } synchReferenceIDs(); // Clear the component map if any one of the mappings is invalid Iterator iter = refs.values().iterator(); while (iter.hasNext()) { ComponentReference cr = (ComponentReference)iter.next(); if (cr.getCachedLookup(getHierarchy()) == null) { components.clear(); break; } } ComponentReference ref = (ComponentReference)components.get(comp); if (ref != null) { if (ref.getCachedLookup(getHierarchy()) != null) return ref; components.remove(comp); } ref = ComponentReference.matchExisting(comp, refs.values()); if (ref != null) { components.put(comp, ref); } return ref; } /** Convert the given reference ID into a component reference. If it's * not in the Script's list, returns null. */ public ComponentReference getComponentReference(String name) { synchReferenceIDs(); return (ComponentReference)refs.get(name); } public void setProperty(String name, Object value) { if (value == null) properties.remove(name); else properties.put(name, value); } public Object getProperty(String name) { Object value = properties.get(name); // Lazy-load the interpreter, so it's only instantiated when required if (value == null && INTERPRETER.equals(name)) { Interpreter bsh = new Interpreter(this); properties.put(name, value = bsh); } return value; } /** Return the currently effective {@link Hierarchy} of components. */ public Hierarchy getHierarchy() { Resolver r = getResolver(); if (r != null && r != this) return r.getHierarchy(); return hierarchy != null ? hierarchy : AWTHierarchy.getDefault(); } /** Return a meaningful description of where the Step came from. */ public String getContext(Step step) { return getFile().toString() + ":" + getLine(this, step); } /** Return the file which defines the given step. */ public static File getFile(Step step) { String context = step.getResolver().getContext(step); int colon = context.indexOf(":"); if (colon == 1 && Character.isLetter(context.charAt(0)) && Platform.isWindows() && context.length() > 2) colon = context.indexOf(":", 2); if (colon != -1) context = context.substring(0, colon); return new File(context); } /** Return the approximate line number of the given step. File lines are one-based (there is no line zero). */ public static int getLine(Step step) { String context = step.getResolver().getContext(step); int colon = context.indexOf(":"); if (colon == 1 && Character.isLetter(context.charAt(0)) && Platform.isWindows() && context.length() > 2) colon = context.indexOf(":", 2); context = context.substring(colon + 1); try { return Integer.parseInt(context); } catch(NumberFormatException e) { return -1; } } private static int getLine(Sequence seq, Step step) { int line = -1; int index = seq.indexOf(step); if (index == -1) { List list = seq.steps(); for (int i=0;i < list.size();i++) { Step sub = (Step)list.get(i); if (sub instanceof Sequence) { int subline = getLine((Sequence)sub, step); if (subline != -1) { line = countLines(seq, i) + subline; break; } } } } else { line = countLines(seq, index); } return line; } /** Return the number of XML lines in the given sequence that precede the * given index. If the index is -1, return the number of XML lines used * by the whole sequence. */ public static int countLines(Sequence seq, int index) { int count = 1; int limit = index; if (limit == -1) { limit = seq.size(); // Empty sequences take a single line if (limit == 0) return 1; // Otherwise, 2 + the line count of the contents count = 2; } if (seq instanceof Script) { // Add in one line per component reference in the script // Plus two lines for the <xml> and <AWTTestScript> lines count += ((Script)seq).getComponentReferences().size() + 2; } for (int i=0;i < limit;i++) { Step step = seq.getStep(i); // Included scripts take only one line if (step instanceof Script) { ++count; } else if (step instanceof Sequence) { count += countLines((Sequence)step, -1); } else { ++count; } } return count; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/ScriptFilter.java
package abbot.script; import java.io.File; import javax.swing.filechooser.FileFilter; import abbot.Platform; import abbot.i18n.Strings; public class ScriptFilter extends FileFilter { /** Indicate whether the given file should appear in the browser. */ public boolean accept(File file) { // OSX has a buggy file chooser, gets NPE if you open a directory if (Platform.isOSX() && Platform.JAVA_VERSION <= 0x1400) { } return Script.isScript(file) || file.isDirectory(); } /** Indicate the combo box entry used to describe files of this type. */ public String getDescription() { return Strings.get("editor.filechooser.script_desc"); } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Sequence.java
package abbot.script; import abbot.InterruptedAbbotException; import abbot.Log; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.util.*; import org.jdom.Document; import org.jdom.Element; import abbot.i18n.Strings; import java.io.StringReader; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; /** Script step which groups a sequence of other Steps. The sub-Steps have a * fixed order and are executed in the order contained in the sequence. * Events sent by sub-Steps are propagated by this one. */ public class Sequence extends Step { private static final String USAGE = "<sequence ...>...</sequence>"; private ArrayList sequence = new ArrayList(); /** Construct a <code>Sequence</code> from XML data. */ public Sequence(Resolver resolver, Element el, Map atts) { super(resolver, atts); try { parseChildren(el); } catch(InvalidScriptException ise) { setScriptError(ise); } } public Sequence(Resolver resolver, Map atts) { super(resolver, atts); } public Sequence(Resolver resolver, String desc) { this(resolver, desc, null); } /** Create an aggregate from a list of existing <code>Step</code>s. */ public Sequence(Resolver resolver, String desc, List steps) { super(resolver, desc); if (steps != null) { Iterator iter = steps.iterator(); synchronized(sequence) { while(iter.hasNext()) { addStep((Step)iter.next()); } } } } protected void parseChild(Element el) throws InvalidScriptException { Step step = createStep(getResolver(), el); addStep(step); } protected void parseChildren(Element el) throws InvalidScriptException { synchronized(sequence) { Iterator iter = el.getContent().iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj instanceof Element) parseChild((Element)obj); else if (obj instanceof org.jdom.Comment) { String text = ((org.jdom.Comment)obj).getText(); addStep(new abbot.script.Comment(getResolver(), text)); } } } } public String getDefaultDescription() { return Strings.get("sequence.desc", new Object[] { String.valueOf(size()) }); } public String getXMLTag() { return TAG_SEQUENCE; } protected Element addContent(Element el) { ArrayList seq; synchronized(sequence) { seq = (ArrayList)sequence.clone(); } Iterator iter = seq.iterator(); while (iter.hasNext()) { Step step = (Step)iter.next(); if (step instanceof abbot.script.Comment) el.addContent(new org.jdom.Comment(step.getDescription())); else el.addContent(step.toXML()); } return el; } /** Returns a string describing the proper XML usage for this class. */ public String getUsage() { return USAGE; } /** Only thing directly editable on a sequence is its description. */ public String toEditableString() { return getDescription(); } /** Process each event in our list. */ protected void runStep() throws Throwable { runStep(null); } /** Process each event in our list, using the given runner. */ protected void runStep(StepRunner runner) throws Throwable { Iterator iter; synchronized(sequence) { iter = ((ArrayList)sequence.clone()).iterator(); } if (runner != null) { while (iter.hasNext() && !runner.stopped()) { if (Thread.interrupted()) { throw new InterruptedAbbotException("Interrupted when running a step"); } runner.runStep((Step)iter.next()); } } else { while (iter.hasNext()) { if (Thread.interrupted()) { throw new InterruptedAbbotException("Interrupted when running a step"); } ((Step)iter.next()).run(); } } } /** Returns the number of steps contained in this one. */ public int size() { synchronized(sequence) { return sequence.size(); } } /** Remove all stepchildren. More effective than Cinderella's stepmother. */ public void clear() { synchronized(sequence) { sequence.clear(); } } /** Returns a list of the steps contained in this one. */ public java.util.List steps() { return sequence; } /** Returns the index of the given step in the sequence, or -1 if the step is not in the sequence. */ public int indexOf(Step step) { synchronized(sequence) { return sequence.indexOf(step); } } /** Return the step at the given index in the sequence. */ public Step getStep(int index) { synchronized(sequence) { return (Step)sequence.get(index); } } /** Inserts a step at the given index in the sequence. */ public void addStep(int index, Step step) { synchronized(sequence) { sequence.add(index, step); } } /** Adds a step to the end of the sequence. */ public void addStep(Step step) { synchronized(sequence) { sequence.add(step); } } /** Replaces the step at the given index. */ public void setStep(int index, Step step) { synchronized(sequence) { sequence.set(index, step); } } /** Removes the step if it exists in the sequence. */ public void removeStep(Step step) { synchronized(sequence) { sequence.remove(step); } } /** Removes the step at the given index in the sequence. */ public void removeStep(int index) { synchronized(sequence) { sequence.remove(index); } } /** * @param string A string that is the serialized for of just a sequence * @return A sequence object containing the relavent items */ public static Sequence createSequenceFromString(Resolver resolver, String string) throws IOException { Sequence seq = new Sequence(resolver, "Temporary Sequence"); seq.createChildrenFromReader(new StringReader(string), false); return seq; } /** * This method takes the given input reader and tries to load the contained elements, this * is exposed here so that it is possible to create a sequence from a clipboard snippet. * @param reader * @param validate Whether to perform validation, use false for the moment for snippets * @throws IOException */ protected void createChildrenFromReader(Reader reader, boolean validate) throws IOException { try { // Set things up to optionally validate on load SAXBuilder builder = new SAXBuilder(validate); if (validate) { URL url = getClass().getClassLoader().getResource("abbot/abbot.xsd"); if (url != null) { builder.setFeature("http://apache.org/xml/features/validation/schema", true); builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", url.toString()); } else { Log.warn("Could not find abbot/abbot.xsd, disabling XML validation"); validate = false; } } Document doc = builder.build(reader); Element root = doc.getRootElement(); Map map = createAttributeMap(root); parseAttributes(map); parseChildren(root); } catch (JDOMException e) { throw new InvalidScriptException(e.getMessage()); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Step.java
package abbot.script; import java.awt.Component; import java.io.*; import java.lang.reflect.*; import java.util.*; import org.jdom.*; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import abbot.Log; import abbot.i18n.Strings; import abbot.tester.ComponentTester; /** * Provides access to one step (line) from a script. A Step is the basic * unit of execution. * <b>Custom Step classes</b><p> * All custom {@link Step} classes must supply a {@link Constructor} with the * signature <code>&lt;init&gt;(${link Resolver}, {@link Map})</code>. If * the step has contents (e.g. {@link Sequence}), then it should also * provide a {@link Constructor} with the signature * <code>&lt;init&gt;({@link Resolver}, {@link Element}, {@link Map})</code>. * <p> * The XML tag for a given {@link Step} will be used to auto-generate the * {@link Step} class name, e.g. the tag &lt;aphrodite/&gt; causes the * parser to create an instance of class <code>abbot.script.Aphrodite</code>, * using one of the {@link Constructor}s described above. * <p> * All derived classes should include an entry in the * <a href={@docRoot}/../abbot.xsd>schema</a>, or validation must be turned * off by setting the System property * <code>abbot.script.validate=false</code>. * <p> * You can make the custom <code>Aphrodite</code> step do just about anything * by overriding the {@link #runStep()} method. * <p> * See the source for any {@link Step} implementation in this package for * examples. */ public abstract class Step implements XMLConstants, XMLifiable, Serializable { private String description = null; private Resolver resolver; /** Error encountered on parse. */ private Throwable invalidScriptError = null; public Step(Resolver resolver, Map attributes) { this(resolver, ""); Log.debug("Instantiating " + getClass()); if (Log.isClassDebugEnabled(Step.class)) { Iterator iter = attributes.keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); Log.debug(key + "=" + attributes.get(key)); } } parseAttributes(attributes); } public Step(Resolver resolver, String description) { // Kind of a hack; a Script is its own resolver if (resolver == null) { if (!(this instanceof Resolver)) { throw new Error("Resolver must be provided"); } resolver = (Resolver)this; } else if (this instanceof Resolver) { resolver = (Resolver)this; } this.resolver = resolver; if ("".equals(description)) description = null; this.description = description; } /** Only exposed so that Script may invoke it on load from disk. */ protected void parseAttributes(Map attributes) { Log.debug("Parsing attributes for " + getClass()); description = (String)attributes.get(TAG_DESC); } /** Main run method. Should <b>never</b> be run on the event dispatch * thread, although no check is explicitly done here. */ public final void run() throws Throwable { if (invalidScriptError != null) throw invalidScriptError; Log.debug("Running " + toString()); runStep(); } /** Implement the step's behavior here. */ protected abstract void runStep() throws Throwable; public String getDescription() { return description != null ? description : getDefaultDescription(); } public void setDescription(String desc) { description = desc; } /** Define the XML tag to use for this script step. */ public abstract String getXMLTag(); /** Provide a usage String for this step. */ public abstract String getUsage(); /** Return a reasonable default description for this script step. This value is used in the absence of an explicit description. */ public abstract String getDefaultDescription(); /** For use by subclasses when an error is encountered during parsing. * Should only be used by the XML parsing ctors. */ protected void setScriptError(Throwable thr) { if (invalidScriptError == null) { invalidScriptError = thr; } else { Log.warn("More than one script error encountered: " + thr); Log.warn("Already have: " + invalidScriptError); } } /** Throw an invalid script exception describing the proper script * usage. This should be used by derived classes whenever parsing * indicates invalid input. */ protected void usage() { usage(null); } /** Store an invalid script exception describing the proper script * usage. This should be used by derived classes whenever parsing * indicates invalid input. */ protected void usage(String details) { String msg = getUsage(); if (details != null) { msg = Strings.get("step.usage", new Object[] { msg, details }); } setScriptError(new InvalidScriptException(msg)); } /** Attributes to save in script. */ public Map getAttributes() { Map map = new HashMap(); if (description != null && !description.equals(getDefaultDescription())) map.put(TAG_DESC, description); return map; } public Resolver getResolver() { return resolver; } /** Override if the step actually has some contents. In most cases, it * won't. */ protected Element addContent(Element el) { return el; } /** Add an attribute to the given XML Element. Attributes are kept in alphabetical order. */ protected Element addAttributes(Element el) { // Use a TreeMap to keep the attributes sorted on output Map atts = new TreeMap(getAttributes()); Iterator iter = atts.keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); String value = (String)atts.get(key); if (value == null) { Log.warn("Attribute '" + key + "' value was null in step " + getXMLTag()); value = ""; } el.setAttribute(key, value); } return el; } /** Convert this Step into a String suitable for editing. The default is the XML representation of the Step. */ public String toEditableString() { return toXMLString(this); } /** Provide a one-line XML string representation. */ public static String toXMLString(XMLifiable obj) { // Comments are the only things that aren't actually elements... if (obj instanceof Comment) { return "<!-- " + ((Comment)obj).getDescription() + " -->"; } Element el = obj.toXML(); StringWriter writer = new StringWriter(); try { XMLOutputter outputter = new XMLOutputter(); outputter.output(el, writer); } catch(IOException io) { Log.warn(io); } return writer.toString(); } /** Convert the object to XML. */ public Element toXML() { return addAttributes(addContent(new Element(getXMLTag()))); } /** Create a new step from an in-line XML string. */ public static Step createStep(Resolver resolver, String str) throws InvalidScriptException, IOException { StringReader reader = new StringReader(str); try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(reader); Element el = doc.getRootElement(); return createStep(resolver, el); } catch(JDOMException e) { throw new InvalidScriptException(e.getMessage()); } } /** Convert the attributes in the given XML Element into a Map of name/value pairs. */ protected static Map createAttributeMap(Element el) { Log.debug("Creating attribute map for " + el); Map attributes = new HashMap(); Iterator iter = el.getAttributes().iterator(); while (iter.hasNext()) { Attribute att = (Attribute)iter.next(); attributes.put(att.getName(), att.getValue()); } return attributes; } /** * Factory method, equivalent to a "fromXML" for step creation. Looks for * a class with the same name as the XML tag, with the first letter * capitalized. For example, &lt;call /&gt; is abbot.script.Call. */ public static Step createStep(Resolver resolver, Element el) throws InvalidScriptException { String tag = el.getName(); Map attributes = createAttributeMap(el); String name = tag.substring(0, 1).toUpperCase() + tag.substring(1); if (tag.equals(TAG_WAIT)) { attributes.put(TAG_WAIT, "true"); name = "Assert"; } try { name = "abbot.script." + name; Log.debug("Instantiating " + name); Class cls = Class.forName(name); try { // Steps with contents require access to the XML element Class[] argTypes = new Class[] { Resolver.class, Element.class, Map.class }; Constructor ctor = cls.getConstructor(argTypes); return (Step)ctor.newInstance(new Object[] { resolver, el, attributes }); } catch(NoSuchMethodException nsm) { // All steps must support this ctor Class[] argTypes = new Class[] { Resolver.class, Map.class }; Constructor ctor = cls.getConstructor(argTypes); return (Step)ctor.newInstance(new Object[] { resolver, attributes }); } } catch(ClassNotFoundException cnf) { String msg = Strings.get("step.unknown_tag", new Object[] { tag }); throw new InvalidScriptException(msg); } catch(InvocationTargetException ite) { Log.warn(ite); throw new InvalidScriptException(ite.getTargetException(). getMessage()); } catch(Exception exc) { Log.warn(exc); throw new InvalidScriptException(exc.getMessage()); } } protected String simpleClassName(Class cls) { return ComponentTester.simpleClassName(cls); } /** Return a description of this script step. */ public String toString() { return getDescription(); } /** Returns the Class corresponding to the given class name. Provides * just-in-time classname resolution to ensure loading by the proper class * loader. <p> */ public Class resolveClass(String className) throws ClassNotFoundException { ClassLoader cl = getResolver().getContextClassLoader(); return Class.forName(className, true, cl); } /** Look up an appropriate ComponentTester given an arbitrary * Component-derived class. * If the class is derived from abbot.tester.ComponentTester, instantiate * one; if it is derived from java.awt.Component, return a matching Tester. * Otherwise return abbot.tester.ComponentTester.<p> * @throws ClassNotFoundException If the given class can't be found. * @throws IllegalArgumentException If the tester cannot be instantiated. */ protected ComponentTester resolveTester(String className) throws ClassNotFoundException { Class testedClass = resolveClass(className); if (Component.class.isAssignableFrom(testedClass)) return ComponentTester.getTester(testedClass); else if (ComponentTester.class.isAssignableFrom(testedClass)) { try { return (ComponentTester)testedClass.newInstance(); } catch(Exception e) { String msg = "Custom ComponentTesters must provide " + "an accessible no-args Constructor: " + e.getMessage(); throw new IllegalArgumentException(msg); } } String msg = "The given class '" + className + "' is neither a Component nor a ComponentTester"; throw new IllegalArgumentException(msg); } private void writeObject(ObjectOutputStream out) { // NOTE: this is only to avoid drag/drop errors out = null; } private void readObject(ObjectInputStream in) { // NOTE: this is only to avoid drag/drop errors in = null; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/StepEvent.java
package abbot.script; import abbot.Log; public class StepEvent extends java.util.EventObject implements Cloneable { /** The step has begun executing. */ public static final String STEP_START = "step-start"; /** The step is N% complete. */ public static final String STEP_PROGRESS = "step-progress"; /** The step has finished. */ public static final String STEP_END = "step-end"; /** The step encountered an error. */ public static final String STEP_ERROR = "step-error"; /** The step failed. This represents a test that failed to produce the expected results. */ public static final String STEP_FAILURE = "step-failure"; /** Multi-use field. Currently only used by STEP_PROGRESS. */ private int id; /** What type of step event (start, end, etc.) */ private String type; /** Error or failure, if any. */ private Throwable throwable = null; public StepEvent(Step source, String type, int id, Throwable throwable) { super(source); Log.debug("Source is " + source); this.type = type; this.id = id; this.throwable = throwable; } public Object clone() { return new StepEvent((Step)getSource(), type, id, throwable); } public Step getStep() { return (Step)getSource(); } public String getType() { return type; } public int getID() { return id; } public String toString() { return type + ", (step " + getStep() + ")"; } public Throwable getError() { return throwable; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/StepListener.java
package abbot.script; /** Listener for script step feedback. */ public interface StepListener { void stateChanged(StepEvent event); }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/StepRunner.java
package abbot.script; import java.util.*; import java.io.File; import javax.swing.SwingUtilities; import abbot.*; import abbot.finder.Hierarchy; import abbot.finder.TestHierarchy; import abbot.i18n.Strings; import abbot.util.*; /** Provides control and tracking of the execution of a step or series of steps. By default the runner stops execution on the first encountered failure/error. The running environment is preserved to the extent possible, which includes discarding any GUI components created by the code under test.<p> If you wish to preserve the application state when there is an error, you can use the method {@link #setTerminateOnError(boolean)}. */ public class StepRunner { private static UIContext currentContext = null; private boolean stopOnFailure = true; private boolean stopOnError = true; /** Whether to terminate the app after an error/failure. */ private boolean terminateOnError = true; /** Whether to terminate the app after stopping. */ private transient boolean terminateOnStop = false; private ArrayList listeners = new ArrayList(); private Map errors = new HashMap(); /** Whether to stop running. */ private transient boolean stop = false; /** Use this to catch event dispatch exceptions. */ private EDTExceptionCatcher catcher; protected AWTFixtureHelper helper; protected Hierarchy hierarchy; /** This ctor uses a new instance of TestHierarchy as the * default Hierarchy. Note that any existing GUI components at the time * of this object's creation will be ignored. */ public StepRunner() { this(new AWTFixtureHelper()); } /** Create a new runner. The given {@link Hierarchy} maintains which GUI * components are in or out of scope of the runner. The {@link AWTFixtureHelper} * will be used to restore state if {@link #terminate()} is called. */ public StepRunner(AWTFixtureHelper helper) { this.helper = helper; this.catcher = new EDTExceptionCatcher(); catcher.install(); hierarchy = helper!=null ? helper.getHierarchy() : null; } /** * @return The designated hierarchy for this <code>StepRunner</code>, * or <code>null</code> if none. */ public Hierarchy getHierarchy() { Hierarchy h = currentContext != null && currentContext.isLaunched() ? currentContext.getHierarchy() : hierarchy; return h; } public UIContext getCurrentContext() { return currentContext; } public void setStopOnFailure(boolean stop) { stopOnFailure = stop; } public void setStopOnError(boolean stop) { stopOnError = stop; } public boolean getStopOnFailure() { return stopOnFailure; } public boolean getStopOnError() { return stopOnError; } /** Stop execution of the script after the current step completes. The * launched application will be left in its current state. */ public void stop() { stop(false); } /** Stop execution, indicating whether to terminate the app. */ public void stop(boolean terminate) { stop = true; terminateOnStop = terminate; } /** Return whether the runner has been stopped. */ public boolean stopped() { return stop; } /** Create a security manager to use for the duration of this runner's execution. The default prevents invoked applications from invoking {@link System#exit(int)} and invokes {@link #terminate()} instead. */ protected SecurityManager createSecurityManager() { return new ExitHandler(); } /** Install a security manager to ensure we prevent the AUT from exiting and can clean up when it tries to. */ protected synchronized void installSecurityManager() { if (System.getSecurityManager() == null && !Boolean.getBoolean("abbot.no_security_manager")) { // When the application tries to exit, throw control back to the // step runner to dispose of it Log.debug("Installing sm"); System.setSecurityManager(createSecurityManager()); } } protected synchronized void removeSecurityManager() { if (System.getSecurityManager() instanceof ExitHandler) { System.setSecurityManager(null); } } /** If the given context is not the current one, terminate the current one * and set this one as current. */ private void updateContext(UIContext context) { if (!context.equivalent(currentContext)) { Log.debug("current=" + currentContext + ", new=" + context); if (currentContext != null) currentContext.terminate(); currentContext = context; } } /** Run the given step, propagating any failures or errors to * listeners. This method should be used for any execution * that should be treated as a single logical action. * This method is primarily used to execute a script, but may * be used in other circumstances to execute one or more steps * in isolation. * The {@link #terminate()} method will be invoked if the script is * stopped for any reason, unless {@link #setTerminateOnError(boolean)} * has been called with a <code>false</code> argument. Otherwise * {@link #terminate()} will only be called if a * {@link Terminate} step is encountered. * @see #terminate() */ public void run(Step step) throws Throwable { if (SwingUtilities.isEventDispatchThread()) { throw new Error(Strings.get("runner.bad_invocation")); } // Always clear locking keys before a test, to ensure we have // a consistent state SystemState.clearLockingKeys(); // Terminate incorrect contexts prior to doing any setup. // Even though a UIContext will invoke terminate on a // non-equivalent context, we need to make it happen // before anything gets run. UIContext context = null; if (step instanceof Script) { context = step instanceof UIContext ? (UIContext)step : ((Script)step).getUIContext(); } else if (step instanceof UIContext) { context = (UIContext)step; } if (context != null) { updateContext(context); } installSecurityManager(); boolean completed = false; clearErrors(); try { if ((step instanceof Script) && ((Script)step).isForked()) { Log.debug("Forking " + step); StepRunner runner = new ForkedStepRunner(this); runner.listeners.addAll(listeners); try { runner.runStep(step); } finally { errors.putAll(runner.errors); } } else { runStep(step); } completed = !stopped(); } catch(ExitException ee) { // application tried to exit Log.debug("App tried to exit"); terminate(); } finally { if (step instanceof Script) { if (completed && errors.size() == 0) { // Script was run successfully } else if (stopped() && terminateOnStop) { terminate(); } } removeSecurityManager(); } } /** Set whether the application under test should be terminated when an error is encountered and script execution stopped. The default implementation always terminates. */ public void setTerminateOnError(boolean state) { terminateOnError = state; } public boolean getTerminateOnError() { return terminateOnError; } protected void clearErrors() { stop = false; errors.clear(); } /** Throw an exception if the file does not exist. */ protected void checkFile(Script script) throws InvalidScriptException { File file = script.getFile(); if (!file.exists() && !file.getName().startsWith(Script.UNTITLED_FILE)) { String msg = "The script '" + script.getFilename() + "' does not exist at the expected location '" + file.getAbsolutePath() + "'"; throw new InvalidScriptException(msg); } } /** Main run method, which stores any failures or exceptions for later * retrieval. Any step will fire STEP_START events to all registered * {@link StepListener}s on starting, and exactly one * of STEP_END, STEP_FAILURE, or STEP_ERROR upon termination. If * stopOnFailure/stopOnError is set false, then both STEP_FAILURE/ERROR * may be sent in addition to STEP_END. */ protected void runStep(final Step step) throws Throwable { if (step instanceof Script) { checkFile((Script)step); ((Script)step).setHierarchy(getHierarchy()); } Log.debug("Running " + step); fireStepStart(step); // checking for stopped here allows a listener to stop execution on a // particular step in response to its "start" event. if (stopped()) { Log.debug("Already stopped, skipping " + step); } else { Throwable exception = null; long exceptionTime = -1; try { if (step instanceof Launch) { ((Launch)step).setThreadedLaunchListener(new LaunchListener()); } // Recurse into sequences if (step instanceof Sequence) { ((Sequence)step).runStep(this); } else { step.run(); } Log.debug("Finished " + step); if (step instanceof Terminate) { terminate(); } } catch(Throwable e) { exceptionTime = System.currentTimeMillis(); exception = e; } finally { // Cf. ComponentTestFixture.runBare() // Any EDT exception which occurred *prior* to when the // exception on the main thread was thrown should be used // instead. long edtExceptionTime = EDTExceptionCatcher.getThrowableTime(); Throwable edtException = EDTExceptionCatcher.getThrowable(); if (edtException != null && (exception == null || edtExceptionTime < exceptionTime)) { exception = edtException; } } if (exception != null) { if (exception instanceof junit.framework.AssertionFailedError) { Log.debug("failure in " + step + ": " + exception); fireStepFailure(step, exception); if (stopOnFailure) { stop(terminateOnError); throw exception; } } else { Log.debug("error in " + step + ": " + exception); fireStepError(step, exception); if (stopOnError) { stop(terminateOnError); throw exception; } } } fireStepEnd(step); } } /** Similar to {@link #run(Step)}, but defers to the {@link Script} * to determine what subset of steps should be run as the UI context. * @param step */ public void launch(Script step) throws Throwable { UIContext ctxt = step.getUIContext(); if (ctxt != null) { ctxt.launch(this); } } /** Dispose of any extant windows and restore any saved environment * state. */ public void terminate() { // Allow the context to do specialized cleanup if (currentContext != null) { currentContext.terminate(); } if (helper != null) { Log.debug("restoring UI state"); helper.restore(); } } protected void setError(Step step, Throwable thr) { if (thr != null) errors.put(step, thr); else errors.remove(step); } public Throwable getError(Step step) { return (Throwable)errors.get(step); } public void addStepListener(StepListener sl) { synchronized(listeners) { listeners.add(sl); } } public void removeStepListener(StepListener sl) { synchronized(listeners) { listeners.remove(sl); } } /** If this is used to propagate a failure/error, be sure to invoke * setError on the step first. */ protected void fireStepEvent(StepEvent event) { Iterator iter; synchronized(listeners) { iter = ((ArrayList)listeners.clone()).iterator(); } while (iter.hasNext()) { StepListener sl = (StepListener)iter.next(); sl.stateChanged(event); } } private void fireStepEvent(Step step, String type, int val, Throwable throwable) { synchronized(listeners) { if (listeners.size() != 0) { StepEvent event = new StepEvent(step, type, val, throwable); fireStepEvent(event); } } } protected void fireStepStart(Step step) { fireStepEvent(step, StepEvent.STEP_START, 0, null); } protected void fireStepProgress(Step step, int val) { fireStepEvent(step, StepEvent.STEP_PROGRESS, val, null); } protected void fireStepEnd(Step step) { fireStepEvent(step, StepEvent.STEP_END, 0, null); } protected void fireStepFailure(Step step, Throwable afe) { setError(step, afe); fireStepEvent(step, StepEvent.STEP_FAILURE, 0, afe); } protected void fireStepError(Step step, Throwable thr) { setError(step, thr); fireStepEvent(step, StepEvent.STEP_ERROR, 0, thr); } private class LaunchListener implements Launch.ThreadedLaunchListener { public void stepFailure(Launch step, AssertionFailedError afe) { fireStepFailure(step, afe); if (stopOnFailure) stop(terminateOnError); } public void stepError(Launch step, Throwable thr) { fireStepError(step, thr); if (stopOnError) stop(terminateOnError); } } protected class ExitHandler extends NoExitSecurityManager { public void checkRead(String file) { // avoid annoying drive a: bug on w32 VM } protected void exitCalled(int status) { Log.debug("Terminating from security manager"); terminate(); } } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/Terminate.java
package abbot.script; import java.util.Map; import abbot.i18n.Strings; /** Placeholder step to indicate to a script that it should terminate. Doesn't actually do anything itself. */ public class Terminate extends Step { private static final String USAGE = "<terminate/>"; public Terminate(Resolver resolver, Map attributes) { super(resolver, attributes); } public Terminate(Resolver resolver, String description) { super(resolver, description); } public void runStep() { // does nothing } public String getDefaultDescription() { return Strings.get("terminate.desc"); } public String getUsage() { return USAGE; } public String getXMLTag() { return TAG_TERMINATE; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/UIContext.java
package abbot.script; import abbot.finder.Hierarchy; /** Provides generic support to set up and tear down a UI context or * fixture. */ public interface UIContext { /** @return A {@link ClassLoader} providing access to classes in this * context. */ ClassLoader getContextClassLoader(); /** Launch this context. If any <code>UIContext</code> is extant, * this <code>UIContext</code> should terminate it before launching. * If this context is already launched, this method * should do nothing. */ void launch(StepRunner runner) throws Throwable; /** @return Whether this <code>UIContext</code> is currently launched. */ boolean isLaunched(); /** Terminate this context. All UI components found in the * {@link Hierarchy} returned by {@link #getHierarchy()} * will be disposed. */ void terminate(); /** @return Whether this <code>UIContext</code> is equivalent to another. */ boolean equivalent(UIContext context); /** A context must maintain the same {@link Hierarchy} for the lifetime of * the fixture. */ public Hierarchy getHierarchy(); }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/XMLConstants.java
package abbot.script; /** Attributes used by script steps and component references. Any entries here should have a corresponding entry to the <a href="doc-files/abbot.xsd">XML schema</a> file. See that file for appropriate XML usage. */ public interface XMLConstants { /** Primary document tag for a test script. */ String TAG_AWTTESTSCRIPT = "AWTTestScript"; String TAG_LAUNCH = "launch"; /** @deprecated */ String TAG_DELEGATE = "delegate"; String TAG_CLASSPATH = "classpath"; String TAG_THREADED = "threaded"; String TAG_APPLETVIEWER = "appletviewer"; String TAG_CODE = "code"; String TAG_CODEBASE = "codebase"; String TAG_ARCHIVE = "archive"; String TAG_TERMINATE = "terminate"; String TAG_COMPONENT = "component"; String TAG_ID = "id"; String TAG_NAME = "name"; String TAG_WEIGHTED = "weighted"; String TAG_WINDOW = "window"; /** Title of a Frame, Dialog or JInternalFrame. Any other use is deprecated (i.e. Title of window ancestor). */ String TAG_TITLE = "title"; String TAG_BORDER_TITLE = "borderTitle"; String TAG_ROOT = "root"; String TAG_PARENT = "parent"; String TAG_INDEX = "index"; String TAG_CLASS = "class"; String TAG_TAG = "tag"; String TAG_LABEL = "label"; String TAG_TEXT = "text"; String TAG_ICON = "icon"; String TAG_INVOKER = "invoker"; String TAG_HORDER = "hOrder"; String TAG_VORDER = "vOrder"; String TAG_PARAMS = "params"; String TAG_DOCBASE = "docBase"; String TAG_EVENT = "event"; String TAG_SEQUENCE = "sequence"; String TAG_TYPE = "type"; String TAG_KIND = "kind"; String TAG_X = "x"; String TAG_Y = "y"; String TAG_WIDTH = "width"; String TAG_HEIGHT = "height"; String TAG_MODIFIERS = "modifiers"; String TAG_COUNT = "count"; String TAG_TRIGGER = "trigger"; String TAG_KEYCODE = "keyCode"; String TAG_KEYCHAR = "keyChar"; String TAG_ACTION = "action"; String TAG_ASSERT = "assert"; String TAG_CALL = "call"; String TAG_SAMPLE = "sample"; String TAG_PROPERTY = "property"; String TAG_FIXTURE = "fixture"; String TAG_SCRIPT = "script"; String TAG_FILENAME = "filename"; String TAG_FORKED = "forked"; String TAG_SLOW = "slow"; String TAG_AWT = "awt"; String TAG_VMARGS = "vmargs"; String TAG_WAIT = "wait"; String TAG_EXPR = "expr"; String TAG_METHOD = "method"; String TAG_ARGS = "args"; String TAG_VALUE = "value"; String TAG_DESC = "desc"; String TAG_INVERT = "invert"; String TAG_TIMEOUT = "timeout"; String TAG_POLL_INTERVAL = "pollInterval"; String TAG_STOP_ON_FAILURE = "stopOnFailure"; String TAG_STOP_ON_ERROR = "stopOnError"; // this is not actually used as a tag per se String TAG_COMMENT = "comment"; }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/script/XMLifiable.java
package abbot.script; import org.jdom.Element; public interface XMLifiable { /** Provide an XML representation of the object. */ Element toXML(); /** Provide an editable string representation of the object. Usually will be a String form of the XML, but may be something simpler if it doesn't make sense to provide the full XML. */ String toEditableString(); }
0
java-sources/abbot/costello/1.4.0/abbot/script
java-sources/abbot/costello/1.4.0/abbot/script/parsers/ColorParser.java
package abbot.script.parsers; import java.awt.Color; /** Convert a {@link String} into a {@link Color}. */ public class ColorParser implements Parser { public ColorParser() { } public Object parse(String input) throws IllegalArgumentException { // NOTE: may want to provide additional parsing, e.g. // #00CC00 // R:G:B // Color.toString (although this is not guaranteed to be consistent) // or some other format Color c = Color.getColor(input); if (c != null) return c; throw new IllegalArgumentException("Can't convert '" + input + "' to java.awt.Color"); } }
0
java-sources/abbot/costello/1.4.0/abbot/script
java-sources/abbot/costello/1.4.0/abbot/script/parsers/FileParser.java
package abbot.script.parsers; import java.io.File; /** Convert a {@link String} into a {@link java.io.File}. May optionally * provide a file prefix indicating a root directory for relative paths. */ public class FileParser implements Parser { public FileParser() { } public Object parse(String input) throws IllegalArgumentException { File file = new File(input); if (!file.isAbsolute()) { file = new File(relativeTo() + File.separator + input); } return file; } public String relativeTo() { return ""; } }
0
java-sources/abbot/costello/1.4.0/abbot/script
java-sources/abbot/costello/1.4.0/abbot/script/parsers/Parser.java
package abbot.script.parsers; /** This interface provides a method for converting a {@link String} into some * destination class type. This interface was designed as an extensible * method of converting {@link String}s into arbitrary target classes when * parsing scripted arguments to methods. When a script is run and a method is * resolved, the {@link String} arguments are converted to the classes * required for the method invocation. Built-in conversions are provided for * {@link abbot.script.ComponentReference}s and all the basic types, including * arrays.<p> * @see ColorParser * @see FileParser * @see TreePathParser */ public interface Parser { Object parse(String string) throws IllegalArgumentException; }
0
java-sources/abbot/costello/1.4.0/abbot/script
java-sources/abbot/costello/1.4.0/abbot/script/parsers/TreePathParser.java
package abbot.script.parsers; import javax.swing.tree.TreePath; import abbot.i18n.Strings; import abbot.script.ArgumentParser; /** Convert a {@link String} into a {@link javax.swing.tree.TreePath}. */ public class TreePathParser implements Parser { /** The string representation of a TreePath is what is usually generated by its toString method, e.g. <p> [root, parent, child] <p> Nodes which contain a comma need to have that comma preceded by a backslash to avoid it being interpreted as two separate nodes.<p> NOTE: The returned TreePath is only a TreePath constructed of Strings; it requires further manipulation to be turned into a true TreePath as it relates to a given Tree. */ public Object parse(String input) throws IllegalArgumentException { if (!(input.startsWith("[") && input.endsWith("]"))) { String msg = Strings.get("parser.treepath.bad_format", new Object[] { input }); throw new IllegalArgumentException(msg); } input = input.substring(1, input.length()-1); // Use our existing utility for parsing a comma-separated list String[] nodeNames = ArgumentParser.parseArgumentList(input); // Strip off leading space, if there is one for (int i=0;i < nodeNames.length;i++) { if (nodeNames[i] != null && nodeNames[i].startsWith(" ")) nodeNames[i] = nodeNames[i].substring(1); } TreePath path = new TreePath(nodeNames); return path; } }
0
java-sources/abbot/costello/1.4.0/abbot
java-sources/abbot/costello/1.4.0/abbot/tester/MapGenerator.java
package abbot.tester; import java.lang.reflect.Field; import java.awt.*; import java.awt.Robot; import java.awt.event.*; import java.util.*; import java.io.*; import javax.swing.*; import javax.swing.text.*; import abbot.Log; import abbot.Platform; import abbot.editor.OSXAdapter; /** Provides read/write of locale-specific mappings for virtual keycode-based KeyStrokes to characters and vice versa. <p> If your locale's map is not present in src/abbot/tester/keymaps, please run this class's {@link #main(String[])} method to generate them and <a href="http://sourceforge.net/tracker/?group_id=50939&atid=461492">submit them to the project</a> for inclusion. <p> Variations among locales and OSes are expected; if a map for a locale+OS is not found, the system falls back to the locale map. */ public class MapGenerator extends KeyStrokeMap { private static boolean setModifiers(Robot robot, int mask, boolean press) { try { if ((mask & KeyEvent.SHIFT_MASK) != 0) { if(press) robot.keyPress(KeyEvent.VK_SHIFT); else robot.keyRelease(KeyEvent.VK_SHIFT); } if ((mask & KeyEvent.CTRL_MASK) != 0) { if(press) robot.keyPress(KeyEvent.VK_CONTROL); else robot.keyRelease(KeyEvent.VK_CONTROL); } if ((mask & KeyEvent.ALT_MASK) != 0) { if (press) robot.keyPress(KeyEvent.VK_ALT); else robot.keyRelease(KeyEvent.VK_ALT); } if ((mask & KeyEvent.META_MASK) != 0) { if (press) robot.keyPress(KeyEvent.VK_META); else robot.keyRelease(KeyEvent.VK_META); } if ((mask & KeyEvent.ALT_GRAPH_MASK) != 0) { if (press) robot.keyPress(KeyEvent.VK_ALT_GRAPH); else robot.keyRelease(KeyEvent.VK_ALT_GRAPH); } return true; } catch(IllegalArgumentException e) { // ignore these } catch(Exception e) { Log.warn(e); } return false; } private static class KeyWatcher extends KeyAdapter { public char keyChar; public boolean keyTyped; public boolean keyPressed; public String codeName; public void keyPressed(KeyEvent e) { keyPressed = true; // For debug only; activating this stuff tends to interfere with // key capture /* Document d = ((JTextComponent)e.getComponent()).getDocument(); try { String insert = codeName != null ? insert = "\n" + codeName + "=" : ""; d.insertString(d.getLength(), insert, null); } catch(BadLocationException ble) { } */ } public void keyTyped(KeyEvent e) { keyChar = e.getKeyChar(); keyTyped = true; // For debug only; activating this stuff tends to interfere with // key capture /* Document d = ((JTextComponent)e.getComponent()).getDocument(); char[] data = { keyChar }; try { String insert = new String(data) + " (" + String.valueOf((int)keyChar) + ")"; d.insertString(d.getLength(), insert, null); } catch(BadLocationException ble) { } */ codeName=null; } } private static KeyWatcher watcher = null; private static final int UNTYPED = -1; private static final int UNDEFINED = -2; private static final int ILLEGAL = -3; private static final int SYSTEM = -4; private static final int ERROR = -5; private static int generateKey(final Window w, final Component c, final Robot robot, Point p, String name, int code, final boolean refocus) { if (watcher == null) { watcher = new KeyWatcher(); c.addKeyListener(watcher); } try { robot.waitForIdle(); if (refocus) { SwingUtilities.invokeAndWait(new Runnable() { public void run() { w.setVisible(true); w.toFront(); c.requestFocus(); if (Platform.isWindows() || Platform.isMacintosh()) { robot.mouseMove(w.getX() + w.getWidth()/2, w.getY() + w.getHeight()/2); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); } } }); } robot.mouseMove(p.x, p.y); robot.waitForIdle(); try { watcher.codeName = name; watcher.keyTyped = watcher.keyPressed = false; robot.keyPress(code); robot.keyRelease(code); long start = System.currentTimeMillis(); while(!watcher.keyPressed || !watcher.keyTyped) { if (System.currentTimeMillis() - start > 500) break; robot.waitForIdle(); } if(!watcher.keyPressed) { // alt-tab, alt-f4 and the like which get eaten by the OS return SYSTEM; } else if(!watcher.keyTyped) // keys which result in KEY_TYPED event return UNTYPED; else if (watcher.keyChar == KeyEvent.CHAR_UNDEFINED) // usually the same as UNTYPED, but just in case return UNDEFINED; else return watcher.keyChar; } catch(IllegalArgumentException e) { // not supported on this system return ILLEGAL; } } catch(Exception e) { // usually a core library bug Log.warn(e); return ERROR; } } private static boolean isFunctionKey(String name) { if (name.startsWith("VK_F")) { try { Integer.parseInt(name.substring(4)); return true; } catch(NumberFormatException e) { } } return false; } private static final Comparator FIELD_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { try { String n1 = ((Field)o1).getName(); String n2 = ((Field)o2).getName(); return n1.compareTo(n2); } catch(Exception e) { return 0; } } }; // From a VK_ code + modifiers, produce a simluated KEY_TYPED // From a keychar, determine the necessary VK_ code + modifiers private static void generateKeyStrokeMap(Window w, JTextComponent c) { // TODO: invoke modifiers for multi-byte input sequences? // Skip known modifiers and locking keys Collection skip = Arrays.asList(new String[] { "VK_UNDEFINED", // modifiers "VK_SHIFT", "VK_CONTROL", "VK_META", "VK_ALT", "VK_ALT_GRAPH", // special-function keys "VK_CAPS_LOCK", "VK_NUM_LOCK", "VK_SCROLL_LOCK", // Misc other function keys "VK_KANA", "VK_KANJI", "VK_ALPHANUMERIC", "VK_KATAKANA", "VK_HIRAGANA", "VK_FULL_WIDTH", "VK_HALF_WIDTH", "VK_ROMAN_CHARACTERS", "VK_ALL_CANDIDATES", "VK_PREVIOUS_CANDIDATE", "VK_CODE_INPUT", "VK_JAPANESE_KATAKANA", "VK_JAPANESE_HIRAGANA", "VK_JAPANESE_ROMAN", "VK_KANA_LOCK", "VK_INPUT_METHOD_ON_OFF", }); System.out.println("Generating keystroke map"); try { Robot robot = new Robot(); // Make sure the window is ready for input if (!RobotVerifier.verify(robot)) { System.err.println("Robot non-functional, can't generate map"); System.exit(1); } robot.delay(500); Field[] fields = KeyEvent.class.getDeclaredFields(); Set codes = new TreeSet(FIELD_COMPARATOR); for(int i=0;i < fields.length;i++) { String name = fields[i].getName(); if(name.startsWith("VK_") && !skip.contains(name) && !name.startsWith("VK_DEAD_") && !isFunctionKey(name)) { codes.add(fields[i]); } } System.out.println("Total VK_ fields read: " + codes.size()); Point p = c.getLocationOnScreen(); p.x += c.getWidth()/2; p.y += c.getHeight()/2; // for now, only do reasonable modifiers; add more if the need // arises int[] modifierCombos = { 0, KeyEvent.SHIFT_MASK, KeyEvent.CTRL_MASK, KeyEvent.META_MASK, KeyEvent.ALT_MASK, KeyEvent.ALT_GRAPH_MASK, }; String[] MODIFIERS = { "none", "shift", "control", "meta", "alt", "alt graph", }; // These modifiers might trigger window manager functions int needRefocus = KeyEvent.META_MASK|KeyEvent.ALT_MASK; Map[] maps = new Map[modifierCombos.length]; for(int m=0;m < modifierCombos.length;m++) { Map map = new TreeMap(FIELD_COMPARATOR); int mask = modifierCombos[m]; if(!setModifiers(robot, mask, true)) { System.out.println("Modifier " + MODIFIERS[m] + " is not currently valid"); continue; } System.out.println("Generating keys with mask=" + MODIFIERS[m]); Iterator iter = codes.iterator(); // Always try to fix the focus; who knows what keys have // been mapped to the WM boolean focus = true; while(iter.hasNext()) { Field f = (Field)iter.next(); int code = f.getInt(null); //System.out.println(f.getName() + "."); System.out.print("."); int value = generateKey(w, c, robot, p, f.getName(), code, focus || (mask & needRefocus) != 0); map.put(f, new Integer(value)); } setModifiers(robot, modifierCombos[m], false); System.out.println(""); maps[m] = map; } Properties props = new Properties(); Iterator iter = maps[0].keySet().iterator(); while (iter.hasNext()) { Field key = (Field)iter.next(); for(int m=0;m < modifierCombos.length;m++) { Map map = maps[m]; if (map == null) continue; String name = key.getName().substring(3); name += "." + Integer.toHexString(modifierCombos[m]); Integer v = (Integer)map.get(key); int value = v.intValue(); String hex; switch(value) { case UNTYPED: hex = "untyped"; break; case UNDEFINED: hex = "undefined"; break; case ILLEGAL: hex = "illegal"; break; case SYSTEM: hex = "system"; break; case ERROR: hex = "error"; break; default: hex = Integer.toHexString(value); break; } props.setProperty(name, hex); } } String[] names = getMapNames(); String[] desc = getMapDescriptions(); for (int i=0;i < names.length;i++) { String fn = getFilename(names[i]); System.out.println("Saving " + names[i] + " as " + fn); FileOutputStream fos = new FileOutputStream(fn); props.store(fos, "Key mappings for " + desc[i]); } } catch(AWTException e) { System.err.println("Robot not available, can't generate map"); } catch(Exception e) { System.err.println("Error: " + e); } } /** Run this to generate the full set of mappings for a given locale. */ public static void main(String[] args) { String language = System.getProperty("abbot.locale.language"); if (language != null) { String country = System.getProperty("abbot.locale.country", ""); String variant = System.getProperty("abbot.locale.variant", ""); Locale.setDefault(new Locale(language, country, variant)); } final JFrame frame = new JFrame("KeyStroke mapping generator"); final JTextArea text = new JTextArea(); // Remove all action mappings; we want to receive *all* keystrokes text.setInputMap(JTextArea.WHEN_FOCUSED, new InputMap()); frame.getContentPane().add(new JScrollPane(text)); frame.setLocation(100, 100); frame.setSize(250, 90); frame.addWindowListener(new WindowAdapter() { public void windowClosing(final WindowEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { e.getWindow().setVisible(true); } }); } }); frame.setVisible(true); if (Platform.isOSX()) { // avoid exit on cmd-Q OSXAdapter.register(frame, new AbstractAction("quit") { public void actionPerformed(ActionEvent e) { } }, null, null); } SwingUtilities.invokeLater(new Runnable() { public void run() { new Thread("keymap generator") { public void run() { generateKeyStrokeMap(frame, text); System.exit(0); } }.start(); } }); } }
0
java-sources/abbot/costello/1.4.0/junit/extensions
java-sources/abbot/costello/1.4.0/junit/extensions/abbot/ResolverFixture.java
package junit.extensions.abbot; import java.awt.Window; import java.util.Iterator; import junit.framework.TestCase; import abbot.Log; import abbot.finder.BasicFinder; import abbot.script.Resolver; import abbot.script.Script; /** Simple wrapper for testing objects which require a Resolver. */ public abstract class ResolverFixture extends ComponentTestFixture { private Resolver resolver; /** Obtain a consistent resolver. */ protected Resolver getResolver() { return resolver; } /** Fixture setup is performed here, to avoid problems should a derived class define its own setUp and neglect to invoke the superclass method. */ protected void fixtureSetUp() throws Throwable { super.fixtureSetUp(); // FIXME kind of a hack, but Script is the only implementation of // Resolver we've got at the moment. resolver = new Script(getHierarchy()); } /** Fixture teardown is performed here, to avoid problems should a derived class define its own tearDown and neglect to invoke the superclass method. */ protected void fixtureTearDown() throws Throwable { super.fixtureTearDown(); resolver = null; } /** Construct a test case with the given name. */ public ResolverFixture(String name) { super(name); } /** Default Constructor. The name will be automatically set from the selected test method. */ public ResolverFixture() { } }
0
java-sources/abbot/costello/1.4.0/junit/extensions
java-sources/abbot/costello/1.4.0/junit/extensions/abbot/ScriptFixture.java
package junit.extensions.abbot; import junit.framework.TestCase; import abbot.Log; import abbot.script.*; import abbot.util.AWTFixtureHelper; import abbot.finder.*; /** Simple wrapper for a test script to run under JUnit. If the script * does not contain a launch step, the hierarchy used will include existing * components. No automatic cleanup of components is performed, since it is * assumed that a Terminate step within the script will trigger that operation * if it is required.<p> */ public class ScriptFixture extends TestCase { private static AWTFixtureHelper awtFixtureHelper = null; private static final Hierarchy DUMMY_HIERARCHY = new AWTHierarchy(); private StepRunner runner; /** Construct a test case with the given name, which <i>must</i> be the * filename of the script to run. */ public ScriptFixture(String filename) { // It is essential that the name be passed to super() unmodified, or // the JUnit GUI will consider it a different test. super(filename); } /** * Provide a non default AWTFixtureHelper, the most common * usercase of this is when you want to base in a custom TestHierarchy * for example when you don't want to ingore existing components. * <code>setAWTFixtureHelper(new AWTFixtureHelper(new TestHierarchy(false)));</code> * */ public void setAWTFixtureHelper(AWTFixtureHelper helper) { awtFixtureHelper = helper; } /** Saves the current UI state for restoration when the fixture (if any) is terminated. Also sets up a {@link TestHierarchy} for the duration of the test. */ protected void setUp() throws Exception { if (awtFixtureHelper == null) { awtFixtureHelper = new AWTFixtureHelper(); } runner = new StepRunner(awtFixtureHelper); // Support for deprecated ComponentTester.assertFrameShowing usage // only. Eventually this will go away. AWTHierarchy.setDefault(runner.getHierarchy()); } protected void tearDown() throws Exception { AWTHierarchy.setDefault(null); runner = null; } /** Override the default TestCase runTest method to invoke the script. The {@link Script} is created and a default {@link StepRunner} is used to run it. @see junit.framework.TestCase#runTest */ protected void runTest() throws Throwable { Script script = new Script(getName(), DUMMY_HIERARCHY); Log.log("Running " + script + " with " + getClass()); try { runner.run(script); } finally { Log.log(script.toString() + " finished"); } } /** Assumes each argument is an Abbot script. Runs each one. */ public static void main(String[] args) { ScriptTestSuite.main(args); } }
0
java-sources/abbot/costello/1.4.0/junit/extensions
java-sources/abbot/costello/1.4.0/junit/extensions/abbot/ScriptTestCollector.java
package junit.extensions.abbot; import java.io.*; import java.util.*; import java.util.zip.*; import java.net.URLClassLoader; import java.net.URL; import java.lang.reflect.*; import junit.framework.*; import junit.runner.*; import abbot.Platform; import abbot.util.PathClassLoader; /** Collects all available classes derived from ScriptTestCase in the current * classpath. */ public class ScriptTestCollector { private ClassLoader loader; private static final String PACKAGE = "junit.extensions.abbot."; public ScriptTestCollector() { this(null); } public ScriptTestCollector(ClassLoader loader) { if (loader == null) { String path = System.getProperty("java.class.path"); loader = new PathClassLoader(path); } this.loader = loader; } private String convertURLsToClasspath(URL[] urls) { String PS = System.getProperty("path.separator"); String path = ""; for (int i=0;i < urls.length;i++) { if (!"".equals(path)) path += PS; URL url = urls[i]; if (url.getProtocol().equals("file")) { String file = url.getFile(); if (Platform.isWindows() && file.startsWith("/")) file = file.substring(1); path += file; } } return path; } /** Override to use something other than java.class.path. */ public Enumeration collectTests() { String jcp = System.getProperty("java.class.path"); String classPath = loader instanceof URLClassLoader ? convertURLsToClasspath(((URLClassLoader)loader).getURLs()) : jcp; Hashtable hash = collectFilesInPath(classPath); if (loader instanceof URLClassLoader) hash.putAll(collectFilesInPath(jcp)); return hash.elements(); } private ArrayList splitClassPath(String classPath) { ArrayList result= new ArrayList(); String separator= System.getProperty("path.separator"); StringTokenizer tokenizer= new StringTokenizer(classPath, separator); while (tokenizer.hasMoreTokens()) result.add(tokenizer.nextToken()); return result; } /** Collect files in zip archives as well as raw class files. */ public Hashtable collectFilesInPath(String classPath) { Hashtable hash = new Hashtable(); //super.collectFilesInPath(classPath); Collection paths = splitClassPath(classPath); Iterator iter = paths.iterator(); while (iter.hasNext()) { String el = (String)iter.next(); if (el.endsWith(".zip") || el.endsWith(".jar")) { hash.putAll(scanArchive(el)); } } return hash; } protected Map scanArchive(String name) { Map map = new HashMap(); try { ZipFile zip = new ZipFile(name); Enumeration en = zip.entries(); while (en.hasMoreElements()) { ZipEntry entry = (ZipEntry)en.nextElement(); if (!entry.isDirectory()) { String filename = entry.getName(); if (isTestClass(filename)) { String cname = classNameFromFile(filename); map.put(cname, cname); } } } } catch(IOException e) { } return map; } protected boolean isTestClass(String classFileName) { boolean isTest = classFileName.endsWith(".class") && classFileName.indexOf("Test") > 0 && classFileName.indexOf('$') == -1; if (isTest) { String className = classNameFromFile(classFileName); try { Class testClass = Class.forName(className, true, loader); Class scriptFixture = Class.forName(PACKAGE + "ScriptFixture", true, loader); Class scriptSuite = Class.forName(PACKAGE + "ScriptTestSuite", true, loader); return (scriptFixture.isAssignableFrom(testClass) || scriptSuite.isAssignableFrom(testClass)) && Modifier.isPublic(testClass.getModifiers()) && TestSuite.getTestConstructor(testClass) != null; } catch(ClassNotFoundException e) { } catch(NoClassDefFoundError e) { } catch(NoSuchMethodException e) { } } return false; } protected String classNameFromFile(String classFileName) { String name = classFileName; // super.classNameFromFile(classFileName); String noclass; if (name.endsWith(".class")) { noclass = name.substring(0,name.length() - ".class".length()); } else { noclass = name; } String noslashes = noclass.replace('/', '.'); return noslashes; } }
0
java-sources/abbot/costello/1.4.0/junit/extensions
java-sources/abbot/costello/1.4.0/junit/extensions/abbot/ScriptTestSuite.java
package junit.extensions.abbot; import java.io.File; import java.lang.reflect.Constructor; import java.util.*; import junit.framework.*; import abbot.Log; import abbot.script.Script; //import junit.ui.TestRunner; //import junit.swingui; /** Similar to TestSuite, except that it auto-generates a suite based on test * scripts matching certain criteria. * <p> * By default, generate a suite of all scripts found in a given directory for * which the accept method returns true. Note that there is no guarantee of * the order of the scripts. * <p> * The ScriptTestSuite constructors which require a class argument provide a * means for using custom fixtures derived from * <a href="ScriptFixture.html">ScriptFixture</a>. The default fixture * preserves existing environment windows (e.g. the JUnit Swing UI TestRunner) * and disposes of all windows generated by the code under test. Derived * fixtures may provide arbitrary code in their setUp/tearDown methods (such * as install/uninstall a custom security manager, set system properties, * etc), the same as you would do in any other derivation of * junit.framework.TestCase. * <p> * <h3>Example 1</h3> * Following is a ScriptTestSuite which will aggregate all tests in the * directory "src/example", whose filenames begin with "MyCode-" and end with * ".xml":<br> * <pre><code> * public class MyCodeTest extends ScriptFixture { * public MyCodeTest(String name) { super(name); } * public static Test suite() { * return new ScriptTestSuite(MyCodeTest.class, "src/example") { * public boolean accept(File file) { * String name = file.getName(); * return name.startsWith("MyCode-") && name.endsWith(".xml"); * } * }; * } * } * </code></pre> */ public class ScriptTestSuite extends TestSuite { private File primaryDirectory; /** Constructs a suite of tests from all the scripts found in the directory specified by the system property "abbot.testsuite.path". The most common use for this constructor would be from an Ant 'junit' task, where the system property is defined for a given run. The suite will recurse directories if "abbot.testsuite.path.recurse" is set to true. */ public ScriptTestSuite() { this(ScriptFixture.class, System.getProperty("abbot.testsuite.path", System.getProperty("user.dir")), Boolean.getBoolean("abbot.testsuite.path.recurse")); } /** Constructs a suite of tests from all the scripts found in the current * directory. Does not recurse to subdirectories. The Class argument * must be a subclass of junit.extensions.abbot.ScriptFixture. */ public ScriptTestSuite(Class fixtureClass) { this(fixtureClass, System.getProperty("user.dir"), false); } /** Constructs a suite of tests from all the scripts found in the given * directory. Does not recurse to subdirectories. The Class argument * must be a subclass of junit.extensions.abbot.ScriptFixture. */ public ScriptTestSuite(Class fixtureClass, String dirname) { this(fixtureClass, dirname, false); } /** Constructs an ScriptTestSuite from all the scripts in the given * directory, recursing if recurse is true. The Class argument * must be a class derived from junit.extensions.abbot.ScriptFixture. */ public ScriptTestSuite(Class fixtureClass, String dirname, boolean recurse) { this(fixtureClass, findFilenames(dirname, recurse)); primaryDirectory = new File(dirname); if (!primaryDirectory.exists() || !primaryDirectory.isDirectory()) { String msg = "Directory '" + dirname + "' did not exist" + " when scanning for test scripts"; addTest(warningTest(msg)); } } /** Constructs a suite of tests for each script given in the argument * list. */ public ScriptTestSuite(String[] filenames) { this(ScriptFixture.class, filenames); } /** Constructs a suite of tests for each script given in the argument * list, using the given class derived from ScriptFixture to wrap each * script. */ public ScriptTestSuite(Class fixtureClass, String[] filenames) { super(fixtureClass.getName()); primaryDirectory = new File(System.getProperty("user.dir")); Log.debug("Loading " + fixtureClass + ", with " + filenames.length + " files"); for (int i=0;i < filenames.length;i++) { File file = new File(filenames[i]); // Filter for desired files only if (!accept(file)) continue; try { Log.debug("Attempting to create " + fixtureClass); Constructor ctor = fixtureClass.getConstructor(new Class[] { String.class }); Test test = (Test)ctor.newInstance(new Object[] { file.getAbsolutePath() }); Log.debug("Created an instance of " + fixtureClass); addTest(test); } catch(Throwable thr) { Log.warn(thr); addTest(warningTest("Could not construct an instance of " + fixtureClass)); break; } } if (testCount() == 0) { addTest(warningTest("No scripts found")); } } public File getDirectory() { return primaryDirectory; } /** Return whether to accept the given file. The default implementation * omits common backup files. */ public boolean accept(File file) { String name = file.getName(); return !name.startsWith(".#") && !name.endsWith("~") && !name.endsWith(".bak"); } /** * Returns a test which will fail and log a warning message. */ private Test warningTest(final String message) { return new TestCase("warning") { protected void runTest() { fail(message); } }; } /** Add all test scripts in the given directory, optionally recursing to * subdirectories. Returns a list of absolute paths. */ protected static List findTestScripts(File dir, List files, boolean recurse) { File[] flist = dir.listFiles(); for (int i=0;flist != null && i < flist.length;i++) { //Log.debug("Examining " + flist[i]); if (flist[i].isDirectory()) { if (recurse) findTestScripts(flist[i], files, recurse); } else if (Script.isScript(flist[i])) { String filename = flist[i].getAbsolutePath(); if (!files.contains(filename)) { Log.debug("Adding " + filename); files.add(filename); } } } return files; } /** Scan for test scripts and return an array of filenames for all scripts found. */ static String[] findFilenames(String dirname, boolean recurse) { File dir = new File(dirname); ArrayList list = new ArrayList(); if (dir.exists() && dir.isDirectory()) { findTestScripts(dir, list, recurse); } return (String[])list.toArray(new String[list.size()]); } /** Run all scripts on the command line as a single suite. */ public static void main(String[] args) { args = Log.init(args); ScriptTestSuite suite = new ScriptTestSuite(args); junit.textui.TestRunner runner = new junit.textui.TestRunner(); try { TestResult r = runner.doRun(suite, false); if (!r.wasSuccessful()) System.exit(-1); System.exit(0); } catch(Throwable thr) { System.err.println(thr.getMessage()); System.exit(-2); } } }
0
java-sources/academy/alex/custommatcher/1.0/academy
java-sources/academy/alex/custommatcher/1.0/academy/alex/CustomMatcher.java
package academy.alex; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; public abstract class CustomMatcher extends Util{ public static class Type extends TypeSafeDiagnosingMatcher<String> { public void describeTo(Description description) {description.appendText("Credit Card type ").appendText(" must be valid");} protected boolean matchesSafely(String cc_type_number, Description description) { String type = cc_type_number.split(":")[0]; String number = cc_type_number.split(":")[1].replaceAll("\\s", "").replaceAll("-", ""); if (number.startsWith("4") && (number.length() == 13 || number.length() == 16) && type.equals("VISA")) {return true;} else if ((number.startsWith("51") || number.startsWith("52") || number.startsWith("53") || number.startsWith("54") || number.startsWith("55")) && number.length() == 16 && type.equals("MasterCard")) {return true;} else if ((number.startsWith("6011") || number.startsWith("62") || number.startsWith("64") || number.startsWith("65")) && number.length() == 16 && type.equals("Discover")) {return true;} else if ((number.startsWith("34") || number.startsWith("37")) && number.length() == 15 && type.equals("American Express")) {return true;} else {return false;} } } public static class Luhn extends TypeSafeDiagnosingMatcher<String> { public void describeTo(Description description) {description.appendText("Credit Card number ").appendText(" must be valid");} protected boolean matchesSafely(String cc_number, Description description) { String number = new String(cc_number.replaceAll("\\s", "").replaceAll("-", "")); int sum = 0; boolean swap = false; for (int i = number.length() - 1; i >= 0; i--) { int digit = Integer.parseInt(number.substring(i, i + 1)); if (swap) {digit *= 2;if (digit > 9) {digit -= 9;}} sum += digit;swap = !swap;}; description.appendValue(cc_number).appendText(" is not valid"); return (sum % 10 == 0); } } public static class Expiration extends TypeSafeDiagnosingMatcher<String> { public void describeTo(Description description) {description.appendText("Credit Card expiration ").appendText(" must be valid");} protected boolean matchesSafely(String cc_exp, Description description) { int exp = Integer.parseInt(cc_exp.substring(3, 5) + cc_exp.substring(0, 2)); // 02/18 => 1802 description.appendValue(cc_exp).appendText(" is already expired"); return today() <= exp; } } public static class CVV extends TypeSafeDiagnosingMatcher<String> { public void describeTo(Description description) {description.appendText("Credit Card CVV ").appendText(" must be valid");} protected boolean matchesSafely(String cc_type_cvv, Description description) { String type = cc_type_cvv.split(":")[0]; String cvv = cc_type_cvv.split(":")[1]; if (type.equals("American Express")) {return cvv.matches("^(\\d{4})$");} else {return cvv.matches("^(\\d{3})$");} } } public static Matcher<String> validType() {return new Type();} public static Matcher<String> validNumber() {return new Luhn();} public static Matcher<String> validExpiration() {return new Expiration();} public static Matcher<String> validCVV() {return new CVV();} }
0
java-sources/academy/alex/custommatcher/1.0/academy
java-sources/academy/alex/custommatcher/1.0/academy/alex/Util.java
package academy.alex; import java.sql.Timestamp; public abstract class Util { protected static int today() { Timestamp ts = new Timestamp(System.currentTimeMillis()); int today = Integer.parseInt((String.valueOf(ts.toString().split("-")[0].substring(2, 4)) + ts.toString().split("-")[1])); return today; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/EjabberdXMLRPCClient.java
package ae.teletronics.ejabberd; import ae.teletronics.ejabberd.entity.response.BooleanXmppResponse; import ae.teletronics.ejabberd.entity.response.GetRosterResponse; import ae.teletronics.ejabberd.entity.response.GetUserPairListResponse; import ae.teletronics.ejabberd.entity.response.GetUsersResponse; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutorService; /** * Created by kristian on 4/7/16. */ public class EjabberdXMLRPCClient implements IEjabberdXMLRPCClient { ExecutorService executorService; XmlRpcClient client = new XmlRpcClient(); ResponseParser responseParser = new ResponseParser(); public EjabberdXMLRPCClient(ExecutorService executorService, XmlRpcClient client) { this.executorService = executorService; this.client = client; } @Override public CompletableFuture<BooleanXmppResponse> createUser(String username, String host, String password){ Map params = new HashMap(); params.put("user", username); params.put("host", host); params.put("password", password); return CompletableFuture.supplyAsync(() -> { try { final HashMap createUserXMLRPCResponse = executeXmlRpc("register", Arrays.asList(params)); return responseParser.parseBooleanResponse(createUserXMLRPCResponse); } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<BooleanXmppResponse> deleteUser(String username, String host){ Map params = new HashMap(); params.put("user", username); params.put("host", host); return CompletableFuture.supplyAsync(() -> { try { final HashMap deleteUserXMLRPCResponse = executeXmlRpc("unregister", Arrays.asList(params)); return responseParser.parseBooleanResponse(deleteUserXMLRPCResponse); } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<GetUsersResponse> getUsers(String host){ Map params = new HashMap(); params.put("host", host); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("registered_users", Arrays.asList(params)); final GetUsersResponse getUsersResponse = responseParser.parseGetUserResponse(response); return getUsersResponse; } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<BooleanXmppResponse> addRosterItem(String localuser, String localserver, String user, String server, String nick, String group, String subs){ Map params = new HashMap(); params.put("localuser", localuser); params.put("localserver", localserver); params.put("user", user); params.put("server", server); params.put("nick", nick); params.put("group", group); params.put("subs", subs); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("add_rosteritem", Arrays.asList(params)); final BooleanXmppResponse booleanXmppResponse = responseParser.parseBooleanResponse(response); return booleanXmppResponse; } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<BooleanXmppResponse> deleteRosterItem(String localuser, String localserver, String user, String server){ Map params = new HashMap(); params.put("localuser", localuser); params.put("localserver", localserver); params.put("server", server); params.put("user", user); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("delete_rosteritem", Arrays.asList(params)); return responseParser.parseBooleanResponse(response); } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<GetRosterResponse> getRoster(String user, String server){ Map struct = new HashMap(); struct.put("user", user); struct.put("server", server); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("get_roster", Arrays.asList(struct)); return responseParser.parseGetRosterResponse(response); } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<BooleanXmppResponse> sendChatMessage(String to, String from, String subject, String body) { Map struct = new HashMap(); struct.put("type", "chat"); struct.put("to", to); struct.put("from", from); struct.put("subject", subject); struct.put("body", body); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("send_message", Arrays.asList(struct)); return responseParser.parseBooleanResponse(response); } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<BooleanXmppResponse> sendStanza(String to, String from, String stanza) { Map struct = new HashMap(); struct.put("to", to); struct.put("from", from); struct.put("stanza", stanza); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("send_stanza", Arrays.asList(struct)); return responseParser.parseBooleanResponse(response); } catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } @Override public CompletableFuture<GetUserPairListResponse> processRosterItems(String action, String subs, String asks, String users, String contacts){ Map struct = new HashMap(); struct.put("action", action); struct.put("subs", subs); struct.put("asks", asks); struct.put("users", users); struct.put("contacts", contacts); return CompletableFuture.supplyAsync(() -> { try { final HashMap response = executeXmlRpc("process_rosteritems", Arrays.asList(struct)); return responseParser.parseUserPairListResponse(response); }catch (XmlRpcException e) { throw new CompletionException(e); } }, executorService); } HashMap executeXmlRpc(String command, List params) throws XmlRpcException { return (HashMap) client.execute(command, params); } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/EjabberdXMLRPCClientBuilder.java
package ae.teletronics.ejabberd; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by kristian on 4/7/16. */ public class EjabberdXMLRPCClientBuilder implements IEjabberdXMLRPCClientBuilder { ExecutorService executorService = Executors.newCachedThreadPool(); String ejabberdHostname = "localhost"; String ejabberdPort = "4560"; String ejabberdProtocol = "http"; String ejabberdPath = "/RPC2"; @Override public EjabberdXMLRPCClientBuilder setExecutorService(ExecutorService executorService){ this.executorService = executorService; return this; } @Override public EjabberdXMLRPCClientBuilder setEjabberdHostname(String ejabberdHostname){ this.ejabberdHostname = ejabberdHostname; return this; } @Override public EjabberdXMLRPCClientBuilder setEjabberdPort(String ejabberdPort){ this.ejabberdPort = ejabberdPort; return this; } @Override public EjabberdXMLRPCClientBuilder setEjabberdProtocol(String ejabberdProtocol){ this.ejabberdProtocol = ejabberdProtocol; return this; } @Override public EjabberdXMLRPCClientBuilder setEjabberdPath(String ejabberdPath){ this.ejabberdPath = ejabberdPath; return this; } @Override public IEjabberdXMLRPCClient build() throws MalformedURLException { final URL ejabberdUrl = buildUrl(); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(ejabberdUrl); XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); return new EjabberdXMLRPCClient(this.executorService, client); } URL buildUrl() throws MalformedURLException { return new URL(this.ejabberdProtocol, this.ejabberdHostname, Integer.parseInt(this.ejabberdPort), this.ejabberdPath); } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/IEjabberdXMLRPCClient.java
package ae.teletronics.ejabberd; import ae.teletronics.ejabberd.entity.response.BooleanXmppResponse; import ae.teletronics.ejabberd.entity.response.GetRosterResponse; import ae.teletronics.ejabberd.entity.response.GetUserPairListResponse; import ae.teletronics.ejabberd.entity.response.GetUsersResponse; import java.util.concurrent.CompletableFuture; /** * Created by carlos on 9/3/17. */ public interface IEjabberdXMLRPCClient { public CompletableFuture<BooleanXmppResponse> createUser(String username, String host, String password); public CompletableFuture<BooleanXmppResponse> deleteUser(String username, String host); public CompletableFuture<GetUsersResponse> getUsers(String host); public CompletableFuture<BooleanXmppResponse> addRosterItem(String localuser, String localserver, String user, String server, String nick, String group, String subs); public CompletableFuture<BooleanXmppResponse> deleteRosterItem(String localuser, String localserver, String user, String server); public CompletableFuture<GetRosterResponse> getRoster(String user, String server); public CompletableFuture<BooleanXmppResponse> sendChatMessage(String to, String from, String subject, String body); public CompletableFuture<BooleanXmppResponse> sendStanza(String to, String from, String stanza); public CompletableFuture<GetUserPairListResponse> processRosterItems(String action, String subs, String asks, String users, String contacts); }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/IEjabberdXMLRPCClientBuilder.java
package ae.teletronics.ejabberd; import java.net.MalformedURLException; import java.util.concurrent.ExecutorService; /** * Created by pcoltau on 3/13/17. */ public interface IEjabberdXMLRPCClientBuilder { IEjabberdXMLRPCClientBuilder setExecutorService(ExecutorService executorService); IEjabberdXMLRPCClientBuilder setEjabberdHostname(String ejabberdHostname); IEjabberdXMLRPCClientBuilder setEjabberdPort(String ejabberdPort); IEjabberdXMLRPCClientBuilder setEjabberdProtocol(String ejabberdProtocol); IEjabberdXMLRPCClientBuilder setEjabberdPath(String ejabberdPath); IEjabberdXMLRPCClient build() throws MalformedURLException; }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/ResponseParser.java
package ae.teletronics.ejabberd; import ae.teletronics.ejabberd.entity.RosterItem; import ae.teletronics.ejabberd.entity.User; import ae.teletronics.ejabberd.entity.UserPair; import ae.teletronics.ejabberd.entity.response.BooleanXmppResponse; import ae.teletronics.ejabberd.entity.response.GetRosterResponse; import ae.teletronics.ejabberd.entity.response.GetUserPairListResponse; import ae.teletronics.ejabberd.entity.response.GetUsersResponse; import java.util.HashMap; /** * Created by kristian on 4/7/16. */ public class ResponseParser { BooleanXmppResponse parseBooleanResponse(HashMap response) { int res = (int) response.get("res"); final BooleanXmppResponse booleanXmppResponse = new BooleanXmppResponse(res); if (!booleanXmppResponse.isSuccessFull()) { booleanXmppResponse.setError((String) response.get("text")); } return booleanXmppResponse; } public GetUsersResponse parseGetUserResponse(HashMap response) { GetUsersResponse getUsersResponse = new GetUsersResponse(); Object[] users = (Object[]) response.get("users"); for (int i = 0; i < users.length; i++) { HashMap userMap = (HashMap) users[i]; String username = (String) userMap.get("username"); getUsersResponse.getUserList().add(new User(username)); } return getUsersResponse; } public GetRosterResponse parseGetRosterResponse(HashMap response) { GetRosterResponse getRosterResponse = new GetRosterResponse(); final Object[] contacts = (Object[]) response.get("contacts"); for (Object contactObject : contacts) { if (contactObject instanceof HashMap && ((HashMap) contactObject).get("contact") instanceof Object[]) { final Object[] contact = (Object[]) ((HashMap) contactObject).get("contact"); RosterItem rosterItem = parseRosterItem(contact); getRosterResponse.getRosterItemList().add(rosterItem); } } return getRosterResponse; } public GetUserPairListResponse parseUserPairListResponse(HashMap response) { GetUserPairListResponse getUserPairListResponse = new GetUserPairListResponse(); final Object[] responseList = (Object[]) response.get("response"); for (Object pairObject : responseList) { if (pairObject instanceof HashMap && ((HashMap) pairObject).get("pairs") instanceof Object[]) { final Object[] userPairMap = (Object[]) ((HashMap) pairObject).get("pairs"); UserPair userPair = parseUserPair(userPairMap); getUserPairListResponse.getUserPairList().add(userPair); } } return getUserPairListResponse; } UserPair parseUserPair(Object[] userPairList) { UserPair userPair = new UserPair(); if (userPairList[0] instanceof HashMap) { HashMap userMap = (HashMap) userPairList[0]; userPair.setUser((String) userMap.get("user")); } if (userPairList[1] instanceof HashMap) { HashMap contactMap = (HashMap) userPairList[1]; userPair.setContact((String) contactMap.get("contact")); } return userPair; } RosterItem parseRosterItem(Object[] contact) { RosterItem rosterItem = new RosterItem(); if (contact[0] instanceof HashMap) { HashMap jidMap = (HashMap) contact[0]; rosterItem.setJid((String) jidMap.get("jid")); } if (contact[1] instanceof HashMap) { HashMap nickMap = (HashMap) contact[1]; rosterItem.setNick((String) nickMap.get("nick")); } if (contact[2] instanceof HashMap) { HashMap subscriptionMap = (HashMap) contact[2]; rosterItem.setSubscription((String) subscriptionMap.get("subscription")); } if (contact[3] instanceof HashMap) { HashMap askMap = (HashMap) contact[3]; rosterItem.setAsk((String) askMap.get("ask")); } if (contact[4] instanceof HashMap) { HashMap groupMap = (HashMap) contact[4]; rosterItem.setGroup((String) groupMap.get("group")); } return rosterItem; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/RosterItem.java
package ae.teletronics.ejabberd.entity; /** * Created by kristian on 4/7/16. */ public class RosterItem { String jid; String nick; String subscription; String ask; String group; public RosterItem() { } public RosterItem(String jid, String nick, String subscription, String ask, String group) { this.jid = jid; this.nick = nick; this.subscription = subscription; this.ask = ask; this.group = group; } public String getJid() { return jid; } public void setJid(String jid) { this.jid = jid; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getSubscription() { return subscription; } public void setSubscription(String subscription) { this.subscription = subscription; } public String getAsk() { return ask; } public void setAsk(String ask) { this.ask = ask; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/User.java
package ae.teletronics.ejabberd.entity; /** * Created by kristian on 4/7/16. */ public class User { String username; public User(String username) { this.username = username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/UserPair.java
package ae.teletronics.ejabberd.entity; /** * Created by jensrjorgensen on 22/02/2017. */ public class UserPair { String user; String contact; public UserPair() { } public UserPair(String user, String contact) { this.user = user; this.contact = contact; } public String getUser() { return this.user; } public void setUser(String user) { this.user = user; } public String getContact() { return this.contact; } public void setContact(String contact) { this.contact = contact; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/AddRosterItemResponse.java
package ae.teletronics.ejabberd.entity.response; /** * Created by kristian on 4/7/16. */ public class AddRosterItemResponse extends ErrorResponse{ }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/BooleanXmppResponse.java
package ae.teletronics.ejabberd.entity.response; /** * Created by kristian on 4/7/16. */ public class BooleanXmppResponse extends ErrorResponse{ public static int XMLRPC_SUCCES = 0; boolean successFull = false; public BooleanXmppResponse() { } public BooleanXmppResponse(boolean successFull) { this.successFull = successFull; } public BooleanXmppResponse(int xmppRes) { this.successFull = xmppRes == XMLRPC_SUCCES; } public BooleanXmppResponse(String error) { super(error); } public boolean isSuccessFull() { return successFull; } public void setSuccessFull(boolean successFull) { this.successFull = successFull; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/CreateUserResponse.java
package ae.teletronics.ejabberd.entity.response; /** * Created by kristian on 4/7/16. */ public class CreateUserResponse extends BooleanXmppResponse{ public CreateUserResponse(boolean successFull) { super(successFull); } public CreateUserResponse(int xmppRes) { super(xmppRes); } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/DeleteRosterItemResponse.java
package ae.teletronics.ejabberd.entity.response; /** * Created by kristian on 4/7/16. */ public class DeleteRosterItemResponse extends ErrorResponse{ }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/DeleteUserResponse.java
package ae.teletronics.ejabberd.entity.response; /** * Created by kristian on 4/7/16. */ public class DeleteUserResponse extends ErrorResponse{ }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/ErrorResponse.java
package ae.teletronics.ejabberd.entity.response; /** * Created by kristian on 4/7/16. */ public class ErrorResponse { String error; public ErrorResponse() { } public ErrorResponse(String error) { this.error = error; } public String getError() { return error; } public void setError(String error) { this.error = error; } public boolean hasError(){ return this.error != null; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/GetRosterResponse.java
package ae.teletronics.ejabberd.entity.response; import ae.teletronics.ejabberd.entity.RosterItem; import java.util.ArrayList; import java.util.List; /** * Created by kristian on 4/7/16. */ public class GetRosterResponse extends ErrorResponse{ List<RosterItem> rosterItemList; public GetRosterResponse() { this.rosterItemList = new ArrayList<>(); } public GetRosterResponse(List<RosterItem> rosterItemList) { this.rosterItemList = rosterItemList; } public GetRosterResponse(String error) { super(error); this.rosterItemList = new ArrayList<>(); } public List<RosterItem> getRosterItemList() { return rosterItemList; } public void setRosterItemList(List<RosterItem> rosterItemList) { this.rosterItemList = rosterItemList; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/GetUserPairListResponse.java
package ae.teletronics.ejabberd.entity.response; import ae.teletronics.ejabberd.entity.UserPair; import java.util.ArrayList; import java.util.List; /** * Created by jensrjorgensen on 22/02/2017. */ public class GetUserPairListResponse extends ErrorResponse { List<UserPair> userPairList; public GetUserPairListResponse() { this.userPairList = new ArrayList<>(); } public GetUserPairListResponse(List<UserPair> userPairList) { this.userPairList = userPairList; } public GetUserPairListResponse(String error) { super(error); this.userPairList = new ArrayList<>(); } public List<UserPair> getUserPairList() { return this.userPairList; } public void gstUserPairList(List<UserPair> userPairList) { this.userPairList = userPairList; } }
0
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity
java-sources/ae/teletronics/ejabberd/EjabberdXMLRPCClient/1.1.0/ae/teletronics/ejabberd/entity/response/GetUsersResponse.java
package ae.teletronics.ejabberd.entity.response; import ae.teletronics.ejabberd.entity.User; import java.util.ArrayList; import java.util.List; /** * Created by kristian on 4/7/16. */ public class GetUsersResponse extends ErrorResponse{ List<User> userList = new ArrayList<>(); public GetUsersResponse() { } public GetUsersResponse(String error) { super(error); } public GetUsersResponse(List<User> userList) { this.userList = userList; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } }
0
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae/teletronics/Application.java
package ae.teletronics; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ConfigurationBuilder; import java.io.IOException; import java.util.Optional; import java.util.Set; /** * Created by kristian on 3/28/16. */ public class Application { public static void main(String[] args) throws InstantiationException, IllegalAccessException, IOException, ClassNotFoundException { Application application = new Application(); ExternalAuth externalAuth = application.getImplementation(); externalAuth.setup(); externalAuth.readInput(); } ExternalAuth getImplementation() throws IllegalAccessException, InstantiationException, ClassNotFoundException { final Reflections reflections = new Reflections(); final Set<Class<? extends ExternalAuth>> externalAuthImplementations = reflections.getSubTypesOf(ExternalAuth.class); final Optional<Class<? extends ExternalAuth>> implementationOptional = externalAuthImplementations.stream().findFirst(); final Class<? extends ExternalAuth> implementationClass = implementationOptional.orElseThrow(() -> { return new ClassNotFoundException("There was no implementation of " + ExternalAuth.class.getName() + " supplied on classpath"); }); return implementationClass.newInstance(); } }
0
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae/teletronics/CommandType.java
package ae.teletronics; /** * Created by kristian on 3/28/16. */ public enum CommandType { AUTHENTICATE, EXISTS, SET_PASS, TRY_REGISTER, REMOVE_USER, REMOVE_SAFELY, UNKNOWN; public static CommandType fromString(String commandType){ if(commandType.equals("auth")){ return AUTHENTICATE; }else if(commandType.equals("isuser")){ return EXISTS; }else if(commandType.equals("setpass")){ return SET_PASS; }else if(commandType.equals("tryregister")){ return TRY_REGISTER; }else if(commandType.equals("removeuser")){ return REMOVE_USER; }else if(commandType.equals("removeuser3")){ return REMOVE_SAFELY; }else{ return UNKNOWN; } } }
0
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae/teletronics/ExternalAuth.java
package ae.teletronics; import java.io.*; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by kristian on 3/28/16. */ public abstract class ExternalAuth implements UserManagement{ public void readInput() throws IOException { this.readInput(new BufferedReader(new InputStreamReader(System.in))); } public void setup(){} public void readInput(BufferedReader bufferedReader) throws IOException { commandInputLoop: while(true){ byte[] lB = new byte[2]; int startPos = 0; while (startPos < lB.length) { int ret = System.in.read(lB, startPos, (lB.length - startPos)); if (ret < 0) { break commandInputLoop; } startPos += ret; } int streamLen = System.in.available(); byte[] rd = new byte[streamLen]; startPos = 0; while (startPos < streamLen) { int ret = System.in.read(rd, startPos,(streamLen - startPos)); if (ret < 0) { break commandInputLoop; } startPos += ret; } String inputCommand = new String(rd, "ASCII"); this.gotCommand(inputCommand); } } void gotCommand(String inputCommand) throws IOException { final InputCommand command = this.parseInput(inputCommand); if (command.commandType != CommandType.UNKNOWN){ boolean status = this.runCommand(command); this.writeOutput(status); } } void writeOutput(boolean commandStatus) throws IOException { byte[] res = new byte[4]; res[0] = 0; res[1] = 2; res[2] = 0; if (commandStatus) { res[3] = 1; } else { res[3] = 0; } System.out.write(res, 0, res.length); System.out.flush(); } InputCommand parseInput(String input){ final String[] args = input.split(":"); if (args.length >= 3){ final HashMap<String, String> commandsMap = new HashMap<String, String>(); CommandType commandType = CommandType.fromString(args[0]); commandsMap.put("user", args[1]); commandsMap.put("server", args[2]); if (args.length == 4){ commandsMap.put("password", args[3]); } return new InputCommand(commandType, commandsMap); }else{ return new InputCommand(CommandType.UNKNOWN); } } private boolean runCommand(InputCommand command){ boolean status = false; switch (command.commandType){ case AUTHENTICATE: status = this.authenticate(command.inputParameters.get("user"), command.inputParameters.get("server"), command.inputParameters.get("password")); break; case EXISTS: status = this.exists(command.inputParameters.get("user"), command.inputParameters.get("server")); break; case SET_PASS: status = this.setPassword(command.inputParameters.get("user"), command.inputParameters.get("server"), command.inputParameters.get("password")); break; case TRY_REGISTER: status = this.register(command.inputParameters.get("user"), command.inputParameters.get("server"), command.inputParameters.get("password")); break; case REMOVE_USER: status = this.remove(command.inputParameters.get("user"), command.inputParameters.get("server")); break; case REMOVE_SAFELY: status = this.removeSafely(command.inputParameters.get("user"), command.inputParameters.get("server"), command.inputParameters.get("password")); break; } return status; } }
0
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae/teletronics/InputCommand.java
package ae.teletronics; import java.util.Collection; import java.util.Map; /** * Created by kristian on 3/28/16. */ public class InputCommand { public InputCommand(CommandType commandType) { this.commandType = commandType; } public InputCommand(CommandType commandType, Map<String, String> inputParameters) { this.commandType = commandType; this.inputParameters = inputParameters; } public CommandType commandType; public Map<String, String> inputParameters; }
0
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae
java-sources/ae/teletronics/ejabberd/ejabberd-external-auth-java/1.0.0/ae/teletronics/UserManagement.java
package ae.teletronics; /** * Created by kristian on 3/28/16. */ public interface UserManagement { /** * * Corresponds to ejabberd `auth` operation. * * @param user Username of the user. Examples: test, testuser, kristian * @param server Server on which the user eixsts. Example: chat.teletronics.ae, chat.github.com * @param password Password for the user. */ public boolean authenticate(String user, String server, String password); /** * * Corresponds to ejabberd `isuser` operation. * * @param user Username of the user. Examples: test, testuser, kristian * @param server Server on which the user eixsts. Example: chat.teletronics.ae, chat.github.com */ public boolean exists(String user, String server); /** * * Corresponds to ejabberd `setpass` operation. * * @param user Username of the user. Examples: test, testuser, kristian * @param server Server on which the user eixsts. Example: chat.teletronics.ae, chat.github.com * @param password Password for the user. */ public boolean setPassword(String user, String server, String password); /** * * Corresponds to `tryregister` operation. * * @param user Username of the user. Examples: test, testuser, kristian * @param server Server on which the user eixsts. Example: chat.teletronics.ae, chat.github.com * @param password Password for the user. */ public boolean register(String user, String server, String password); /** * Corresponds to `removeuser` operation. * @param user Username of the user. Examples: test, testuser, kristian * @param server Server on which the user eixsts. Example: chat.teletronics.ae, chat.github.com */ public boolean remove(String user, String server); /** * Corresponds to `removeuser3` operation. * @param user Username of the user. Examples: test, testuser, kristian * @param server Server on which the user eixsts. Example: chat.teletronics.ae, chat.github.com * @param password Password for the user. */ public boolean removeSafely(String user, String server, String password); }
0
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers/demo/CallSendAudioFromFileHangupDemo.java
package net.sourceforge.peers.demo; import net.sourceforge.peers.Config; import net.sourceforge.peers.FileLogger; import net.sourceforge.peers.Logger; import net.sourceforge.peers.XmlConfig; import net.sourceforge.peers.media.*; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; import java.io.File; import java.util.Optional; public class CallSendAudioFromFileHangupDemo implements SipListener { private Logger logger; private Config config; private UserAgent userAgent; private SipRequest sipRequest; private Object registeredSync = new Object(); private Optional<Boolean> registered; public CallSendAudioFromFileHangupDemo(String calleeSipUrl) throws Exception { logger = new FileLogger(null); config = new XmlConfig(Utils.DEFAULT_PEERS_HOME + File.separator + UserAgent.CONFIG_FILE, logger); // Two consecutive calls. Two concurrent wont work - for now call(calleeSipUrl, "media/message.alaw", SoundSource.DataFormat.ALAW_8KHZ_MONO_LITTLE_ENDIAN); call(calleeSipUrl, "media/message.raw", SoundSource.DataFormat.LINEAR_PCM_8KHZ_16BITS_SIGNED_MONO_LITTLE_ENDIAN); } public void call(final String callee, final String mediaFile, final SoundSource.DataFormat mediaFileDataFormat) throws Exception { userAgent = new UserAgent(this, () -> new FilePlaybackSoundManager(mediaFile, mediaFileDataFormat, logger), config, null, logger); try { registered = Optional.empty(); userAgent.register(); if (!isRegistered()) { logger.error("Not able to register"); } String callId = Utils.generateCallID(userAgent.getConfig().getLocalInetAddress()); sipRequest = userAgent.invite(callee, callId); MediaManager mediaManager = userAgent.getMediaManager(); mediaManager.waitConnected(); SoundSource soundSource = mediaManager.getSoundSource(); soundSource.waitFinished(); mediaManager.waitFinishedSending(); System.out.println("Hanging up"); userAgent.terminate(sipRequest); } finally { userAgent.unregister(); userAgent.close(); } } // SipListener methods private boolean isRegistered() throws InterruptedException { if (registered.isPresent()) return registered.get(); synchronized (registeredSync) { while (!registered.isPresent()) { registeredSync.wait(); } return registered.get(); } } @Override public void registering(SipRequest sipRequest) { System.out.println("Registering " + sipRequest); } @Override public void registerSuccessful(SipResponse sipResponse) { System.out.println("Register successful " + sipResponse); registered = Optional.of(true); synchronized (registeredSync) { registeredSync.notifyAll(); } } @Override public void registerFailed(SipResponse sipResponse) { System.out.println("Register failed " + sipResponse); registered = Optional.of(false); synchronized (registeredSync) { registeredSync.notifyAll(); } } @Override public void incomingCall(SipRequest sipRequest, SipResponse provResponse) { System.out.println("Incoming call " + sipRequest + ", " + provResponse); } @Override public void remoteHangup(SipRequest sipRequest) { System.out.println("Remote hangup " + sipRequest); } @Override public void ringing(SipResponse sipResponse) { System.out.println("Ringing " + sipResponse); } @Override public void calleePickup(SipResponse sipResponse) { System.out.println("Callee pickup " + sipResponse); } @Override public void error(SipResponse sipResponse) { System.out.println("Error " + sipResponse); } @Override public void dtmfEvent(RFC4733.DTMFEvent dtmfEvent, int duration) { System.out.println(" DTMF " + dtmfEvent.name()); } public static void main(String[] args) { try { new CallSendAudioFromFileHangupDemo(args[0]); } catch (Exception e) { e.printStackTrace(); } } }
0
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers/demo/CommandsReader.java
package net.sourceforge.peers.demo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CommandsReader extends Thread { public static final String CALL = "call"; public static final String HANGUP = "hangup"; private boolean isRunning; private EventManager eventManager; public CommandsReader(EventManager eventManager) { this.eventManager = eventManager; } @Override public void run() { InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); setRunning(true); while (isRunning()) { String command; try { command = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); break; } command = command.trim(); if (command.startsWith(CALL)) { String callee = command.substring( command.lastIndexOf(' ') + 1); eventManager.call(callee); } else if (command.startsWith(HANGUP)) { eventManager.hangup(); } else { System.out.println("unknown command " + command); } } } public synchronized boolean isRunning() { return isRunning; } public synchronized void setRunning(boolean isRunning) { this.isRunning = isRunning; } }
0
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers/demo/CustomConfig.java
package net.sourceforge.peers.demo; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import net.sourceforge.peers.Config; import net.sourceforge.peers.media.MediaMode; import net.sourceforge.peers.media.SoundSource; import net.sourceforge.peers.rtp.RFC3551; import net.sourceforge.peers.sdp.Codec; import net.sourceforge.peers.sip.syntaxencoding.SipURI; public class CustomConfig implements Config { private InetAddress publicIpAddress; @Override public InetAddress getLocalInetAddress() { InetAddress inetAddress; try { // if you have only one active network interface, getLocalHost() // should be enough //inetAddress = InetAddress.getLocalHost(); // if you have several network interfaces like I do, // select the right one after running ipconfig or ifconfig inetAddress = InetAddress.getByName("192.168.1.10"); } catch (UnknownHostException e) { e.printStackTrace(); return null; } return inetAddress; } @Override public InetAddress getPublicInetAddress() { return publicIpAddress; } @Override public String getUserPart() { return "alice"; } @Override public String getDomain() { return "atlanta.com"; } @Override public String getPassword() { return "secret1234"; } @Override public MediaMode getMediaMode() { return MediaMode.captureAndPlayback; } @Override public String getAuthorizationUsername() { return getUserPart(); } @Override public List<Codec> getSupportedCodecs() { List<Codec> supportedCodecs = new ArrayList<Codec>(); Codec codec = new Codec(); codec.setPayloadType(RFC3551.PAYLOAD_TYPE_PCMA); codec.setName(RFC3551.PCMA); supportedCodecs.add(codec); return supportedCodecs; } @Override public void setPublicInetAddress(InetAddress inetAddress) { publicIpAddress = inetAddress; } @Override public SipURI getOutboundProxy() { return null; } @Override public int getSipPort() { return 0; } @Override public boolean isMediaDebug() { return false; } @Override public SoundSource.DataFormat getMediaFileDataFormat() { return null; } @Override public String getMediaFile() { return null; } @Override public int getRtpPort() { return 0; } @Override public void setLocalInetAddress(InetAddress inetAddress) { } @Override public void setUserPart(String userPart) { } @Override public void setDomain(String domain) { } @Override public void setPassword(String password) { } @Override public void setOutboundProxy(SipURI outboundProxy) { } @Override public void setSipPort(int sipPort) { } @Override public void setMediaMode(MediaMode mediaMode) { } @Override public void setMediaDebug(boolean mediaDebug) { } @Override public void setMediaFileDataFormat(SoundSource.DataFormat mediaFileDataFormat) { } @Override public void setMediaFile(String mediaFile) { } @Override public void setRtpPort(int rtpPort) { } @Override public void save() { } @Override public void setAuthorizationUsername(String authorizationUsername) { } @Override public void setSupportedCodecs(List<Codec> supportedCodecs) { } }
0
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-demo/0.5.4/net/sourceforge/peers/demo/EventManager.java
package net.sourceforge.peers.demo; import java.net.SocketException; import net.sourceforge.peers.Config; import net.sourceforge.peers.FileLogger; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.AbstractSoundManagerFactory; import net.sourceforge.peers.media.javaxsound.JavaxSoundManager; import net.sourceforge.peers.media.AbstractSoundManager; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public class EventManager implements SipListener, AbstractSoundManagerFactory { private UserAgent userAgent; private SipRequest sipRequest; private CommandsReader commandsReader; private AbstractSoundManager soundManager; public EventManager() throws SocketException { Config config = new CustomConfig(); Logger logger = new FileLogger(null); soundManager = new JavaxSoundManager(false, logger, null); userAgent = new UserAgent(this, config, logger); new Thread() { public void run() { try { userAgent.register(); } catch (SipUriSyntaxException e) { e.printStackTrace(); } } }.start(); commandsReader = new CommandsReader(this); commandsReader.start(); } // commands methods public void call(final String callee) { new Thread() { @Override public void run() { try { sipRequest = userAgent.invite(callee, null); } catch (SipUriSyntaxException e) { e.printStackTrace(); } } }.start(); } public void hangup() { new Thread() { @Override public void run() { userAgent.terminate(sipRequest); } }.start(); } // SipListener methods @Override public void registering(SipRequest sipRequest) { } @Override public void registerSuccessful(SipResponse sipResponse) { } @Override public void registerFailed(SipResponse sipResponse) { } @Override public void incomingCall(SipRequest sipRequest, SipResponse provResponse) { } @Override public void remoteHangup(SipRequest sipRequest) { } @Override public void ringing(SipResponse sipResponse) { } @Override public void calleePickup(SipResponse sipResponse) { } @Override public AbstractSoundManager getSoundManager() { return soundManager; } @Override public void error(SipResponse sipResponse) { } @Override public void dtmfEvent(RFC4733.DTMFEvent dtmfEvent, int duration) { //TODO implement } public static void main(String[] args) { try { new EventManager(); } catch (SocketException e) { e.printStackTrace(); } } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/AboutFrame.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.HyperlinkEvent.EventType; import net.sourceforge.peers.Logger; public class AboutFrame extends JFrame implements ActionListener, HyperlinkListener { public static final String LICENSE_FILE = File.separator + "gpl.txt"; private static final long serialVersionUID = 1L; private Logger logger; public AboutFrame(String peersHome, Logger logger) { setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("About"); String message = "Peers: java SIP softphone<br>" + "Copyright 2007-2010 Yohann Martineau<br>" + "<a href=\"" + EventManager.PEERS_URL + "\">" + EventManager.PEERS_URL + "</a>"; JTextPane textPane = new JTextPane(); textPane.setContentType("text/html"); textPane.setEditable(false); textPane.setText(message); textPane.addHyperlinkListener(this); textPane.setOpaque(false); textPane.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15)); add(textPane, BorderLayout.PAGE_START); String gpl = null; try { FileReader fileReader = new FileReader(peersHome + LICENSE_FILE); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuffer buf = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { buf.append(" "); buf.append(line); buf.append("\r\n"); } bufferedReader.close(); gpl = buf.toString(); } catch (IOException e) { logger.error(e.getMessage(), e); } JTextArea textArea = new JTextArea(); textArea.setEditable(false); Font font = textArea.getFont(); font = new Font(font.getName(), font.getStyle(), font.getSize() - 2); textArea.setFont(font); if (gpl != null) { textArea.setText(gpl); } JPanel panel = new JPanel(); JScrollPane scrollPane = new JScrollPane(textArea); textArea.setCaretPosition(0); //scrollPane.setPreferredSize(new Dimension(600, 300)); panel.add(scrollPane); panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); add(panel, BorderLayout.CENTER); panel = new JPanel(); JButton button = new JButton("Close"); button.addActionListener(this); panel.add(button); add(panel, BorderLayout.PAGE_END); pack(); Dimension dimension = scrollPane.getSize(); dimension = new Dimension(dimension.width + 20, 300); scrollPane.setPreferredSize(dimension); pack(); } @Override public void actionPerformed(ActionEvent e) { dispose(); } @Override public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) { if (EventType.ACTIVATED.equals(hyperlinkEvent.getEventType())) { try { URI uri = hyperlinkEvent.getURL().toURI(); java.awt.Desktop.getDesktop().browse(uri); } catch (URISyntaxException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } } } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/AccountFrame.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; /** * AccountFrame, edited with NetBeans IDE. * * @author yohann */ public class AccountFrame extends javax.swing.JFrame { private static final long serialVersionUID = 1L; private Logger logger; /** Creates new form AccountFrame */ public AccountFrame(UserAgent userAgent, Logger logger) { this.userAgent = userAgent; this.logger = logger; unregistering = false; initComponents(); registration = new Registration(jLabel6, logger); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jPasswordField1 = new javax.swing.JPasswordField(); jLabel6 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Account"); Config config = userAgent.getConfig(); String userPart = config.getUserPart(); if (userPart != null) { jTextField1.setText(userPart); } String domain = config.getDomain(); if (domain != null) { jTextField2.setText(domain); } String password = config.getPassword(); if (password != null) { jPasswordField1.setText(password); } SipURI outboundProxy = config.getOutboundProxy(); if (outboundProxy != null) { jTextField4.setText(outboundProxy.toString()); } jLabel1.setText("User"); jLabel2.setText("Domain"); jLabel3.setText("Password"); jLabel4.setText("Outbound Proxy"); jLabel5.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); jLabel5.setText("Account management"); jButton1.setText("Apply"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Close"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE) .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE) .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE) .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 150, Short.MAX_VALUE) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2) .addGap(6, 6, 6)) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jLabel5) .addGap(168, 168, 168)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jLabel6)) .addGap(7, 7, 7)) ); pack(); }// </editor-fold> private void applyNewConfig() { Config config = userAgent.getConfig(); String userpart = jTextField1.getText(); if (userpart != null) { config.setUserPart(userpart); } String domain = jTextField2.getText(); if (domain != null) { config.setDomain(domain); } char[] password = jPasswordField1.getPassword(); if (password != null && password.length > 0) { config.setPassword(new String(password)); } String outboundProxy = jTextField4.getText(); if (outboundProxy != null) { SipURI sipURI; try { if ("".equals(outboundProxy.trim())) { config.setOutboundProxy(null); } else { if (!outboundProxy.startsWith(RFC3261.SIP_SCHEME)) { outboundProxy = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + outboundProxy; } sipURI = new SipURI(outboundProxy); config.setOutboundProxy(sipURI); } } catch (SipUriSyntaxException e) { JOptionPane.showMessageDialog(this, e.getMessage()); logger.error("sip uri syntax issue", e); return; } } config.save(); unregistering = false; if (password != null && password.length > 0) { Runnable runnable = new Runnable() { public void run() { try { userAgent.register(); } catch (SipUriSyntaxException e) { JOptionPane.showMessageDialog(AccountFrame.this, e.getMessage()); logger.error("sip uri syntax issue", e); } } }; Thread thread = new Thread(runnable); thread.start(); } } public void registering(SipRequest sipRequest) { registration.registerSent(); } public synchronized void registerSuccess(SipResponse sipResponse) { if (unregistering) { userAgent.close(); applyNewConfig(); } else { registration.registerSuccessful(); } } public void registerFailed(SipResponse sipResponse) { if (unregistering) { userAgent.close(); applyNewConfig(); } else { registration.registerFailed(); } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { Runnable runnable; if (userAgent.isRegistered()) { synchronized (this) { unregistering = true; } runnable = new Runnable() { @Override public void run() { try { userAgent.unregister(); } catch (SipUriSyntaxException e) { logger.error("syntax error", e); } } }; } else { runnable = new Runnable() { @Override public void run() { userAgent.close(); applyNewConfig(); } }; } SwingUtilities.invokeLater(runnable); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { dispose(); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField4; // End of variables declaration private boolean unregistering; private UserAgent userAgent; private Registration registration; }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrame.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.border.Border; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public class CallFrame implements ActionListener, WindowListener { public static final String HANGUP_ACTION_COMMAND = "hangup"; public static final String PICKUP_ACTION_COMMAND = "pickup"; public static final String BUSY_HERE_ACTION_COMMAND = "busyhere"; public static final String CLOSE_ACTION_COMMAND = "close"; private CallFrameState state; public final CallFrameState INIT; public final CallFrameState UAC; public final CallFrameState UAS; public final CallFrameState RINGING; public final CallFrameState SUCCESS; public final CallFrameState FAILED; public final CallFrameState REMOTE_HANGUP; public final CallFrameState TERMINATED; private JFrame frame; private JPanel callPanel; private JPanel callPanelContainer; private CallFrameListener callFrameListener; private SipRequest sipRequest; CallFrame(String remoteParty, String id, CallFrameListener callFrameListener, Logger logger) { INIT = new CallFrameStateInit(id, this, logger); UAC = new CallFrameStateUac(id, this, logger); UAS = new CallFrameStateUas(id, this, logger); RINGING = new CallFrameStateRinging(id, this, logger); SUCCESS = new CallFrameStateSuccess(id, this, logger); FAILED = new CallFrameStateFailed(id, this, logger); REMOTE_HANGUP = new CallFrameStateRemoteHangup(id, this, logger); TERMINATED = new CallFrameStateTerminated(id, this, logger); state = INIT; this.callFrameListener = callFrameListener; frame = new JFrame(remoteParty); Container contentPane = frame.getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); JLabel remotePartyLabel = new JLabel(remoteParty); Border remotePartyBorder = BorderFactory.createEmptyBorder(5, 5, 0, 5); remotePartyLabel.setBorder(remotePartyBorder); remotePartyLabel.setAlignmentX(Component.CENTER_ALIGNMENT); contentPane.add(remotePartyLabel); Keypad keypad = new Keypad(this); contentPane.add(keypad); callPanelContainer = new JPanel(); contentPane.add(callPanelContainer); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.addWindowListener(this); } public void callClicked() { state.callClicked(); } public void incomingCall() { state.incomingCall(); } public void remoteHangup() { state.remoteHangup(); } public void error(SipResponse sipResponse) { state.error(sipResponse); } public void calleePickup() { state.calleePickup(); } public void ringing() { state.ringing(); } void hangup() { if (callFrameListener != null) { callFrameListener.hangupClicked(sipRequest); } } void pickup() { if (callFrameListener != null && sipRequest != null) { callFrameListener.pickupClicked(sipRequest); } } void busyHere() { if (callFrameListener != null && sipRequest != null) { frame.dispose(); callFrameListener.busyHereClicked(sipRequest); sipRequest = null; } } void close() { frame.dispose(); } public void setState(CallFrameState state) { this.state.log(state); this.state = state; } public JFrame getFrame() { return frame; } public void setCallPanel(JPanel callPanel) { if (this.callPanel != null) { callPanelContainer.remove(this.callPanel); frame.pack(); } callPanelContainer.add(callPanel); frame.pack(); this.callPanel = callPanel; } public void addPageEndLabel(String text) { Container container = frame.getContentPane(); JLabel label = new JLabel(text); Border labelBorder = BorderFactory.createEmptyBorder(0, 5, 0, 5); label.setBorder(labelBorder); label.setAlignmentX(Component.CENTER_ALIGNMENT); container.add(label); frame.pack(); } public void setSipRequest(SipRequest sipRequest) { this.sipRequest = sipRequest; } // action listener methods @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); Runnable runnable = null; if (HANGUP_ACTION_COMMAND.equals(actionCommand)) { runnable = new Runnable() { @Override public void run() { state.hangupClicked(); } }; } else if (CLOSE_ACTION_COMMAND.equals(actionCommand)) { runnable = new Runnable() { @Override public void run() { state.closeClicked(); } }; } else if (PICKUP_ACTION_COMMAND.equals(actionCommand)) { runnable = new Runnable() { public void run() { state.pickupClicked(); } }; } else if (BUSY_HERE_ACTION_COMMAND.equals(actionCommand)) { runnable = new Runnable() { @Override public void run() { state.busyHereClicked(); } }; } if (runnable != null) { SwingUtilities.invokeLater(runnable); } } // window listener methods @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { state.hangupClicked(); } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } public void keypadEvent(char c) { callFrameListener.dtmf(c); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameListener.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import net.sourceforge.peers.sip.transport.SipRequest; public interface CallFrameListener { public void hangupClicked(SipRequest sipRequest); public void pickupClicked(SipRequest sipRequest); public void busyHereClicked(SipRequest sipRequest); public void dtmf(char digit); }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameState.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JPanel; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.AbstractState; import net.sourceforge.peers.sip.transport.SipResponse; public abstract class CallFrameState extends AbstractState { protected CallFrame callFrame; protected JPanel callPanel; public CallFrameState(String id, CallFrame callFrame, Logger logger) { super(id, logger); this.callFrame = callFrame; } public void callClicked() {} public void incomingCall() {} public void calleePickup() {} public void error(SipResponse sipResponse) {} public void pickupClicked() {} public void busyHereClicked() {} public void hangupClicked() {} public void remoteHangup() {} public void closeClicked() {} public void ringing() {} }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateFailed.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import net.sourceforge.peers.Logger; public class CallFrameStateFailed extends CallFrameState { public CallFrameStateFailed(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); callPanel = new JPanel(); callPanel.add(new JLabel("Failed")); JButton closeButton = new JButton("Close"); closeButton.setActionCommand(CallFrame.CLOSE_ACTION_COMMAND); closeButton.addActionListener(callFrame); callPanel.add(closeButton); } @Override public void closeClicked() { callFrame.setState(callFrame.TERMINATED); callFrame.close(); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateInit.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JFrame; import net.sourceforge.peers.Logger; public class CallFrameStateInit extends CallFrameState { public CallFrameStateInit(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); } @Override public void callClicked() { callFrame.setState(callFrame.UAC); JFrame frame = callFrame.getFrame(); callFrame.setCallPanel(callFrame.UAC.callPanel); frame.setVisible(true); } @Override public void incomingCall() { callFrame.setState(callFrame.UAS); JFrame frame = callFrame.getFrame(); callFrame.setCallPanel(callFrame.UAS.callPanel); frame.setVisible(true); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateRemoteHangup.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import net.sourceforge.peers.Logger; public class CallFrameStateRemoteHangup extends CallFrameState { public CallFrameStateRemoteHangup(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); callPanel = new JPanel(); callPanel.add(new JLabel("Remote hangup")); JButton closeButton = new JButton("Close"); closeButton.setActionCommand(CallFrame.CLOSE_ACTION_COMMAND); closeButton.addActionListener(callFrame); callPanel.add(closeButton); } @Override public void closeClicked() { callFrame.setState(callFrame.TERMINATED); callFrame.close(); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateRinging.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.transport.SipResponse; public class CallFrameStateRinging extends CallFrameState { public CallFrameStateRinging(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); callPanel = new JPanel(); callPanel.add(new JLabel("Ringing")); JButton hangupButton = new JButton("Hangup"); hangupButton.setActionCommand(CallFrame.HANGUP_ACTION_COMMAND); hangupButton.addActionListener(callFrame); callPanel.add(hangupButton); } @Override public void hangupClicked() { callFrame.setState(callFrame.TERMINATED); callFrame.hangup(); callFrame.close(); } @Override public void calleePickup() { callFrame.setState(callFrame.SUCCESS); callFrame.setCallPanel(callFrame.SUCCESS.callPanel); } @Override public void error(SipResponse sipResponse) { callFrame.setState(callFrame.FAILED); callFrame.setCallPanel(callFrame.FAILED.callPanel); callFrame.addPageEndLabel("Reason: " + sipResponse.getReasonPhrase()); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateSuccess.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import net.sourceforge.peers.Logger; public class CallFrameStateSuccess extends CallFrameState { public CallFrameStateSuccess(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); callPanel = new JPanel(); callPanel.add(new JLabel("Talking")); JButton hangupButton = new JButton("Hangup"); hangupButton.setActionCommand(CallFrame.HANGUP_ACTION_COMMAND); hangupButton.addActionListener(callFrame); callPanel.add(hangupButton); } @Override public void remoteHangup() { callFrame.setState(callFrame.REMOTE_HANGUP); callFrame.setCallPanel(callFrame.REMOTE_HANGUP.callPanel); } @Override public void hangupClicked() { callFrame.setState(callFrame.TERMINATED); callFrame.hangup(); callFrame.close(); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateTerminated.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import net.sourceforge.peers.Logger; public class CallFrameStateTerminated extends CallFrameState { public CallFrameStateTerminated(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); } @Override public void calleePickup() { callFrame.hangup(); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateUac.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.transport.SipResponse; public class CallFrameStateUac extends CallFrameState { public CallFrameStateUac(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); callPanel = new JPanel(); callPanel.add(new JLabel("Calling")); JButton hangupButton = new JButton("Hangup"); hangupButton.setActionCommand(CallFrame.HANGUP_ACTION_COMMAND); hangupButton.addActionListener(callFrame); callPanel.add(hangupButton); } @Override public void hangupClicked() { callFrame.setState(callFrame.TERMINATED); callFrame.hangup(); callFrame.close(); } @Override public void calleePickup() { callFrame.setState(callFrame.SUCCESS); callFrame.setCallPanel(callFrame.SUCCESS.callPanel); } @Override public void error(SipResponse sipResponse) { callFrame.setState(callFrame.FAILED); callFrame.setCallPanel(callFrame.FAILED.callPanel); callFrame.addPageEndLabel("Reason: " + sipResponse.getReasonPhrase()); } @Override public void ringing() { callFrame.setState(callFrame.RINGING); callFrame.setCallPanel(callFrame.RINGING.callPanel); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/CallFrameStateUas.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import net.sourceforge.peers.Logger; public class CallFrameStateUas extends CallFrameState { public CallFrameStateUas(String id, CallFrame callFrame, Logger logger) { super(id, callFrame, logger); callPanel = new JPanel(); callPanel.add(new JLabel("Incoming call")); JButton hangupButton = new JButton("Busy here"); hangupButton.setActionCommand(CallFrame.BUSY_HERE_ACTION_COMMAND); hangupButton.addActionListener(callFrame); callPanel.add(hangupButton); JButton pickupButton = new JButton("Pickup"); pickupButton.setActionCommand(CallFrame.PICKUP_ACTION_COMMAND); pickupButton.addActionListener(callFrame); callPanel.add(pickupButton); } @Override public void pickupClicked() { callFrame.setState(callFrame.SUCCESS); callFrame.pickup(); callFrame.setCallPanel(callFrame.SUCCESS.callPanel); } @Override public void busyHereClicked() { callFrame.setState(callFrame.TERMINATED); callFrame.busyHere(); } @Override public void remoteHangup() { callFrame.setState(callFrame.REMOTE_HANGUP); callFrame.setCallPanel(callFrame.REMOTE_HANGUP.callPanel); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/EventManager.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.AbstractSoundManager; import net.sourceforge.peers.media.AbstractSoundManagerFactory; import net.sourceforge.peers.media.MediaManager; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.core.useragent.SipListener; import net.sourceforge.peers.sip.core.useragent.UserAgent; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldName; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaders; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import net.sourceforge.peers.sip.transactionuser.Dialog; import net.sourceforge.peers.sip.transactionuser.DialogManager; import net.sourceforge.peers.sip.transport.SipMessage; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public class EventManager implements SipListener, AbstractSoundManagerFactory, MainFrameListener, CallFrameListener, ActionListener { public static final String PEERS_URL = "http://peers.sourceforge.net/"; public static final String PEERS_USER_MANUAL = PEERS_URL + "user_manual"; public static final String ACTION_EXIT = "Exit"; public static final String ACTION_ACCOUNT = "Account"; public static final String ACTION_PREFERENCES = "Preferences"; public static final String ACTION_ABOUT = "About"; public static final String ACTION_DOCUMENTATION = "Documentation"; private UserAgent userAgent; private MainFrame mainFrame; private AccountFrame accountFrame; private Map<String, CallFrame> callFrames; private boolean closed; private Logger logger; private AbstractSoundManager soundManager; public EventManager(MainFrame mainFrame, String peersHome, Logger logger, AbstractSoundManager soundManager) { this.mainFrame = mainFrame; this.logger = logger; this.soundManager = soundManager; callFrames = Collections.synchronizedMap( new HashMap<String, CallFrame>()); closed = false; // create sip stack try { userAgent = new UserAgent(this, peersHome, logger); } catch (SocketException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(null, "Peers sip port " + "unavailable, about to leave", "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } }); } } // sip events // never update gui from a non-swing thread, thus using // SwingUtilties.invokeLater for each event coming from sip stack. @Override public void registering(final SipRequest sipRequest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (accountFrame != null) { accountFrame.registering(sipRequest); } mainFrame.registering(sipRequest); } }); } @Override public void registerFailed(final SipResponse sipResponse) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { //mainFrame.setLabelText("Registration failed"); if (accountFrame != null) { accountFrame.registerFailed(sipResponse); } mainFrame.registerFailed(sipResponse); } }); } @Override public void registerSuccessful(final SipResponse sipResponse) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (closed) { userAgent.close(); System.exit(0); return; } if (accountFrame != null) { accountFrame.registerSuccess(sipResponse); } mainFrame.registerSuccessful(sipResponse); } }); } @Override public void calleePickup(final SipResponse sipResponse) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CallFrame callFrame = getCallFrame(sipResponse); if (callFrame != null) { callFrame.calleePickup(); } } }); } @Override public AbstractSoundManager getSoundManager() { return soundManager; } @Override public void error(final SipResponse sipResponse) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CallFrame callFrame = getCallFrame(sipResponse); if (callFrame != null) { callFrame.error(sipResponse); } } }); } @Override public void dtmfEvent(RFC4733.DTMFEvent dtmfEvent, int duration) { //TODO Implement } @Override public void incomingCall(final SipRequest sipRequest, SipResponse provResponse) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { SipHeaders sipHeaders = sipRequest.getSipHeaders(); SipHeaderFieldName sipHeaderFieldName = new SipHeaderFieldName(RFC3261.HDR_FROM); SipHeaderFieldValue from = sipHeaders.get(sipHeaderFieldName); final String fromValue = from.getValue(); String callId = Utils.getMessageCallId(sipRequest); CallFrame callFrame = new CallFrame(fromValue, callId, EventManager.this, logger); callFrames.put(callId, callFrame); callFrame.setSipRequest(sipRequest); callFrame.incomingCall(); } }); } @Override public void remoteHangup(final SipRequest sipRequest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CallFrame callFrame = getCallFrame(sipRequest); if (callFrame != null) { callFrame.remoteHangup(); } } }); } @Override public void ringing(final SipResponse sipResponse) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CallFrame callFrame = getCallFrame(sipResponse); if (callFrame != null) { callFrame.ringing(); } } }); } // main frame events @Override public void register() { if (userAgent == null) { // if several peers instances are launched concurrently, // display error message and exit return; } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Config config = userAgent.getConfig(); if (config.getPassword() != null) { try { userAgent.register(); } catch (SipUriSyntaxException e) { mainFrame.setLabelText(e.getMessage()); } } } }); } @Override public void callClicked(final String uri) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String callId = Utils.generateCallID( userAgent.getConfig().getLocalInetAddress()); CallFrame callFrame = new CallFrame(uri, callId, EventManager.this, logger); callFrames.put(callId, callFrame); SipRequest sipRequest; try { sipRequest = userAgent.invite(uri, callId); } catch (SipUriSyntaxException e) { logger.error(e.getMessage(), e); mainFrame.setLabelText(e.getMessage()); return; } callFrame.setSipRequest(sipRequest); callFrame.callClicked(); } }); } @Override public void windowClosed() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { userAgent.unregister(); } catch (Exception e) { logger.error("error while unregistering", e); } closed = true; try { Thread.sleep(3 * RFC3261.TIMER_T1); } catch (InterruptedException e) { } System.exit(0); } }); } // call frame events @Override public void hangupClicked(final SipRequest sipRequest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { userAgent.terminate(sipRequest); } }); } @Override public void pickupClicked(final SipRequest sipRequest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String callId = Utils.getMessageCallId(sipRequest); DialogManager dialogManager = userAgent.getDialogManager(); Dialog dialog = dialogManager.getDialog(callId); userAgent.acceptCall(sipRequest, dialog); } }); } @Override public void busyHereClicked(final SipRequest sipRequest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { userAgent.rejectCall(sipRequest); } }); } @Override public void dtmf(final char digit) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MediaManager mediaManager = userAgent.getMediaManager(); mediaManager.sendDtmf(digit); } }); } private CallFrame getCallFrame(SipMessage sipMessage) { String callId = Utils.getMessageCallId(sipMessage); return callFrames.get(callId); } public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); logger.debug("gui actionPerformed() " + action); Runnable runnable = null; if (ACTION_EXIT.equals(action)) { runnable = new Runnable() { @Override public void run() { windowClosed(); } }; } else if (ACTION_ACCOUNT.equals(action)) { runnable = new Runnable() { @Override public void run() { if (accountFrame == null || !accountFrame.isDisplayable()) { accountFrame = new AccountFrame(userAgent, logger); accountFrame.setVisible(true); } else { accountFrame.requestFocus(); } } }; } else if (ACTION_PREFERENCES.equals(action)) { runnable = new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(null, "Not implemented yet"); } }; } else if (ACTION_ABOUT.equals(action)) { runnable = new Runnable() { @Override public void run() { AboutFrame aboutFrame = new AboutFrame( userAgent.getPeersHome(), logger); aboutFrame.setVisible(true); } }; } else if (ACTION_DOCUMENTATION.equals(action)) { runnable = new Runnable() { @Override public void run() { try { URI uri = new URI(PEERS_USER_MANUAL); java.awt.Desktop.getDesktop().browse(uri); } catch (URISyntaxException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } } }; } if (runnable != null) { SwingUtilities.invokeLater(runnable); } } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/Keypad.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; public class Keypad extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; public static final String CHARS = "123456789*0#"; private CallFrame callFrame; public Keypad(CallFrame callFrame) { this.callFrame = callFrame; initComponents(); } private void initComponents() { setLayout(new GridLayout(4, 3, 10, 5)); for (int i = 0; i < CHARS.length(); ++i) { char[] c = { CHARS.charAt(i) }; String digit = new String(c); JButton button = new JButton(digit); button.setActionCommand(digit); button.addActionListener(this); add(button); } setBorder(BorderFactory.createEmptyBorder(5, 10, 0, 10)); Dimension dimension = new Dimension(180, 115); setMinimumSize(dimension); setMaximumSize(dimension); } @Override public void actionPerformed(ActionEvent actionEvent) { String command = actionEvent.getActionCommand(); callFrame.keypadEvent(command.charAt(0)); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/MainFrame.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers.gui; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import net.sourceforge.peers.FileLogger; import net.sourceforge.peers.Logger; import net.sourceforge.peers.media.javaxsound.JavaxSoundManager; import net.sourceforge.peers.media.AbstractSoundManager; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.transport.SipRequest; import net.sourceforge.peers.sip.transport.SipResponse; public class MainFrame implements WindowListener, ActionListener { public static void main(final String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(args); } }); } private static void createAndShowGUI(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); new MainFrame(args); } private JFrame mainFrame; private JPanel mainPanel; private JPanel dialerPanel; private JTextField uri; private JButton actionButton; private JLabel statusLabel; private EventManager eventManager; private Registration registration; private Logger logger; public MainFrame(final String[] args) { String peersHome = Utils.DEFAULT_PEERS_HOME; if (args.length > 0) { peersHome = args[0]; } logger = new FileLogger(peersHome); String lookAndFeelClassName = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(lookAndFeelClassName); } catch (Exception e) { logger.error("cannot change look and feel", e); } final AbstractSoundManager soundManager = new JavaxSoundManager( false, //TODO config.isMediaDebug(), logger, peersHome); String title = ""; if (!Utils.DEFAULT_PEERS_HOME.equals(peersHome)) { title = peersHome; } title += "/Peers: SIP User-Agent"; mainFrame = new JFrame(title); mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); mainFrame.addWindowListener(this); mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); dialerPanel = new JPanel(); uri = new JTextField("sip:", 15); uri.addActionListener(this); actionButton = new JButton("Call"); actionButton.addActionListener(this); dialerPanel.add(uri); dialerPanel.add(actionButton); dialerPanel.setAlignmentX(Component.LEFT_ALIGNMENT); statusLabel = new JLabel(title); statusLabel.setAlignmentX(Component.LEFT_ALIGNMENT); Border border = BorderFactory.createEmptyBorder(0, 2, 2, 2); statusLabel.setBorder(border); mainPanel.add(dialerPanel); mainPanel.add(statusLabel); Container contentPane = mainFrame.getContentPane(); contentPane.add(mainPanel); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); menu.setMnemonic('F'); JMenuItem menuItem = new JMenuItem("Exit"); menuItem.setMnemonic('x'); menuItem.setActionCommand(EventManager.ACTION_EXIT); registration = new Registration(statusLabel, logger); Thread thread = new Thread(new Runnable() { public void run() { String peersHome = Utils.DEFAULT_PEERS_HOME; if (args.length > 0) { peersHome = args[0]; } eventManager = new EventManager(MainFrame.this, peersHome, logger, soundManager); eventManager.register(); } }, "gui-event-manager"); thread.start(); try { while (eventManager == null) { Thread.sleep(50); } } catch (InterruptedException e) { return; } menuItem.addActionListener(eventManager); menu.add(menuItem); menuBar.add(menu); menu = new JMenu("Edit"); menu.setMnemonic('E'); menuItem = new JMenuItem("Account"); menuItem.setMnemonic('A'); menuItem.setActionCommand(EventManager.ACTION_ACCOUNT); menuItem.addActionListener(eventManager); menu.add(menuItem); menuItem = new JMenuItem("Preferences"); menuItem.setMnemonic('P'); menuItem.setActionCommand(EventManager.ACTION_PREFERENCES); menuItem.addActionListener(eventManager); menu.add(menuItem); menuBar.add(menu); menu = new JMenu("Help"); menu.setMnemonic('H'); menuItem = new JMenuItem("User manual"); menuItem.setMnemonic('D'); menuItem.setActionCommand(EventManager.ACTION_DOCUMENTATION); menuItem.addActionListener(eventManager); menu.add(menuItem); menuItem = new JMenuItem("About"); menuItem.setMnemonic('A'); menuItem.setActionCommand(EventManager.ACTION_ABOUT); menuItem.addActionListener(eventManager); menu.add(menuItem); menuBar.add(menu); mainFrame.setJMenuBar(menuBar); mainFrame.pack(); mainFrame.setVisible(true); } // window events @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { eventManager.windowClosed(); } @Override public void windowClosing(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } // action event @Override public void actionPerformed(ActionEvent e) { eventManager.callClicked(uri.getText()); } // misc. public void setLabelText(String text) { statusLabel.setText(text); mainFrame.pack(); } public void registerFailed(SipResponse sipResponse) { registration.registerFailed(); } public void registerSuccessful(SipResponse sipResponse) { registration.registerSuccessful(); } public void registering(SipRequest sipRequest) { registration.registerSent(); } public void socketExceptionOnStartup() { JOptionPane.showMessageDialog(mainFrame, "peers SIP port " + "unavailable, exiting"); System.exit(1); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/MainFrameListener.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers.gui; public interface MainFrameListener { public void callClicked(String callee); public void windowClosed(); public void register(); }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/Registration.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JLabel; import net.sourceforge.peers.Logger; public class Registration { public final RegistrationState UNREGISTERED; public final RegistrationState REGISTERING; public final RegistrationState SUCCESS; public final RegistrationState FAILED; protected JLabel label; private RegistrationState state; public Registration(JLabel label, Logger logger) { this.label = label; String id = String.valueOf(hashCode()); UNREGISTERED = new RegistrationStateUnregsitered(id, this, logger); state = UNREGISTERED; REGISTERING = new RegistrationStateRegistering(id, this, logger); SUCCESS = new RegistrationStateSuccess(id, this, logger); FAILED = new RegistrationStateFailed(id, this, logger); } public void setState(RegistrationState state) { this.state = state; } public synchronized void registerSent() { state.registerSent(); } public synchronized void registerFailed() { state.registerFailed(); } public synchronized void registerSuccessful() { state.registerSuccessful(); } protected void displayRegistering() { URL url = getClass().getResource("working.gif"); // String folder = MainFrame.class.getPackage().getName().replace(".", // File.separator); // String filename = folder + File.separator + "working.gif"; // Logger.debug("filename: " + filename); // URL url = MainFrame.class.getClassLoader().getResource(filename); ImageIcon imageIcon = new ImageIcon(url); label.setIcon(imageIcon); label.setText("Registering"); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/RegistrationState.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.AbstractState; public abstract class RegistrationState extends AbstractState { protected Registration registration; public RegistrationState(String id, Registration registration, Logger logger) { super(id, logger); this.registration = registration; } public void registerSent() {} public void registerSuccessful() {} public void registerFailed() {} }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/RegistrationStateFailed.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import net.sourceforge.peers.Logger; public class RegistrationStateFailed extends RegistrationState { public RegistrationStateFailed(String id, Registration registration, Logger logger) { super(id, registration, logger); } @Override public void registerSent() { registration.setState(registration.REGISTERING); registration.displayRegistering(); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/RegistrationStateRegistering.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JLabel; import net.sourceforge.peers.Logger; public class RegistrationStateRegistering extends RegistrationState { public RegistrationStateRegistering(String id, Registration registration, Logger logger) { super(id, registration, logger); } @Override public void registerSuccessful() { registration.setState(registration.SUCCESS); JLabel label = registration.label; URL url = getClass().getResource("green.png"); // String folder = MainFrame.class.getPackage().getName().replace(".", // File.separator); // String filename = folder + File.separator + "green.png"; // logger.debug("filename: " + filename); // URL url = MainFrame.class.getClassLoader().getResource(filename); ImageIcon imageIcon = new ImageIcon(url); label.setIcon(imageIcon); label.setText("Registered"); } @Override public void registerFailed() { registration.setState(registration.FAILED); JLabel label = registration.label; URL url = getClass().getResource("red.png"); // String folder = MainFrame.class.getPackage().getName().replace(".", // File.separator); // URL url = MainFrame.class.getClassLoader().getResource( // folder + File.separator + "red.png"); logger.debug("image url: " + url); ImageIcon imageIcon = new ImageIcon(url); label.setIcon(imageIcon); label.setText("Registration failed"); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/RegistrationStateSuccess.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import net.sourceforge.peers.Logger; public class RegistrationStateSuccess extends RegistrationState { public RegistrationStateSuccess(String id, Registration registration, Logger logger) { super(id, registration, logger); } @Override public void registerSent() { registration.setState(registration.REGISTERING); registration.displayRegistering(); } }
0
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-gui/0.5.4/net/sourceforge/peers/gui/RegistrationStateUnregsitered.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers.gui; import net.sourceforge.peers.Logger; public class RegistrationStateUnregsitered extends RegistrationState { public RegistrationStateUnregsitered(String id, Registration registration, Logger logger) { super(id, registration, logger); } @Override public void registerSent() { registration.setState(registration.REGISTERING); registration.displayRegistering(); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/Config.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010 Yohann Martineau */ package net.sourceforge.peers; import java.net.InetAddress; import java.util.List; import net.sourceforge.peers.media.MediaMode; import net.sourceforge.peers.media.SoundSource; import net.sourceforge.peers.sdp.Codec; import net.sourceforge.peers.sip.syntaxencoding.SipURI; public interface Config { public void save(); public InetAddress getLocalInetAddress(); public InetAddress getPublicInetAddress(); public String getUserPart(); public String getDomain(); public String getPassword(); public SipURI getOutboundProxy(); public int getSipPort(); public MediaMode getMediaMode(); public boolean isMediaDebug(); public SoundSource.DataFormat getMediaFileDataFormat(); public String getMediaFile(); public int getRtpPort(); public String getAuthorizationUsername(); public List<Codec> getSupportedCodecs(); public void setLocalInetAddress(InetAddress inetAddress); public void setPublicInetAddress(InetAddress inetAddress); public void setUserPart(String userPart); public void setDomain(String domain); public void setPassword(String password); public void setOutboundProxy(SipURI outboundProxy); public void setSipPort(int sipPort); public void setMediaMode(MediaMode mediaMode); public void setMediaDebug(boolean mediaDebug); public void setMediaFileDataFormat(SoundSource.DataFormat mediaFileDataFormat); public void setMediaFile(String mediaFile); public void setRtpPort(int rtpPort); public void setAuthorizationUsername(String authorizationUsername); public void setSupportedCodecs(List<Codec> supportedCodecs); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/FileLogger.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2007-2013 Yohann Martineau */ package net.sourceforge.peers; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import net.sourceforge.peers.sip.Utils; public class FileLogger implements Logger { public final static String LOG_FILE = File.separator + "logs" + File.separator + "peers.log"; public final static String NETWORK_FILE = File.separator + "logs" + File.separator + "transport.log"; private PrintWriter logWriter; private PrintWriter networkWriter; private Object logMutex; private Object networkMutex; private SimpleDateFormat logFormatter; private SimpleDateFormat networkFormatter; public FileLogger(String peersHome) { if (peersHome == null) { peersHome = Utils.DEFAULT_PEERS_HOME; } try { logWriter = new PrintWriter(new BufferedWriter( new FileWriter(peersHome + LOG_FILE))); networkWriter = new PrintWriter(new BufferedWriter( new FileWriter(peersHome + NETWORK_FILE))); } catch (IOException e) { System.out.println("logging to stdout"); logWriter = new PrintWriter(System.out); networkWriter = new PrintWriter(System.out); } logMutex = new Object(); networkMutex = new Object(); logFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); networkFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); } @Override public final void debug(String message) { synchronized (logMutex) { logWriter.write(genericLog(message.toString(), "DEBUG")); logWriter.flush(); } } @Override public final void info(String message) { synchronized (logMutex) { logWriter.write(genericLog(message.toString(), "INFO ")); logWriter.flush(); } } @Override public final void error(String message) { synchronized (logMutex) { logWriter.write(genericLog(message.toString(), "ERROR")); logWriter.flush(); } } @Override public final void error(String message, Exception exception) { synchronized (logMutex) { logWriter.write(genericLog(message, "ERROR")); exception.printStackTrace(logWriter); logWriter.flush(); } } private final String genericLog(String message, String level) { StringBuffer buf = new StringBuffer(); buf.append(logFormatter.format(new Date())); buf.append(" "); buf.append(level); buf.append(" ["); buf.append(Thread.currentThread().getName()); buf.append("] "); buf.append(message); buf.append("\n"); return buf.toString(); } @Override public final void traceNetwork(String message, String direction) { synchronized (networkMutex) { StringBuffer buf = new StringBuffer(); buf.append(networkFormatter.format(new Date())); buf.append(" "); buf.append(direction); buf.append(" ["); buf.append(Thread.currentThread().getName()); buf.append("]\n\n"); buf.append(message); buf.append("\n"); networkWriter.write(buf.toString()); networkWriter.flush(); } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/JavaConfig.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2012 Yohann Martineau */ package net.sourceforge.peers; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import net.sourceforge.peers.media.MediaMode; import net.sourceforge.peers.media.SoundSource; import net.sourceforge.peers.rtp.RFC3551; import net.sourceforge.peers.rtp.RFC4733; import net.sourceforge.peers.sdp.Codec; import net.sourceforge.peers.sip.syntaxencoding.SipURI; public class JavaConfig implements Config { private InetAddress localInetAddress; private InetAddress publicInetAddress; private String userPart; private String password; private String domain; private SipURI outboundProxy; private int sipPort; private MediaMode mediaMode; private boolean mediaDebug; private SoundSource.DataFormat mediaFileDataFormat; private String mediaFile; private int rtpPort; private String authorizationUsername; private List<Codec> supportedCodecs; public JavaConfig() { // Add default codecs supportedCodecs = new ArrayList<Codec>(); Codec codec = new Codec(); codec.setPayloadType(RFC3551.PAYLOAD_TYPE_PCMA); codec.setName(RFC3551.PCMA); supportedCodecs.add(codec); codec = new Codec(); codec.setPayloadType(RFC3551.PAYLOAD_TYPE_PCMU); codec.setName(RFC3551.PCMU); supportedCodecs.add(codec); codec = new Codec(); codec.setPayloadType(RFC4733.PAYLOAD_TYPE_TELEPHONE_EVENT); codec.setName(RFC4733.TELEPHONE_EVENT); //TODO add fmtp:101 0-15 attribute supportedCodecs.add(codec); } public JavaConfig(InetAddress localInetAddress, String userPart, String password, String domain, SipURI outboundProxy, int sipPort, MediaMode mediaMode, boolean mediaDebug, SoundSource.DataFormat mediaFileDataFormat, String mediaFile, int rtpPort, String authorizationUsername, List<Codec> supportedCodecs) { this.localInetAddress = localInetAddress; this.userPart = userPart; this.password = password; this.domain = domain; this.outboundProxy = outboundProxy; this.sipPort = sipPort; this.mediaMode = mediaMode; this.mediaDebug = mediaDebug; this.mediaFileDataFormat = mediaFileDataFormat; this.mediaFile = mediaFile; this.rtpPort = rtpPort; this.authorizationUsername = authorizationUsername; this.supportedCodecs = supportedCodecs; } @Override public void save() { throw new RuntimeException("not implemented"); } @Override public InetAddress getLocalInetAddress() { return localInetAddress; } @Override public InetAddress getPublicInetAddress() { return publicInetAddress; } @Override public String getUserPart() { return userPart; } @Override public String getDomain() { return domain; } @Override public String getPassword() { return password; } @Override public SipURI getOutboundProxy() { return outboundProxy; } @Override public int getSipPort() { return sipPort; } @Override public MediaMode getMediaMode() { return mediaMode; } @Override public boolean isMediaDebug() { return mediaDebug; } @Override public int getRtpPort() { return rtpPort; } public String getAuthorizationUsername() { return authorizationUsername; } @Override public List<Codec> getSupportedCodecs() { return supportedCodecs; } @Override public SoundSource.DataFormat getMediaFileDataFormat() { return mediaFileDataFormat; } @Override public String getMediaFile() { return mediaFile; } @Override public void setLocalInetAddress(InetAddress inetAddress) { localInetAddress = inetAddress; } @Override public void setPublicInetAddress(InetAddress inetAddress) { publicInetAddress = inetAddress; } @Override public void setUserPart(String userPart) { this.userPart = userPart; } @Override public void setDomain(String domain) { this.domain = domain; } @Override public void setPassword(String password) { this.password = password; } @Override public void setOutboundProxy(SipURI outboundProxy) { this.outboundProxy = outboundProxy; } @Override public void setSipPort(int sipPort) { this.sipPort = sipPort; } @Override public void setMediaMode(MediaMode mediaMode) { this.mediaMode = mediaMode; } @Override public void setMediaDebug(boolean mediaDebug) { this.mediaDebug = mediaDebug; } @Override public void setRtpPort(int rtpPort) { this.rtpPort = rtpPort; } public void setAuthorizationUsername(String authorizationUsername) { this.authorizationUsername = authorizationUsername; } @Override public void setSupportedCodecs(List<Codec> supportedCodecs) { this.supportedCodecs = supportedCodecs; } @Override public void setMediaFileDataFormat(SoundSource.DataFormat mediaFileDataFormat) { this.mediaFileDataFormat = mediaFileDataFormat; } @Override public void setMediaFile(String mediaFile) { this.mediaFile = mediaFile; } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/Logger.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2013 Yohann Martineau */ package net.sourceforge.peers; public interface Logger { public void debug(String message); public void info(String message); public void error(String message); public void error(String message, Exception exception); public void traceNetwork(String message, String direction); }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/Timer.java
package net.sourceforge.peers; import java.util.Date; import java.util.TimerTask; import java.util.function.BooleanSupplier; /** * Basically a java.util.Timer, but it does not throw IllegalStateExceptions if you try to * schedule a task after it has been cancelled */ public class Timer extends java.util.Timer { public Timer() { super(); } public Timer(boolean isDaemon) { super(isDaemon); } public Timer(String name) { super(name); } public Timer(String name, boolean isDaemon) { super(name, isDaemon); } public void schedule(TimerTask task, long delay) { callIgnoreIllegalStateTransaction(() -> { super.schedule(task, delay); return true; }); } public void schedule(TimerTask task, Date time) { callIgnoreIllegalStateTransaction(() -> { super.schedule(task, time); return true; }); } public void schedule(TimerTask task, long delay, long period) { callIgnoreIllegalStateTransaction(() -> { super.schedule(task, delay, period); return true; }); } public void schedule(TimerTask task, Date firstTime, long period) { callIgnoreIllegalStateTransaction(() -> { super.schedule(task, firstTime, period); return true; }); } public void scheduleAtFixedRate(TimerTask task, long delay, long period) { callIgnoreIllegalStateTransaction(() -> { super.scheduleAtFixedRate(task, delay, period); return true; }); } public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) { callIgnoreIllegalStateTransaction(() -> { super.scheduleAtFixedRate(task, firstTime, period); return true; }); } private void callIgnoreIllegalStateTransaction(BooleanSupplier code) { try { code.getAsBoolean(); } catch (IllegalStateException e) { // ignore } } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/XmlConfig.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2010-2013 Yohann Martineau */ package net.sourceforge.peers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import net.sourceforge.peers.media.MediaMode; import net.sourceforge.peers.media.SoundSource; import net.sourceforge.peers.sdp.Codec; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.syntaxencoding.SipURI; import net.sourceforge.peers.sip.syntaxencoding.SipUriSyntaxException; import org.w3c.dom.*; import org.xml.sax.SAXException; public class XmlConfig implements Config { public final static int RTP_DEFAULT_PORT = 8000; private final static String XML_CODEC_NODE = "codec"; private final static String XML_CODEC_ATTR_NAME = "name"; private final static String XML_CODEC_ATTR_PAYLOADTYPE = "payloadType"; private Logger logger; private File file; private Document document; // persistent variables private InetAddress localInetAddress; private String userPart; private String domain; private String password; private SipURI outboundProxy; private int sipPort; private MediaMode mediaMode; private boolean mediaDebug; private String mediaFile; private SoundSource.DataFormat mediaFileDataFormat; private int rtpPort; private String authorizationUsername; private List<Codec> supportedCodecs; // corresponding DOM nodes private Node ipAddressNode; private Node userPartNode; private Node domainNode; private Node passwordNode; private Node outboundProxyNode; private Node sipPortNode; private Node mediaModeNode; private Node mediaDebugNode; private Node mediaFileDataFormatNode; private Node mediaFileNode; private Node rtpPortNode; private Node authUserNode; private Node supportedCodecsNode; // non-persistent variables private InetAddress publicInetAddress; //private InetAddress public XmlConfig(String fileName, Logger logger) { file = new File(fileName); this.logger = logger; if (!file.exists()) { logger.debug("config file " + fileName + " not found"); return; } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { logger.error("parser configuration exception", e); return; } try { document = documentBuilder.parse(file); } catch (SAXException e) { logger.error("cannot parse " + fileName,e ); return; } catch (IOException e) { logger.error("IOException", e); return; } Element documentElement = document.getDocumentElement(); ipAddressNode = getFirstChild(documentElement, "ipAddress"); String address = ipAddressNode.getTextContent(); try { if (isNullOrEmpty(ipAddressNode)) { localInetAddress = InetAddress.getLocalHost(); } else { localInetAddress = InetAddress.getByName(address); } } catch (UnknownHostException e) { logger.error("unknown host: " + address, e); } userPartNode = getFirstChild(documentElement, "userPart"); if (isNullOrEmpty(userPartNode)) { logger.error("userpart not found in configuration file"); } else { userPart = userPartNode.getTextContent(); } authUserNode = getFirstChild(documentElement, "authorizationUsername"); if (! isNullOrEmpty(authUserNode)) { authorizationUsername = authUserNode.getTextContent(); } domainNode = getFirstChild(documentElement, "domain"); if (isNullOrEmpty(domainNode)) { logger.error("domain not found in configuration file"); } else { domain = domainNode.getTextContent(); } passwordNode = getFirstChild(documentElement, "password"); if (!isNullOrEmpty(passwordNode)) { password = passwordNode.getTextContent(); } outboundProxyNode = getFirstChild(documentElement, "outboundProxy"); if (!isNullOrEmpty(outboundProxyNode)) { String uri = outboundProxyNode.getTextContent(); try { outboundProxy = new SipURI(uri); } catch (SipUriSyntaxException e) { logger.error("sip uri syntax exception: " + uri, e); } } sipPortNode = getFirstChild(documentElement, "sipPort"); if (isNullOrEmpty(sipPortNode)) { sipPort = RFC3261.TRANSPORT_DEFAULT_PORT; } else { sipPort = Integer.parseInt(sipPortNode.getTextContent()); } mediaModeNode = getFirstChild(documentElement, "mediaMode"); if (isNullOrEmpty(mediaModeNode)) { mediaMode = MediaMode.captureAndPlayback; } else { mediaMode = MediaMode.valueOf(mediaModeNode.getTextContent()); } mediaDebugNode = getFirstChild(documentElement, "mediaDebug"); if (isNullOrEmpty(mediaDebugNode)) { mediaDebug = false; } else { mediaDebug = Boolean.parseBoolean(mediaDebugNode.getTextContent()); } mediaFileDataFormatNode = getFirstChild(documentElement, "mediaFileDataFormat"); if (!isNullOrEmpty(mediaFileDataFormatNode)) { mediaFileDataFormat = SoundSource.DataFormat.fromShortAlias(mediaFileDataFormatNode.getTextContent()); } mediaFileNode = getFirstChild(documentElement, "mediaFile"); if (!isNullOrEmpty(mediaFileNode)) { mediaFile = mediaFileNode.getTextContent(); } if (mediaMode == MediaMode.file) { if (mediaFile == null || "".equals(mediaFile.trim())) { logger.error("streaming from file but no file provided"); } } rtpPortNode = getFirstChild(documentElement, "rtpPort"); if (isNullOrEmpty(rtpPortNode)) { rtpPort = RTP_DEFAULT_PORT; } else { rtpPort = Integer.parseInt(rtpPortNode.getTextContent()); if (rtpPort % 2 != 0) { logger.error("rtp port provided is " + rtpPort + " rtp port must be even"); } } supportedCodecs = new ArrayList<Codec>(); supportedCodecsNode = getFirstChild(documentElement, "supportedCodecs"); if(supportedCodecsNode != null && supportedCodecsNode.hasChildNodes()) { NodeList nodeList = supportedCodecsNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); if (XML_CODEC_NODE.equals(node.getNodeName()) && node.hasAttributes()) { Node name = node.getAttributes().getNamedItem(XML_CODEC_ATTR_NAME); Node pt = node.getAttributes().getNamedItem(XML_CODEC_ATTR_PAYLOADTYPE); Codec codec = new Codec(); codec.setName(name.getNodeValue()); codec.setPayloadType(Integer.parseInt(pt.getNodeValue())); supportedCodecs.add(codec); } } } } private boolean isNullOrEmpty(Node node) { return node == null || "".equals(node.getTextContent().trim()); } private Node getFirstChild(Node parent, String childName) { if (parent == null || childName == null) { return null; } NodeList nodeList = parent.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); if (childName.equals(node.getNodeName())) { return node; } } return null; } @Override public void save() { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); } catch (TransformerConfigurationException e) { logger.error("cannot create transformer", e); return; } FileWriter fileWriter; try { fileWriter = new FileWriter(file); } catch (IOException e) { logger.error("cannot create file writer", e); return; } StreamResult streamResult = new StreamResult(fileWriter); DOMSource domSource = new DOMSource(document); try { transformer.transform(domSource, streamResult); } catch (TransformerException e) { logger.error("cannot save config file", e); return; } logger.debug("config file saved"); } @Override public InetAddress getLocalInetAddress() { return localInetAddress; } @Override public InetAddress getPublicInetAddress() { return publicInetAddress; } @Override public String getUserPart() { return userPart; } @Override public String getDomain() { return domain; } @Override public String getPassword() { return password; } @Override public SipURI getOutboundProxy() { return outboundProxy; } @Override public int getSipPort() { return sipPort; } @Override public MediaMode getMediaMode() { return mediaMode; } @Override public boolean isMediaDebug() { return mediaDebug; } @Override public int getRtpPort() { return rtpPort; } @Override public String getAuthorizationUsername() { return authorizationUsername; } @Override public List<Codec> getSupportedCodecs() { return supportedCodecs; } @Override public SoundSource.DataFormat getMediaFileDataFormat() { return mediaFileDataFormat; } @Override public String getMediaFile() { return mediaFile; } @Override public void setLocalInetAddress(InetAddress inetAddress) { this.localInetAddress = inetAddress; ipAddressNode.setTextContent(inetAddress.getHostAddress()); } @Override public void setPublicInetAddress(InetAddress inetAddress) { this.publicInetAddress = inetAddress; } @Override public void setUserPart(String userPart) { this.userPart = userPart; userPartNode.setTextContent(userPart); } @Override public void setDomain(String domain) { this.domain = domain; domainNode.setTextContent(domain); } @Override public void setPassword(String password) { this.password = password; passwordNode.setTextContent(password); } @Override public void setOutboundProxy(SipURI outboundProxy) { this.outboundProxy = outboundProxy; if (outboundProxy == null) { outboundProxyNode.setTextContent(""); } else { outboundProxyNode.setTextContent(outboundProxy.toString()); } } @Override public void setSipPort(int sipPort) { this.sipPort = sipPort; sipPortNode.setTextContent(Integer.toString(sipPort)); } @Override public void setMediaMode(MediaMode mediaMode) { this.mediaMode = mediaMode; mediaModeNode.setTextContent(mediaMode.toString()); } @Override public void setMediaDebug(boolean mediaDebug) { this.mediaDebug = mediaDebug; mediaDebugNode.setTextContent(Boolean.toString(mediaDebug)); } @Override public void setRtpPort(int rtpPort) { this.rtpPort = rtpPort; rtpPortNode.setTextContent(Integer.toString(rtpPort)); } @Override public void setAuthorizationUsername(String authorizationUsername) { this.authorizationUsername = authorizationUsername; authUserNode.setTextContent(authorizationUsername); } @Override public void setSupportedCodecs(List<Codec> supportedCodecs) { this.supportedCodecs = supportedCodecs; // Remove all child nodes first if(supportedCodecsNode.hasChildNodes()) { NodeList nodeList = supportedCodecsNode.getChildNodes(); for (int i = nodeList.getLength() - 1; i > 0; i--) { Node node = nodeList.item(i); supportedCodecsNode.removeChild(node); } } for(Codec codec : supportedCodecs) { Element node = document.createElement(XML_CODEC_NODE); node.setAttribute(XML_CODEC_ATTR_NAME, codec.getName()); node.setAttribute(XML_CODEC_ATTR_PAYLOADTYPE, Integer.toString(codec.getPayloadType())); supportedCodecsNode.appendChild(node); } } @Override public void setMediaFileDataFormat(SoundSource.DataFormat mediaFileDataFormat) { this.mediaFileDataFormat = mediaFileDataFormat; mediaFileDataFormatNode.setTextContent(mediaFileDataFormat.getShortAlias()); } @Override public void setMediaFile(String mediaFile) { this.mediaFile = mediaFile; mediaFileNode.setTextContent(mediaFile); } }
0
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers
java-sources/ae/teletronics/peers/peers-lib/0.5.4/net/sourceforge/peers/media/AbstractSoundManager.java
/* This file is part of Peers, a java SIP softphone. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2013 Yohann Martineau */ package net.sourceforge.peers.media; public abstract class AbstractSoundManager implements SoundSource { public final static String MEDIA_DIR = "media"; public abstract void init(); public abstract void close(); public abstract int writeData(byte[] buffer, int offset, int length); }