001: /*******************************************************************************
002: * Copyright (c) 2007 IBM Corporation and others. All rights reserved. This
003: * program and the accompanying materials are made available under the terms of
004: * the Eclipse Public License v1.0 which accompanies this distribution, and is
005: * available at http://www.eclipse.org/legal/epl-v10.html
006: *
007: * Contributors: IBM Corporation - initial API and implementation
008: ******************************************************************************/package org.eclipse.pde.build.tests;
009:
010: import java.io.*;
011: import java.lang.reflect.InvocationTargetException;
012: import java.net.URL;
013: import java.util.*;
014:
015: import junit.framework.TestCase;
016:
017: import org.apache.tools.ant.Project;
018: import org.apache.tools.ant.helper.AntXMLContext;
019: import org.apache.tools.ant.helper.ProjectHelper2;
020: import org.apache.tools.zip.ZipEntry;
021: import org.apache.tools.zip.ZipFile;
022: import org.eclipse.ant.core.AntRunner;
023: import org.eclipse.core.resources.*;
024: import org.eclipse.core.runtime.*;
025: import org.eclipse.pde.build.internal.tests.AntUtils;
026: import org.eclipse.pde.internal.build.AbstractScriptGenerator;
027: import org.eclipse.pde.internal.build.site.BuildTimeSiteFactory;
028: import org.eclipse.pde.internal.build.site.QualifierReplacer;
029: import org.eclipse.ui.dialogs.IOverwriteQuery;
030: import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
031: import org.eclipse.ui.wizards.datatransfer.ImportOperation;
032:
033: public abstract class PDETestCase extends TestCase {
034: public static final String PROJECT_NAME = "org.eclipse.pde.build.tests.builder";
035:
036: private IFolder buildFolder = null;
037:
038: protected void clearStatics() throws Exception {
039: AbstractScriptGenerator.getConfigInfos().clear();
040: BuildTimeSiteFactory.setInstalledBaseSite(null);
041: AbstractScriptGenerator.setForceUpdateJar(false);
042: //TODO: bug 192904, need to setGlobalQualifier to null
043: QualifierReplacer.setGlobalQualifier("");
044: }
045:
046: protected void runTest() throws Throwable {
047: super .runTest();
048:
049: //clean up after success
050: if (buildFolder != null && buildFolder.exists()) {
051: try {
052: buildFolder.delete(true, null);
053: } catch (CoreException e) {
054: }
055: }
056: }
057:
058: protected IProject newTest() throws Exception {
059: IProject builderProject = ResourcesPlugin.getWorkspace()
060: .getRoot().getProject(PROJECT_NAME);
061: if (!builderProject.exists()) {
062: builderProject.create(null);
063: }
064: if (!builderProject.isOpen())
065: builderProject.open(null);
066:
067: return builderProject;
068: }
069:
070: protected IFolder newTest(String resources) throws Exception {
071: clearStatics();
072:
073: IProject builderProject = newTest();
074:
075: // create build folder for this test
076: buildFolder = builderProject.getFolder(resources);
077: if (buildFolder.exists()) {
078: try {
079: buildFolder.delete(true, null);
080: buildFolder.create(true, true, null);
081: } catch (CoreException e) {
082: }
083: } else {
084: buildFolder.create(true, true, null);
085: }
086:
087: URL resource = FileLocator.find(Platform
088: .getBundle(Activator.PLUGIN_ID), new Path("/resources/"
089: + resources), null);
090: if (resource != null) {
091: String path = FileLocator.toFileURL(resource).getPath();
092:
093: IOverwriteQuery query = new IOverwriteQuery() {
094: public String queryOverwrite(String pathString) {
095: return ALL;
096: }
097: };
098: List files = new ArrayList(1);
099: files.add(new File(path));
100: ImportOperation op = new ImportOperation(new Path(
101: PROJECT_NAME),
102: FileSystemStructureProvider.INSTANCE, query, files);
103: op.setCreateContainerStructure(false);
104: op.run(null);
105: }
106:
107: return buildFolder;
108: }
109:
110: protected void runBuild(IFolder buildFolder) throws Exception {
111: URL resource = FileLocator.find(Platform
112: .getBundle("org.eclipse.pde.build"), new Path(
113: "/scripts/build.xml"), null);
114: String buildXMLPath = FileLocator.toFileURL(resource).getPath();
115:
116: runAntScript(buildXMLPath, new String[] { "main" }, buildFolder
117: .getLocation().toOSString(), null);
118: }
119:
120: protected void runProductBuild(IFolder buildFolder)
121: throws Exception {
122: URL resource = FileLocator.find(Platform
123: .getBundle("org.eclipse.pde.build"), new Path(
124: "/scripts/productBuild/productBuild.xml"), null);
125: String buildXMLPath = FileLocator.toFileURL(resource).getPath();
126:
127: runAntScript(buildXMLPath, new String[] { "main" }, buildFolder
128: .getLocation().toOSString(), null);
129: }
130:
131: protected void generateScripts(IFolder buildFolder,
132: Properties generateProperties) throws Exception {
133: URL resource = FileLocator.find(Platform
134: .getBundle("org.eclipse.pde.build"), new Path(
135: "/scripts/genericTargets.xml"), null);
136: String buildXMLPath = FileLocator.toFileURL(resource).getPath();
137:
138: runAntScript(buildXMLPath, new String[] { "generateScript" },
139: buildFolder.getLocation().toOSString(),
140: generateProperties);
141: }
142:
143: protected void runAntScript(String script, String[] targets,
144: String antHome, Properties additionalProperties)
145: throws Exception {
146: runAntScript(script, targets, antHome, additionalProperties,
147: null, null);
148: }
149:
150: protected void runAntScript(String script, String[] targets,
151: String antHome, Properties additionalProperties,
152: String listener, String logger) throws Exception {
153: String[] args = createAntRunnerArgs(script, targets, antHome,
154: additionalProperties, listener, logger);
155: try {
156: AntRunner runner = new AntRunner();
157: runner.run((Object) args);
158: } catch (InvocationTargetException e) {
159: Throwable target = e.getTargetException();
160: if (target instanceof Exception)
161: throw (Exception) target;
162: throw e;
163: }
164: }
165:
166: protected String[] createAntRunnerArgs(String script,
167: String[] targets, String antHome,
168: Properties additionalProperties, String listener,
169: String logger) {
170: int numArgs = 5
171: + targets.length
172: + (additionalProperties != null ? additionalProperties
173: .size() : 0);
174: if (listener != null)
175: numArgs += 2;
176: if (logger != null)
177: numArgs += 2;
178: String[] args = new String[numArgs];
179: int idx = 0;
180: args[idx++] = "-buildfile";
181: args[idx++] = script;
182: args[idx++] = "-logfile";
183: args[idx++] = antHome + "/log.log";
184: args[idx++] = "-Dbuilder=" + antHome;
185: if (listener != null) {
186: args[idx++] = "-listener";
187: args[idx++] = listener;
188: }
189: if (logger != null) {
190: args[idx++] = "-logger";
191: args[idx++] = logger;
192: }
193: if (additionalProperties != null
194: && additionalProperties.size() > 0) {
195: Enumeration e = additionalProperties.keys();
196: while (e.hasMoreElements()) {
197: String key = (String) e.nextElement();
198: String value = additionalProperties.getProperty(key);
199: if (value.length() > 0)
200: args[idx++] = "-D" + key + "="
201: + additionalProperties.getProperty(key);
202: else
203: args[idx++] = "";
204: }
205: }
206:
207: for (int i = 0; i < targets.length; i++) {
208: args[idx++] = targets[i];
209: }
210: return args;
211: }
212:
213: /**
214: * Assert that the zip file contains at least the given entries
215: * @param buildFolder
216: * @param archive
217: * @param entries
218: * @throws Exception
219: */
220: public static void assertZipContents(IFolder buildFolder,
221: String archive, Set entries) throws Exception {
222: assertZipContents(buildFolder, archive, entries, true);
223: }
224:
225: public static void assertZipContents(IFolder buildFolder,
226: String archive, Set entries, boolean assertEmpty)
227: throws Exception {
228: File folder = new File(buildFolder.getLocation().toOSString());
229: File archiveFile = new File(folder, archive);
230: assertTrue(archiveFile.exists());
231:
232: ZipFile zip = new ZipFile(archiveFile);
233: try {
234: Enumeration e = zip.getEntries();
235: while (e.hasMoreElements() && entries.size() > 0) {
236: ZipEntry entry = (ZipEntry) e.nextElement();
237: String name = entry.getName();
238: if (entries.contains(name)) {
239: if (!entry.isDirectory())
240: assertTrue(entry.getSize() > 0);
241: entries.remove(name);
242: }
243: }
244: } finally {
245: zip.close();
246: }
247: if (assertEmpty)
248: assertTrue(entries.size() == 0);
249: }
250:
251: /**
252: * Assert that the given resource exists and has size > 0
253: * @param buildFolder
254: * @param fileName
255: * @throws Exception
256: */
257: public static void assertResourceFile(IFolder buildFolder,
258: String fileName) throws Exception {
259: buildFolder.refreshLocal(IResource.DEPTH_INFINITE, null);
260: IFile file = buildFolder.getFile(fileName);
261: assertTrue(file.exists());
262:
263: File ioFile = file.getLocation().toFile();
264: assertTrue(ioFile.length() > 0);
265: }
266:
267: /**
268: * Assert that the given log file contains the given message
269: * The message is expected to be contained on a single line
270: * @param log
271: * @param msg
272: * @throws Exception
273: */
274: public static void assertLogContainsLine(IFile log, String msg)
275: throws Exception {
276: assertLogContainsLines(log, new String[] { msg });
277: }
278:
279: /**
280: * Assert that the given log file contains the given lines
281: * Lines are expected to appear in order
282: * @param log
283: * @param lines
284: * @throws Exception
285: */
286: public static void assertLogContainsLines(IFile log, String[] lines)
287: throws Exception {
288: assertNotNull(log);
289: assertTrue(log.exists());
290:
291: File logFile = log.getLocation().toFile();
292: assertTrue(logFile.length() > 0);
293:
294: int idx = 0;
295: BufferedReader reader = new BufferedReader(new FileReader(
296: logFile));
297: while (reader.ready()) {
298: String line = reader.readLine();
299: if (line.indexOf(lines[idx]) >= 0) {
300: if (++idx >= lines.length) {
301: reader.close();
302: return;
303: }
304: }
305: }
306: reader.close();
307: assertTrue(false);
308: }
309:
310: /**
311: * assert that the given xml file exists, has size > 0 and is a valid ant script
312: * @param buildXML
313: * @throws Exception
314: */
315: public static Project assertValidAntScript(IFile buildXML)
316: throws Exception {
317: assertResourceFile((IFolder) buildXML.getParent(), buildXML
318: .getName());
319:
320: // Parse the build file using ant
321: ProjectHelper2 helper = new ProjectHelper2();
322: Project project = new Project();
323: project.addReference("ant.projectHelper", helper); //$NON-NLS-1$
324:
325: AntXMLContext context = new AntXMLContext(project);
326: project.addReference("ant.parsing.context", context);
327: project.addReference("ant.targets", context.getTargets());
328: context.setCurrentTargets(new HashMap());
329:
330: AntUtils.setupProject(project);
331: project.init();
332:
333: // this will throw an exception if it is not a valid ant script
334: helper.parse(project, buildXML.getLocation().toFile(),
335: new ProjectHelper2.RootHandler(context,
336: new ProjectHelper2.MainHandler()));
337: return project;
338: }
339: }
|