aboutsummaryrefslogtreecommitdiffstats
path: root/uitest/src/com/vaadin/tests/TestBench.java
blob: 0323899ee8ee25d4b8edf6ae5baf5983f33ae50a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* 
 * Copyright 2000-2013 Vaadin Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.vaadin.tests;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.vaadin.data.Property;
import com.vaadin.data.util.HierarchicalContainer;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.LegacyApplication;
import com.vaadin.server.Page;
import com.vaadin.server.Page.UriFragmentChangedEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.LegacyWindow;
import com.vaadin.ui.Link;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;

/**
 * TestBench finds out testable classes within given java packages and adds them
 * to menu from where they can be executed. Class is considered testable if it
 * is of class Application or CustomComponent.
 * 
 * Note: edit TestBench.testablePackages array
 * 
 * @author Vaadin Ltd.
 * 
 */
public class TestBench extends com.vaadin.server.LegacyApplication implements
        Property.ValueChangeListener {

    // Add here packages which are used for finding testable classes
    String[] testablePackages = { "com.vaadin.tests",
            "com.vaadin.tests.tickets" };

    HierarchicalContainer testables = new HierarchicalContainer();

    LegacyWindow mainWindow = new LegacyWindow("TestBench window");

    // Main layout consists of tree menu and body layout
    HorizontalSplitPanel mainLayout = new HorizontalSplitPanel();

    Tree menu;

    VerticalLayout bodyLayout = new VerticalLayout();

    // TODO this could probably be a simple Set
    HashMap<Class<?>, String> itemCaptions = new HashMap<Class<?>, String>();

    @Override
    public void init() {

        // Add testable classes to hierarchical container
        for (int p = 0; p < testablePackages.length; p++) {
            testables.addItem(testablePackages[p]);
            try {
                final List<Class<?>> testableClasses = getTestableClassesForPackage(testablePackages[p]);
                for (final Iterator<Class<?>> it = testableClasses.iterator(); it
                        .hasNext();) {
                    final Class<?> t = it.next();
                    // ignore TestBench itself
                    if (t.equals(TestBench.class)) {
                        continue;
                    }
                    try {
                        testables.addItem(t);
                        itemCaptions.put(t, t.getName());
                        testables.setParent(t, testablePackages[p]);
                        testables.setChildrenAllowed(t, false);
                        continue;
                    } catch (final Exception e) {
                        try {
                            testables.addItem(t);
                            itemCaptions.put(t, t.getName());
                            testables.setParent(t, testablePackages[p]);
                            testables.setChildrenAllowed(t, false);
                            continue;
                        } catch (final Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        menu = new Tree("Testables", testables);

        for (final Iterator<Class<?>> i = itemCaptions.keySet().iterator(); i
                .hasNext();) {
            final Class<?> testable = i.next();
            // simplify captions
            final String name = testable.getName().substring(
                    testable.getName().lastIndexOf('.') + 1);
            menu.setItemCaption(testable, name);
        }
        // expand all root items
        for (final Iterator<?> i = menu.rootItemIds().iterator(); i.hasNext();) {
            menu.expandItemsRecursively(i.next());
        }

        menu.addListener(this);
        menu.setImmediate(true);
        menu.setNullSelectionAllowed(false);
        VerticalLayout lo = new VerticalLayout();
        lo.addComponent(menu);

        mainWindow.getPage().addListener(new Page.UriFragmentChangedListener() {
            @Override
            public void uriFragmentChanged(UriFragmentChangedEvent source) {
                String fragment = source.getUriFragment();
                if (fragment != null && !"".equals(fragment)) {
                    // try to find a proper test class

                    // exact match
                    Iterator<?> iterator = menu.getItemIds().iterator();
                    while (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (next instanceof Class) {
                            Class<?> c = (Class<?>) next;
                            String string = c.getName();
                            if (string.equals(fragment)) {
                                menu.setValue(c);
                                mainLayout.setSplitPosition(0);
                                return;
                            }
                        }
                    }

                    // simple name match
                    iterator = menu.getItemIds().iterator();
                    while (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (next instanceof Class) {
                            Class<?> c = (Class<?>) next;
                            String string = c.getSimpleName();
                            if (string.equals(fragment)) {
                                menu.setValue(c);
                                mainLayout.setSplitPosition(0);
                                return;
                            }
                        }
                    }
                    // ticket match
                    iterator = menu.getItemIds().iterator();
                    while (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (next instanceof Class) {
                            Class<?> c = (Class<?>) next;
                            String string = c.getSimpleName();
                            if (string.startsWith("Ticket" + fragment)) {
                                menu.setValue(c);
                                mainLayout.setSplitPosition(0);
                                return;
                            }
                        }
                    }

                    // just partly mach lowercase
                    iterator = menu.getItemIds().iterator();
                    while (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (next instanceof Class) {
                            Class<?> c = (Class<?>) next;
                            String string = c.getSimpleName();
                            if (string.toLowerCase().contains(
                                    fragment.toLowerCase())) {
                                menu.setValue(c);
                                mainLayout.setSplitPosition(0);
                                return;
                            }
                        }
                    }

                    getMainWindow().showNotification(
                            "No potential matc for #" + fragment);

                }

            }
        });

        mainLayout.addComponent(lo);

        Panel bodyPanel = new Panel(bodyLayout);
        bodyPanel.addStyleName("light");
        bodyPanel.setSizeFull();

        mainLayout.addComponent(bodyPanel);

        mainLayout.setSplitPosition(30);

        mainWindow.setContent(mainLayout);

        setMainWindow(mainWindow);
    }

    private Component createTestable(Class<?> c) {
        try {
            final LegacyApplication app = (LegacyApplication) c.newInstance();
            app.doInit(null);
            Layout lo = (Layout) app.getMainWindow().getContent();
            lo.setParent(null);
            return lo;
        } catch (final Exception e) {
            try {
                final CustomComponent cc = (CustomComponent) c.newInstance();
                cc.setSizeFull();
                return cc;
            } catch (final Exception e1) {
                e1.printStackTrace();
                VerticalLayout lo = new VerticalLayout();
                lo.addComponent(new Label(
                        "Cannot create application / custom component: "
                                + e1.toString()));

                Link l = new Link("Try opening via app runner",
                        new ExternalResource("../run/" + c.getName()));
                lo.addComponent(l);

                return lo;
            }
        }
    }

    // Handle menu selection and update body
    @Override
    public void valueChange(Property.ValueChangeEvent event) {
        bodyLayout.removeAllComponents();
        bodyLayout.setCaption(null);

        final Object o = menu.getValue();
        if (o != null && o instanceof Class) {
            final Class<?> c = (Class<?>) o;
            final String title = c.getName();
            bodyLayout.setCaption(title);
            bodyLayout.addComponent(createTestable(c));
        } else {
            // NOP node selected or deselected tree item
        }
    }

    /**
     * Return all testable classes within given package. Class is considered
     * testable if it's superclass is Application or CustomComponent.
     * 
     * @param packageName
     * @return
     * @throws ClassNotFoundException
     */
    public static List<Class<?>> getTestableClassesForPackage(String packageName)
            throws Exception {
        final ArrayList<File> directories = new ArrayList<File>();
        try {
            final ClassLoader cld = Thread.currentThread()
                    .getContextClassLoader();
            if (cld == null) {
                throw new ClassNotFoundException("Can't get class loader.");
            }
            final String path = packageName.replace('.', '/');
            // Ask for all resources for the path
            final Enumeration<URL> resources = cld.getResources(path);
            while (resources.hasMoreElements()) {
                final URL url = resources.nextElement();
                directories.add(new File(url.getFile()));
            }
        } catch (final Exception x) {
            throw new Exception(packageName
                    + " does not appear to be a valid package.");
        }

        final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
        // For every directory identified capture all the .class files
        for (final Iterator<File> it = directories.iterator(); it.hasNext();) {
            final File directory = it.next();
            if (directory.exists()) {
                // Get the list of the files contained in the package
                final String[] files = directory.list();
                for (int j = 0; j < files.length; j++) {
                    // we are only interested in .class files
                    if (files[j].endsWith(".class")) {
                        // removes the .class extension
                        final String p = packageName + '.'
                                + files[j].substring(0, files[j].length() - 6);
                        final Class<?> c = Class.forName(p);
                        if (c.getSuperclass() != null) {
                            if ((c.getSuperclass()
                                    .equals(com.vaadin.server.VaadinSession.class))) {
                                classes.add(c);
                            } else if ((c.getSuperclass()
                                    .equals(com.vaadin.ui.CustomComponent.class))) {
                                classes.add(c);
                            }
                        }

                        // for (int i = 0; i < c.getInterfaces().length; i++) {
                        // Class cc = c.getInterfaces()[i];
                        // if (c.getInterfaces()[i].equals(Testable.class)) {
                        // // Class is testable
                        // classes.add(c);
                        // }
                        // }
                    }
                }
            } else {
                throw new ClassNotFoundException(packageName + " ("
                        + directory.getPath()
                        + ") does not appear to be a valid package");
            }
        }

        return classes;
    }

}