Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 048a70c8dfecfa8ba1d0d81f00f089db1596e5a5 (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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*******************************************************************************
 * Copyright (c) 2000, 2008 IBM 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.compare.tests;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

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

import org.eclipse.compare.internal.Utilities;
import org.eclipse.compare.internal.core.patch.FileDiff;
import org.eclipse.compare.internal.core.patch.FileDiffResult;
import org.eclipse.compare.internal.core.patch.LineReader;
import org.eclipse.compare.internal.patch.WorkspacePatcher;
import org.eclipse.compare.patch.ApplyPatchOperation;
import org.eclipse.compare.patch.IFilePatch;
import org.eclipse.compare.patch.IFilePatchResult;
import org.eclipse.compare.patch.PatchConfiguration;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.Bundle;

public class PatchTest extends TestCase {

	private static final String PATCHDATA = "patchdata";
	private static final String PATCH_CONFIGURATION = "patchConfiguration.properties";
	
	class StringStorage implements IStorage {
		String fileName;
		public StringStorage(String old) {
			fileName = old;
		}
		public Object getAdapter(Class adapter) {
			return null;
		}
		public boolean isReadOnly() {
			return false;
		}
		public String getName() {
			return fileName;
		}
		public IPath getFullPath() {
			return null;
		}
		public InputStream getContents() throws CoreException {
			return new BufferedInputStream(asInputStream(fileName));
		}
	}
	
	class FileStorage implements IStorage {
		File file;
		public FileStorage(File file) {
			this.file = file;
		}
		public InputStream getContents() throws CoreException {
			try {
				return new FileInputStream(file);
			} catch (FileNotFoundException e) {
				// ignore, should never happen
			}
			return null;
		}
		public IPath getFullPath() {
			return new Path(file.getAbsolutePath());
		}
		public String getName() {
			return file.getName();
		}
		public boolean isReadOnly() {
			return true;
		}
		public Object getAdapter(Class adapter) {
			return null;
		}
	}
	
	class JarEntryStorage implements IStorage {
		JarEntry jarEntry;
		JarFile jarFile;
		public JarEntryStorage(JarEntry jarEntry, JarFile jarFile) {
			this.jarEntry = jarEntry;
			this.jarFile = jarFile;
		}
		public InputStream getContents() throws CoreException {
			try {
				return jarFile.getInputStream(jarEntry);
			} catch (IOException e) {
				// ignore, should never happen
			}
			return null;
		}
		public IPath getFullPath() {
			return new Path(jarFile.getName());
		}
		public String getName() {
			return jarEntry.getName();
		}
		public boolean isReadOnly() {
			return true;
		}
		public Object getAdapter(Class adapter) {
			return null;
		}
	}
	
	public PatchTest(String name) {
		super(name);
	}

	protected void setUp() throws Exception {
		// empty
	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}
	
	public void testCreatePatch() throws CoreException, IOException {
		patch("addition.txt", "patch_addition.txt", "exp_addition.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}
	
	public void testUnterminatedCreatePatch() throws CoreException, IOException {
		patch("addition.txt", "patch_addition2.txt", "exp_addition2.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}

	public void testContext0Patch() throws CoreException, IOException {
		patch("context.txt", "patch_context0.txt", "exp_context.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}

	public void testContext1Patch() throws CoreException, IOException {
		patch("context.txt", "patch_context1.txt", "exp_context.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}

	public void testContext3Patch() throws CoreException, IOException {
		patch("context.txt", "patch_context3.txt", "exp_context.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	}
	
	public void testContext3PatchWithHeader() throws CoreException, IOException {
		patch("context.txt", "patch_context3_header.txt", "exp_context.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		IStorage patchStorage = new StringStorage("patch_context3_header.txt");
		IFilePatch[] patches = ApplyPatchOperation.parsePatch(patchStorage);
		String header = patches[0].getHeader();
		LineReader reader = new LineReader(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(header.getBytes()))));
		List lines = reader.readLines();
		List expected = new ArrayList();
		expected.add("Index: old.txt\n");
		expected.add("UID: 42\n");
		assertEquals(LineReader.createString(false, expected), LineReader.createString(false, lines));
	}
	
	public void testDateUnknown() throws CoreException {
		IStorage patchStorage = new StringStorage("patch_dateunknown.txt");
		IFilePatch[] patches = ApplyPatchOperation.parsePatch(patchStorage);
		assertEquals(IFilePatch.DATE_UNKNOWN, patches[0].getBeforeDate());
		assertEquals(IFilePatch.DATE_UNKNOWN, patches[0].getAfterDate());
	}
	
	public void testDateError() throws CoreException {
		IStorage patchStorage = new StringStorage("patch_dateerror.txt");
		IFilePatch[] patches = ApplyPatchOperation.parsePatch(patchStorage);
		assertEquals(IFilePatch.DATE_UNKNOWN, patches[0].getBeforeDate());
		assertEquals(IFilePatch.DATE_UNKNOWN, patches[0].getAfterDate());
	}
	
	public void testDateKnown() throws CoreException {
		IStorage patchStorage = new StringStorage("patch_datevalid.txt");
		IFilePatch[] patches = ApplyPatchOperation.parsePatch(patchStorage);
		assertFalse(IFilePatch.DATE_UNKNOWN == patches[0].getBeforeDate());
		assertFalse(IFilePatch.DATE_UNKNOWN == patches[0].getAfterDate());
	}
	
	//Test creation of new workspace patch 
	public void testWorkspacePatch_Create(){
		//Note the order that exists in the array of expected results is based purely on the order of the files in the patch 
		patchWorkspace(new String[]{"addition.txt", "addition.txt"}, "patch_workspacePatchAddition.txt", new String[] { "exp_workspacePatchAddition2.txt","exp_workspacePatchAddition.txt"}, false, 0);   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
	}
	
	//Test applying the reverse of workspace creation patch 
	public void testWorkspacePatch_Create_Reverse(){
		//Note the order that exists in the array of expected results is based purely on the order of the files in the patch 
		patchWorkspace(new String[]{"exp_workspacePatchAddition2.txt","exp_workspacePatchAddition.txt"}, "patch_workspacePatchAddition.txt", new String[] {"addition.txt", "addition.txt"}, true, 0);   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
	}
	
	//Test the patching of an already existing file, the creation of a new one and the deletion of elements in a file
	public void testWorkspacePatch_Modify(){
		//Note the order that exists in the array of expected results is based purely on the order of the files in the patch 
		patchWorkspace(new String[]{"exp_workspacePatchAddition2.txt","exp_workspacePatchAddition.txt", "addition.txt"}, "patch_workspacePatchMod.txt", new String[] { "exp_workspacePatchMod1.txt","exp_workspacePatchMod2.txt", "exp_workspacePatchMod3.txt"}, false, 0 );   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
	}
	
	//Test applying the reverse of a workspace modify patch
	public void testWorkspacePatch_Modify_Reverse(){
		//Note the order that exists in the array of expected results is based purely on the order of the files in the patch 
		patchWorkspace(new String[]{ "exp_workspacePatchMod1.txt","exp_workspacePatchMod2.txt", "exp_workspacePatchMod3.txt"}, "patch_workspacePatchMod.txt", new String[] {"exp_workspacePatchAddition2.txt","exp_workspacePatchAddition.txt", "addition.txt"}, true, 0 );   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
	}
	
	//Tests the deletion of an already existing file, and the modification of another file
	public void testWorkspacePatch_Delete(){
		//Note the order that exists in the array of expected results is based purely on the order of the files in the patch 
		patchWorkspace(new String[]{"exp_workspacePatchMod2.txt","addition.txt", "exp_workspacePatchMod1.txt","addition.txt"}, "patch_workspacePatchDelete.txt", new String[] { "addition.txt","exp_workspacePatchDelete2.txt", "addition.txt", "exp_workspacePatchDelete1.txt"}, false, 0 );   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$
	}
	
	//Test applying the reverse of a workspace deletion patch
	public void testWorkspacePatch_Delete_Reverse(){
		//Note the order that exists in the array of expected results is based purely on the order of the files in the patch 
		patchWorkspace(new String[]{"addition.txt","exp_workspacePatchDelete2.txt", "addition.txt", "exp_workspacePatchDelete1.txt" }, "patch_workspacePatchDelete.txt", new String[] {"exp_workspacePatchMod2.txt","addition.txt", "exp_workspacePatchMod1.txt","addition.txt"}, true, 0 );   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$
	}
	
	// Keeps track of the failures
	private List failures = new ArrayList();
	
	public void testPatchdataSubfolders() throws IOException, CoreException {
		URL patchdataUrl = new URL(getBundle().getEntry("/"), new Path(PATCHDATA).toString());
		patchdataUrl = FileLocator.resolve(patchdataUrl);
		
		Map map = null;
		if (patchdataUrl.getProtocol().equals("file")) {
			map = extractNamesForFileProtocol(patchdataUrl);
		} else if (patchdataUrl.getProtocol().equals("jar")) {
			map = extractNamesForJarProtocol(patchdataUrl);	
		} else {
			fail("Unknown protocol");
		}
		assertNotNull(map);
		
		for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
			
			String sf = (String) iterator.next(); // subfolder
			Object[] result = (Object[]) map.get(sf);
			String[] fns =(String[]) result[0]; // filenames
			PatchConfiguration pc = (PatchConfiguration) result[1];
			
			if (pc == null) {
				pc = extractFuzzFromFilename(fns[1].substring(sf.length()));
			}
			
			// create a message to distinguish tests from different subfolders
			String msg = "Test for subfolder [" + PATCHDATA + "/" + sf + "] failed.";
			
			try {
				// test with expected result
				patchWorkspace(msg, new String[] { fns[0] }, fns[1],
						new String[] { fns[2] }, pc);
			} catch (AssertionFailedError e) {
				failures.add(e);
			}

			// test with actual result, should fail
			if (fns[3] != null) {
				try {
					patchWorkspace(msg, new String[] { fns[0] }, fns[1],
							new String[] { fns[3] }, pc);
				} catch (AssertionFailedError e) {
					// a failure is expected
					continue; // continue with a next subfolder
				}
				failures
						.add(new AssertionFailedError(
								"\npatchWorkspace should fail for file ["
										+ fns[3] + "] in folder [" + PATCHDATA
										+ "/" + sf + "]."));
			}
		}
		
		if (failures.isEmpty())
			return;

		if (failures.size() == 1)
			throw (AssertionFailedError) failures.get(0);

		StringBuffer sb = new StringBuffer(
				"Failures occured while testing data from patchdata subfolder (Please check log for further details):");
		for (Iterator iterator = failures.iterator(); iterator.hasNext();) {
			AssertionFailedError error = (AssertionFailedError) iterator.next();
			log("org.eclipse.compare.tests", error);
			sb.append("\n" + error.getMessage());
		}
		throw new AssertionFailedError(sb.toString());
	}
	
	// both copy-pasted from CoreTest
	
	private void log(String pluginID, IStatus status) {
		Platform.getLog(Platform.getBundle(pluginID)).log(status);
	}
	
	private void log(String pluginID, Throwable e) {
		log(pluginID, new Status(IStatus.ERROR, pluginID, IStatus.ERROR, "Error", e)); //$NON-NLS-1$
	}
	
	/**
	 * Return the patch configuration (with the fuzz factor) for the patcher
	 * basing on the patch file name. Default value for the fuzz is
	 * <code>-1</code> which means that it should be calculated automatically.
	 * 
	 * @param patch
	 *            The patch file name
	 * @return Patch configuration with the fuzz factor set.
	 * @deprecated Use patchConfiguration.properties file for each subfolder
	 *             instead.
	 */
	private PatchConfiguration extractFuzzFromFilename(String patch) {
		int fuzz = -1;
		if (patch.indexOf("fuzz3") > -1 || patch.indexOf("f3") > -1)
			fuzz = 3;
		if (patch.indexOf("fuzz2") > -1 || patch.indexOf("f2") > -1)
			fuzz = 2;
		if (patch.indexOf("fuzz1") > -1 || patch.indexOf("f1") > -1)
			fuzz = 1;
		if (patch.indexOf("fuzz0") > -1 || patch.indexOf("f0") > -1)
			fuzz = 0;
		
		PatchConfiguration pc = new PatchConfiguration();
		pc.setFuzz(fuzz);
		return pc;
	}
	
	/**
	 * @param patchdataUrl
	 * @return A map with subfolder name as a key and an array of objects as a
	 *         value. The first object in the array is another array (of
	 *         Strings) containing file names for the test. The last value in
	 *         this array can be <code>null</code> as testing against actual
	 *         result is optional. The second object is an instance of
	 *         <code>PatchConfiguration</code> class.
	 * @throws IOException
	 * @throws CoreException
	 */
	private Map extractNamesForJarProtocol(URL patchdataUrl) throws IOException,
			CoreException {
		JarFile jarFile = ((JarURLConnection) patchdataUrl.openConnection()).getJarFile();
		
		// look for the patchdata folder entry
		String patchdataName = null;
		Enumeration entries = jarFile.entries();
		while (entries.hasMoreElements()) {
			JarEntry entry = (JarEntry) entries.nextElement();
			String entryName = entry.getName();
			if (entryName.endsWith("/" + PATCHDATA + "/")) {
				patchdataName = entryName;
				break;
			}
		}
		// patchdata folder not found
		if (patchdataName == null)
			return null;
		
		// look for files in patchdata subfolders
		Map result = new HashMap();
		Set subfoldersWithConfiguration = new HashSet();
		entries = jarFile.entries();
		while (entries.hasMoreElements()) {
			JarEntry entry = (JarEntry) entries.nextElement();
			String entryName = entry.getName();
			if (entry.isDirectory()) {
				if (!entryName.equals(patchdataName) && entryName.startsWith(patchdataName)) {
					// a subfolder found
					ZipEntry patchConf = jarFile.getEntry(entryName + "/" + PATCH_CONFIGURATION);
					if (patchConf != null) {
						JarEntryStorage jes = new JarEntryStorage(entry,jarFile);
						Properties properties = new Properties();
					    try {
					        properties.load(jes.getContents());
					    } catch (IOException e) {
					    	fail("IOException occured while loading the Patch Configuration file for "+entryName.toString());
					    }
					    
					    processProperties(result, properties, entryName);
						subfoldersWithConfiguration.add(entryName);
					}
				}
			} else {
				if (!entryName.equals(patchdataName) && entryName.startsWith(patchdataName)) {
					String relativePath = entryName.substring(patchdataName.length());
					String subfolderName = relativePath.substring(0, relativePath.indexOf("/"));
					if (!subfoldersWithConfiguration.contains(subfolderName))
						extractNamesForJarEntry(result,jarFile,entry,patchdataName);
				}
			}
		}
		return result;
	}
	
	/**
	 * @param cm configuration map
	 * @param jf jar file with compare tests (comparetests.jar) 
	 * @param je jar entry to process
	 * @param patchdataName name of the jar entry for 'patchdata' folder
	 * @throws CoreException
	 * 
	 * @deprecated Use patchConfiguration.properties file for each subfolder
	 *             instead.
	 */
	private void extractNamesForJarEntry(Map cm, JarFile jf, JarEntry je,
			String patchdataName) throws CoreException {
		String entryName = je.getName();
		//TODO: redundant check, it has been already checked in extractNamesForJarProtocol
		if (!entryName.equals(patchdataName) && entryName.startsWith(patchdataName)) {
			if (!entryName.endsWith("/")) {
				
				// file within a subfolder of 'patchdata' folder
				String relativePath = entryName.substring(patchdataName.length());
				
				StringTokenizer st = new StringTokenizer(relativePath, "/");
				if (st.countTokens() != 2) 
					return; // accept only files in a direct subfolder
				
				String subfolder = st.nextToken();
				String filename = st.nextToken();
				
				if (filename.indexOf("patch") > -1) {
					assertTrue(ApplyPatchOperation.isPatch(new JarEntryStorage(
							je, jf)));
					String[] names = (String[]) cm.get(subfolder);
					if (names == null)
						cm.put(subfolder, new String[] { null, relativePath,
								null, null });
					else
						names[1] = relativePath;
				} else if (filename.indexOf("exp") > -1) {
					String[] names = (String[]) cm.get(subfolder);
					if (names == null)
						cm.put(subfolder, new String[] { null, null,
								relativePath, null });
					else
						names[2] = relativePath;
				} else if (filename.indexOf("act") > -1) {
					String[] names = (String[]) cm.get(subfolder);
					if (names == null)
						cm.put(subfolder, new String[] { null, null, null,
								relativePath });
					else
						names[3] = relativePath;
				} else {
					String[] names = (String[]) cm.get(subfolder);
					if (names == null)
						cm.put(subfolder, new String[] { relativePath, null,
								null, null });
					else
						names[0] = relativePath;
				}
			}
		}
	}
	
	private Map extractNamesForFileProtocol(URL patchdataUrl)
			throws CoreException {

		Map result = new HashMap(); // configuration map

		IPath patchdataFolderPath = new Path(patchdataUrl.getPath());
		File patchdataFolderFile = patchdataFolderPath.toFile();
		assertTrue(patchdataFolderFile.isDirectory());
		File[] listOfSubfolders = patchdataFolderFile
				.listFiles(new FileFilter() {
					public boolean accept(File pathname) {
						return pathname.isDirectory();
					}
				});
		for (int i = 0; i < listOfSubfolders.length; i++) {
			File subfolder = listOfSubfolders[i];
			Path pcPath = new Path(subfolder.getPath() + "/" + PATCH_CONFIGURATION);
			File pcFile = pcPath.toFile();
			
			if (subfolder.getName().equals("CVS"))
				continue;
			if (pcFile.exists()) {
				Properties properties = new Properties();
			    try {
			        properties.load(new FileInputStream(pcFile));
			    } catch (IOException e) {
			    	fail("IOException occured while loading the Patch Configuration file for "
							+ subfolder.toString());
			    }
			    processProperties(result, properties, subfolder.getName());
			} else {
				extractNamesForFile(result, patchdataFolderFile, subfolder);
			}
		}
		return result;
	}

	/**
	 * @param cm configuration map
	 * @param patchdataFolderFile file object for 'patchdata' folder
	 * @param subfolder file object for current subfolder to process
	 * @throws CoreException
	 * @deprecated Use patchConfiguration.properties file for each subfolder
	 *             instead.
	 */
	private void extractNamesForFile(Map cm, File patchdataFolderFile,
			File subfolder) throws CoreException {
		File[] files = subfolder.listFiles();
		File patchFile = null;
		File fileToPatch = null;
		File fileWithExpectedResult = null;
		File fileWithActualResult = null; // optional
		for (int j = 0; j < files.length; j++) {
			File file = files[j];
			if (file.isDirectory()) // probably CVS dir
				continue;
			String filename = file.getName();
			if (filename.indexOf("patch") > -1) {
				assertTrue(ApplyPatchOperation.isPatch(new FileStorage(file)));
				patchFile = file;
			} else if (filename.indexOf("exp") > -1) {
				fileWithExpectedResult = file;
			} else if (filename.indexOf("act") > -1) {
				fileWithActualResult = file;
			} else {
				fileToPatch = file;
			}
		}

		// make the paths relative
		String fileToPatchString = fileToPatch.getPath().substring(patchdataFolderFile.getPath().length() + 1);
		String patchFileString = patchFile.getPath().substring(patchdataFolderFile.getPath().length() + 1);
		String fileWithExpectedResultString = fileWithExpectedResult.getPath().substring(patchdataFolderFile.getPath().length() + 1);
		String fileWithActualResultString = null;
		if (fileWithActualResult != null)
			fileWithActualResultString = fileWithActualResult.getPath().substring(patchdataFolderFile.getPath().length() + 1);

		cm.put(subfolder.getName(), new Object[] {
				new String[] { fileToPatchString, patchFileString,
						fileWithExpectedResultString,
						fileWithActualResultString }, null });
	}
	
	private void processProperties(Map cm, Properties p, String subfolderName) {
		boolean skipTest = Boolean.valueOf(p.getProperty("skipTest", "false")).booleanValue();
	    if (skipTest)
	    	return;
	    String pf = p.getProperty("patchFile", "patch.txt");
	    String cf = p.getProperty("contextFile", "context.txt");
	    String erf = p.getProperty("expectedResultFile", "exp_context");
	    // optional, can't guess the file name here, it might left empty intentionally
	    String arf = p.getProperty("actualResultFile", null);
	    int fuzzFactor = Integer.parseInt(p.getProperty("fuzzFactor", "0")); 
	    boolean ignoreWhitespace = Boolean.valueOf(p.getProperty("ignoreWhitespace", "false")).booleanValue();
	    int prefixSegmentStrip = Integer.parseInt(p.getProperty("prefixSegmentStrip", "0"));
	    boolean reversed = Boolean.valueOf(p.getProperty("reversed", "false")).booleanValue();
	    
	    PatchConfiguration pc = new PatchConfiguration();
	    pc.setFuzz(fuzzFactor);
	    pc.setIgnoreWhitespace(ignoreWhitespace);
	    pc.setPrefixSegmentStripCount(prefixSegmentStrip);
	    pc.setReversed(reversed);
	    
	    // make the paths relative
		pf = subfolderName + "/" + pf;
		cf = subfolderName + "/" + cf;
		erf = subfolderName + "/" + erf;
		if (arf != null) // optional
			arf = subfolderName + "/" + arf;
		
		// add to the map
		cm.put(subfolderName, new Object[] { new String[] { cf, pf, erf, arf },	pc });
	}
	
	
	// Test changing
	private BufferedReader getReader(String name) {
		InputStream resourceAsStream = asInputStream(name);
		InputStreamReader reader2= new InputStreamReader(resourceAsStream);
		return new BufferedReader(reader2);
	}

	private InputStream asInputStream(String name) {
		IPath path= new Path(PATCHDATA).append(name);
		try {
			URL url= new URL(getBundle().getEntry("/"), path.toString());
			return url.openStream();
		} catch (IOException e) {
			fail("Failed while reading " + name);
			return null; // never reached
		}
	}

	private void patch(final String old, String patch, String expt) throws CoreException, IOException {
		patcherPatch(old, patch, expt);
		filePatch(old, patch, expt);
	}

	private void filePatch(final String old, String patch, String expt) throws CoreException, IOException {
		LineReader lr= new LineReader(getReader(expt));
		List inLines= lr.readLines();
		String expected = LineReader.createString(false, inLines);
		
		IStorage oldStorage = new StringStorage(old);
		IStorage patchStorage = new StringStorage(patch);
		IFilePatch[] patches = ApplyPatchOperation.parsePatch(patchStorage);
		assertTrue(patches.length == 1);
		IFilePatchResult result = patches[0].apply(oldStorage, new PatchConfiguration(), null);
		assertTrue(result.hasMatches());
		assertFalse(result.hasRejects());
		InputStream actualStream = result.getPatchedContents();
		String actual = asString(actualStream);
		assertEquals(expected, actual);
	}

	private String asString(InputStream exptStream) throws IOException {
		return Utilities.readString(exptStream, ResourcesPlugin.getEncoding());
	}

	private void patcherPatch(String old, String patch, String expt) {
		LineReader lr= new LineReader(getReader(old));
		List inLines= lr.readLines();

		WorkspacePatcher patcher= new WorkspacePatcher();
		try {
			patcher.parse(getReader(patch));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		FileDiff[] diffs= patcher.getDiffs();
		Assert.assertEquals(diffs.length, 1);
		
		FileDiffResult diffResult = patcher.getDiffResult(diffs[0]);
		diffResult.patch(inLines, null);
		
		LineReader expectedContents= new LineReader(getReader(expt));
		List expectedLines= expectedContents.readLines();
		
		Object[] expected= expectedLines.toArray();
		Object[] result= inLines.toArray();
		
		Assert.assertEquals(expected.length, result.length);
		
		for (int i= 0; i < expected.length; i++)
			Assert.assertEquals(expected[i], result[i]);
	}
	
	private void patchWorkspace(String[] originalFiles, String patch,
			String[] expectedOutcomeFiles, boolean reverse,
			int fuzzFactor) {
		PatchConfiguration pc = new PatchConfiguration();
		pc.setReversed(reverse);
		pc.setFuzz(fuzzFactor);
		patchWorkspace(null, originalFiles, patch, expectedOutcomeFiles, pc);
	}

	/**
	 * Parses a workspace patch and applies the diffs to the appropriate files
	 * 
	 * @param msg
	 * @param originalFiles
	 * @param patch
	 * @param expectedOutcomeFiles
	 * @param patchConfiguration
	 *            The patch configuration to use. One of its parameters is fuzz
	 *            factor. If it equals <code>-1</code> it means that the fuzz
	 *            should be calculated automatically.
	 */
	private void patchWorkspace(String msg, String[] originalFiles, String patch, String[] expectedOutcomeFiles, PatchConfiguration patchConfiguration) {
		
		//ensure that we have the same number of input files as we have expected files
		Assert.assertEquals(originalFiles.length, expectedOutcomeFiles.length);
		
		// Parse the passed in patch and extract all the Diffs
		WorkspacePatcher patcher = new WorkspacePatcher();
		try {
			patcher.getConfiguration().setFuzz(patchConfiguration.getFuzz());
			patcher.getConfiguration().setIgnoreWhitespace(patchConfiguration.isIgnoreWhitespace());
			patcher.getConfiguration().setPrefixSegmentStripCount(patchConfiguration.getPrefixSegmentStripCount());
			patcher.parse(getReader(patch));
			patcher.setReversed(patchConfiguration.isReversed());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//Sort the diffs by project 
		FileDiff[] diffs= patcher.getDiffs();
		
		//Iterate through all of the original files, apply the diffs that belong to the file and compare
		//with the corresponding outcome file
		for (int i = 0; i < originalFiles.length; i++) {	
			LineReader lr= new LineReader(getReader(originalFiles[i]));
			List inLines= lr.readLines();
		
			FileDiffResult diffResult = patcher.getDiffResult(diffs[i]);
			diffResult.patch(inLines, null);
			
			LineReader expectedContents= new LineReader(getReader(expectedOutcomeFiles[i]));
			List expectedLines= expectedContents.readLines();
			
			Object[] expected= expectedLines.toArray();
			Object[] result= inLines.toArray();
			
			Assert.assertEquals(msg, expected.length, result.length);
			
			for (int j= 0; j < expected.length; j++)
				Assert.assertEquals(msg, expected[j], result[j]);
		}
	}
	
	private Bundle getBundle() {
		return CompareTestPlugin.getDefault().getBundle();
	}	
}

Back to the top