Skip to main content
summaryrefslogtreecommitdiffstats
blob: e1d958db6597d07331c67277525b8bde800abec6 (plain) (blame)
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*******************************************************************************
 * Copyright (c) 2001, 2008 Oracle Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Oracle Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.jst.jsf.test.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.zip.ZipFile;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.validation.ValidationFramework;
import org.eclipse.wst.validation.internal.ConfigurationManager;
import org.eclipse.wst.validation.internal.GlobalConfiguration;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.osgi.framework.Bundle;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Test utility methods
 *
 * @author cbateman
 *
 */
public final class JSFTestUtil
{
    private static boolean     _enableTrace = false;
    
    /**
     * Setting to true enables internal tracing in this class.  The default
     * is false.  There is no thread safety.
     * 
     * @param enableTrace
     */
    public static void setEnableTrace(final boolean enableTrace)
    {
        _enableTrace = enableTrace;
    }
    
    /**
     * Used to turn off build validation to speed up testing
     *
     * @param isEnabled
     * @throws InvocationTargetException
     * @throws InvocationTargetException
     */
    public static void setValidationEnabled(final boolean isEnabled) throws InvocationTargetException
    {
        // old way (just in case)
        final GlobalConfiguration config = new GlobalConfiguration(ConfigurationManager.getManager().getGlobalConfiguration());
        config.setDisableAllValidation(!isEnabled);
        config.passivate();
        config.store();
        
        // new way
        ValidationFramework.getDefault().suspendAllValidation(!isEnabled);
    }

    /**
     * @param proxied
     * @param proxyHostName
     * @param proxyPort
     */
    public static void setInternetProxyPreferences(final boolean proxied, final String proxyHostName, final String proxyPort)
    {
        // disable
//        IProxyService proxy = ProxyManager.getProxyManager();
//
//        if (proxied)
//        {
//            ProxyData proxyData = new ProxyData(IProxyData.HTTP_PROXY_TYPE);
//            proxyData.setHost(proxyHostName);
//            proxyData.setPassword(proxyPort);
//            try
//            {
//                proxy.setProxyData(new ProxyData[] {proxyData});
//                proxy.setProxiesEnabled(true);
//            }
//            catch (CoreException ce)
//            {
//                // TODO: is this recoverable? Maybe should throw up.
//                Activator.log("Error setting web proxy.  Tests may fail or take a long time to run", ce);
//            }
//
//        }
//        else
//        {
//            proxy.setProxiesEnabled(false);
//        }
    }

    /**
     * Loads the source file in bundle called fileName into the jdtTestEnvironment
     * under srcFolderName/packageName.beanClassName
     *
     * @param bundle
     * @param fileName
     * @param beanClassName
     * @param srcFolderName
     * @param packageName
     * @param jdtTestEnvironment
     * @throws Exception
     */
    public static void loadSourceClass(final Bundle bundle,
                                       final String fileName,
                                       final String beanClassName,
                                       final String srcFolderName,
                                       final String packageName,
                                       final JDTTestEnvironment jdtTestEnvironment) throws Exception
    {
        final TestFileResource codeRes = new TestFileResource();
        codeRes.load(bundle, fileName);
        final String code = codeRes.toString();
        jdtTestEnvironment.addSourceFile(srcFolderName, packageName, beanClassName, code);
    }
    
    public static ZipFile createZipFile(final Bundle bundle, final String entryName) throws IOException, URISyntaxException
    {
        return new ZipFile(new File(getAbsolutePath(bundle, entryName).toOSString()));
    }

    public static URI getPlatformAbsPath(final String relativePath) throws MalformedURLException, URISyntaxException
    {
    	
        final File file = new File(Platform.getInstanceLocation().getURL().getFile() + File.separator + relativePath);
        return file.toURI();
    }

    public static IPath getAbsolutePath(final Bundle bundle, final String relativePath) throws IOException, URISyntaxException
    {
        final URL bundleUrl = bundle.getEntry(relativePath);
        Assert.assertNotNull(bundleUrl);
        final URL url = FileLocator.resolve(bundleUrl);
        return new Path(new File(url.getFile()).getAbsolutePath());
    }

    public static void savePlatformRelative(final TestFileResource testFile, final String relativePath) throws IOException, URISyntaxException
    {
        saveToFileSystem(testFile, getPlatformAbsPath(relativePath));
    }

    public static void saveToFileSystem(final TestFileResource testFile, final URI absPath) throws IOException
    {
        saveToFileSystem(testFile.toBytes(), absPath);
    }

    public static void saveToFileSystem(final byte[] buffer, final URI absPath) throws IOException
    {
        final File file = new File(absPath);

        FileOutputStream  outFile = null;

        try
        {
            outFile=new FileOutputStream(file);
            outFile.write(buffer);
        }
        finally
        {
            if (outFile != null)
            {
                outFile.close();
            }
        }

    }

    public static void saveToFileSystem(final InputStream inStream, final URI absPath) throws IOException
    {
        ByteArrayOutputStream loadFromInputStream = loadFromInputStream(inStream);
        saveToFileSystem(loadFromInputStream.toByteArray(), absPath);
    }
    
    /**
     * @param testFile
     * @param absPath
     * @return true if the contents of testFile and the contents of what absPath point to
     * are the same based on a byte for byte comparison (Arrays.equal(byte[], byte[]).
     *
     * @throws IOException
     */
    public static boolean areEqual(final TestFileResource testFile, final URI absPath) throws IOException
    {
        final File file = new File(absPath);

        return Arrays.equals(loadFromFile(file).toByteArray(), testFile.toBytes());
    }

    public static ByteArrayOutputStream loadFromFile(final IFile file) throws IOException
    {
        InputStream inStream = null;

        try
        {
            inStream = file.getContents();
            return loadFromInputStream(inStream);
        }
        catch(final CoreException ce)
        {
            return new ByteArrayOutputStream();
        }
        finally
        {
            if (inStream != null)
            {
                inStream.close();
            }
        }
    }

    public static ByteArrayOutputStream loadFromFile(final File file) throws IOException
    {
        FileInputStream  inFile = null;

        try
        {
            inFile=new FileInputStream(file);
            return loadFromInputStream(inFile);
        }
        finally
        {
            if (inFile != null)
            {
                inFile.close();
            }
        }
    }

    /**
     * Caller is responsible for closing the stream
     * @param stream
     * @return the byte stream loaded from the file
     * @throws IOException
     */
    public static ByteArrayOutputStream loadFromInputStream(final InputStream stream) throws IOException
    {
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        final byte[]  inBuffer = new byte[1024];
        int bytesRead;
//        int curPos = 0;
        while ((bytesRead = stream.read(inBuffer)) != -1)
        {
            buffer.write(inBuffer,0,bytesRead);
//            curPos+=bytesRead;
        }

        return buffer;
    }

    public static IndexedRegion getIndexedRegion(final IStructuredDocument document, final int documentOffset)
    {
        // C.B: most of this logic was copied from ContentAssistUtils.getNodeAt
        // I chose to copy rather than just call that because ContentAssistUtils is
        // internal
        final IStructuredModel model = getStructuredModel(document);
        IndexedRegion             region = null;
        if (model != null)
        {
            try
            {
                int lastOffset = documentOffset;
                region = model.getIndexedRegion(documentOffset);
                trace("Starting at region: "+region.toString());
                while (region == null && lastOffset >= 0) {
                    lastOffset--;
                    region = model.getIndexedRegion(lastOffset);
                    trace("Iterating on region: "+region.toString());
                }

                trace("Finished with: "+region.toString()+", Class: "+region.getClass());

                // now we assume we have an element.  But our context may be
                // on an attribute in that node, so we need to check
                if (region instanceof IDOMElement)
                {
                    trace("Region is an IDOMElement");
                    final IDOMElement domElement = (IDOMElement) region;

                    final NamedNodeMap attributes = domElement.getAttributes();

                    for (int i = 0; i < attributes.getLength(); i++)
                    {
                        final Node  attrNode = attributes.item(i);

                        if (attrNode instanceof IDOMAttr)
                        {
                            final IDOMAttr attr = (IDOMAttr) attrNode;
                            trace("Examining attribute: "+attr.toString());

                            if (documentOffset >= attr.getStartOffset()
                                    && documentOffset < attr.getEndOffset())
                            {
                                region = attr;
                                trace("Found attribute: "+region.toString());
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
            	trace("releasing model");
                model.releaseFromRead();
            }
        }

        trace("returning: "+region);
        return region;
    }

    private static void trace(final String message)
    {
        if (_enableTrace)
        {
            System.out.println("getIndexedRegion: "+message);
        }
    }

    /**
     * @param document
     * @return a structured model or null if one cannot be opened for document.
     * Note: the caller is responsible for releasing the instance of structured
     * model that gets returned.
     */
    private static IStructuredModel getStructuredModel(final IStructuredDocument document)
    {
        final IModelManager modelManager = StructuredModelManager.getModelManager();

        if (modelManager != null)
        {
            return StructuredModelManager.getModelManager().getModelForRead(document);
        }

        return null;
    }
    
    /**
     * Attempts to delete resource.  If the delete operation throws a 
     * CoreException, the call will sleep the thread for backOffInMs
     * before trying again.  Will try a maximum of 'maxTries' times.  If at that
     * point the resource still exists, an error will be logged and the method
     * will return.
     * 
     * @param resource
     * @param maxTries
     * @param backInMs
     * @return true if the delete was successful.
     */
    public static  boolean safeDelete(final IResource resource, final int maxTries, final int backOffInMs)
    {
        boolean success = false;

        DELETE_LOOP: for (int attempt = 0; attempt < maxTries; attempt++)
        {
            try
            {
                resource.delete(true, null);
                success = true;
                break DELETE_LOOP;
            }
            catch (CoreException e)
            {
                try
                {
                    Thread.sleep(backOffInMs);
                }
                catch (InterruptedException e1)
                {
                    // do nothing, just continue
                }
            }
        }
        if (!success)
        {
            System.err.println("Could not delete resource: "+resource.getLocation().toOSString());
        }
        return success;
    }

    private static IJobChangeListener javaScriptJobChangeListener;

    public static void preventJavaScriptJobs() {
    	if (javaScriptJobChangeListener == null) {
	    	javaScriptJobChangeListener = new JobChangeAdapter() {
	    		@Override
	    		public void scheduled(IJobChangeEvent event) {
	    			Job job = event.getJob();
	    			if (job != null) {
	    				String jobName = job.getName();
	    				if (jobName != null && jobName.length() > 0) {
	    					if (jobName.toUpperCase().contains("JAVASCRIPT")) { //$NON-NLS-1$
	    						job.cancel();
	    					}
	    				}
	    			}
	    		}
	    	};
    	}
    	Job.getJobManager().addJobChangeListener(javaScriptJobChangeListener);
    }

    public static void allowJavaScriptJobs() {
    	if (javaScriptJobChangeListener != null) {
    		Job.getJobManager().removeJobChangeListener(javaScriptJobChangeListener);
    		//don't null out javaScriptJobChangeListener as it may be reused without re-construction
    	}
    }

    public static Class<? extends TestCase> getPreventJavaScriptJobsTestCase() {
    	return PreventJavaScriptJobsTestCase.class;
    }

    public static Class<? extends TestCase> getAllowJavaScriptJobsTestCase() {
    	return AllowJavaScriptJobsTestCase.class;
    }

    public static class PreventJavaScriptJobsTestCase extends TestCase {
    	public void testPreventJavaScriptJobs() throws Exception {
    		preventJavaScriptJobs();
    	}
    }

    public static class AllowJavaScriptJobsTestCase extends TestCase {
    	public void testAllowJavaScriptJobs() throws Exception {
    		allowJavaScriptJobs();
    	}
    }

    private JSFTestUtil()
    {
    	// no instantiation
    }
}

Back to the top