KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > datatransfer > ExportUtil


1 /*******************************************************************************
2  * Copyright (c) 2004, 2007 Richard Hoefter and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * Richard Hoefter (richard.hoefter@web.de) - initial API and implementation, bug 95300, bug 95297, bug 128104
10  * IBM Corporation - nlsing and incorporating into Eclipse.
11  * Class created from combination of all utility classes of contribution
12  * Bug 177833
13  *******************************************************************************/

14
15 package org.eclipse.ant.internal.ui.datatransfer;
16
17 import java.io.BufferedReader JavaDoc;
18 import java.io.ByteArrayInputStream JavaDoc;
19 import java.io.File JavaDoc;
20 import java.io.FileNotFoundException JavaDoc;
21 import java.io.FileReader JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.StringWriter JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.Comparator JavaDoc;
27 import java.util.HashSet JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.LinkedList JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33 import java.util.TreeSet JavaDoc;
34 import java.util.regex.Matcher JavaDoc;
35 import java.util.regex.Pattern JavaDoc;
36
37 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
38 import javax.xml.parsers.ParserConfigurationException JavaDoc;
39 import javax.xml.transform.OutputKeys JavaDoc;
40 import javax.xml.transform.Result JavaDoc;
41 import javax.xml.transform.Source JavaDoc;
42 import javax.xml.transform.Transformer JavaDoc;
43 import javax.xml.transform.TransformerConfigurationException JavaDoc;
44 import javax.xml.transform.TransformerException JavaDoc;
45 import javax.xml.transform.TransformerFactory JavaDoc;
46 import javax.xml.transform.TransformerFactoryConfigurationError JavaDoc;
47 import javax.xml.transform.dom.DOMSource JavaDoc;
48 import javax.xml.transform.stream.StreamResult JavaDoc;
49
50 import org.eclipse.ant.internal.ui.AntUIPlugin;
51 import org.eclipse.core.resources.IFile;
52 import org.eclipse.core.resources.IMarker;
53 import org.eclipse.core.resources.IProject;
54 import org.eclipse.core.resources.IResource;
55 import org.eclipse.core.resources.IWorkspace;
56 import org.eclipse.core.resources.IWorkspaceRoot;
57 import org.eclipse.core.resources.ResourcesPlugin;
58 import org.eclipse.core.runtime.CoreException;
59 import org.eclipse.core.runtime.IAdaptable;
60 import org.eclipse.core.runtime.IPath;
61 import org.eclipse.core.runtime.IStatus;
62 import org.eclipse.core.runtime.Path;
63 import org.eclipse.core.runtime.Status;
64 import org.eclipse.core.variables.VariablesPlugin;
65 import org.eclipse.jdt.core.Flags;
66 import org.eclipse.jdt.core.IClassFile;
67 import org.eclipse.jdt.core.IClasspathEntry;
68 import org.eclipse.jdt.core.ICompilationUnit;
69 import org.eclipse.jdt.core.IJavaElement;
70 import org.eclipse.jdt.core.IJavaModel;
71 import org.eclipse.jdt.core.IJavaModelMarker;
72 import org.eclipse.jdt.core.IJavaProject;
73 import org.eclipse.jdt.core.IMethod;
74 import org.eclipse.jdt.core.IPackageFragmentRoot;
75 import org.eclipse.jdt.core.IRegion;
76 import org.eclipse.jdt.core.ISourceReference;
77 import org.eclipse.jdt.core.IType;
78 import org.eclipse.jdt.core.JavaCore;
79 import org.eclipse.jdt.core.JavaModelException;
80 import org.eclipse.jdt.core.Signature;
81 import org.eclipse.jdt.core.search.IJavaSearchConstants;
82 import org.eclipse.jdt.core.search.IJavaSearchScope;
83 import org.eclipse.jdt.core.search.SearchEngine;
84 import org.eclipse.jdt.core.search.SearchMatch;
85 import org.eclipse.jdt.core.search.SearchParticipant;
86 import org.eclipse.jdt.core.search.SearchPattern;
87 import org.eclipse.jdt.core.search.SearchRequestor;
88 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
89 import org.eclipse.jface.viewers.ISelection;
90 import org.eclipse.jface.viewers.IStructuredSelection;
91 import org.eclipse.swt.widgets.Shell;
92 import org.eclipse.ui.IFileEditorInput;
93 import org.w3c.dom.Document JavaDoc;
94 import org.xml.sax.SAXException JavaDoc;
95
96 /**
97  * Eclipse API shortcuts.
98  */

99 public class ExportUtil
100 {
101     private ExportUtil()
102     {
103     }
104
105     /**
106      * Get resource from selection.
107      */

108     public static IResource getResource(ISelection selection)
109     {
110         if (selection instanceof IStructuredSelection)
111         {
112             for (Iterator JavaDoc iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();)
113             {
114                 IAdaptable adaptable = (IAdaptable) iter.next();
115                 return (IResource) adaptable.getAdapter(IResource.class);
116             }
117         }
118         return null;
119     }
120
121     /**
122      * Get Java project from resource.
123      */

124     public static IJavaProject getJavaProjectByName(String JavaDoc name)
125     {
126         IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
127         IJavaModel javaModel = JavaCore.create(rootWorkspace);
128         IJavaProject[] javaProjects;
129         try
130         {
131             javaProjects = javaModel.getJavaProjects();
132         }
133         catch (JavaModelException e)
134         {
135             return null;
136         }
137         for (int i = 0; i < javaProjects.length; i++)
138         {
139             IJavaProject javaProject = javaProjects[i];
140             if (name.equals(javaProject.getProject().getName()))
141             {
142                 return javaProject;
143             }
144         }
145         return null;
146     }
147
148     /**
149      * Get project root for given project.
150      */

151     public static String JavaDoc getProjectRoot(IJavaProject project)
152     {
153         return project.getResource().getLocation().toString();
154     }
155
156     /**
157      * Convert Eclipse path to absolute filename.
158      * @param file Project root optionally followed by resource name.
159      * An absolute path is simply converted to a string.
160      * @return full qualified path
161      */

162     public static String JavaDoc resolve(IPath file)
163     {
164         if (file == null)
165         {
166             return null;
167         }
168         try
169         {
170             IFile f = ResourcesPlugin.getWorkspace().getRoot().getFile(file);
171             IPath p = f.getLocation();
172             return (p != null) ? p.toString() : f.toString();
173         }
174         catch (IllegalArgumentException JavaDoc e)
175         {
176             // resource is missing
177
String JavaDoc projectName = ExportUtil.removePrefix(file.toString(), "/"); //$NON-NLS-1$
178
IJavaProject project = ExportUtil.getJavaProjectByName(projectName);
179             return ExportUtil.getProjectRoot(project);
180         }
181     }
182
183     /**
184      * Get Java project for given root.
185      */

186     public static IJavaProject getJavaProject(String JavaDoc root)
187     {
188         IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
189         IJavaModel javaModel = JavaCore.create(rootWorkspace);
190         IJavaProject[] javaProjects;
191         try
192         {
193             javaProjects = javaModel.getJavaProjects();
194         }
195         catch (JavaModelException e)
196         {
197             return null;
198         }
199         for (int i = 0; i < javaProjects.length; i++)
200         {
201             IJavaProject javaProject = javaProjects[i];
202             if (root.equals(javaProject.getPath().toString()))
203             {
204                 return javaProject;
205             }
206         }
207         return null;
208     }
209
210     /**
211      * Remove project root from given project file.
212      */

213     public static String JavaDoc removeProjectRoot(String JavaDoc file, IProject project)
214     {
215         String JavaDoc res = removePrefix(file, '/' + project.getName() + '/');
216         if (res.equals('/' + project.getName()))
217         {
218             return "."; //$NON-NLS-1$
219
}
220         return res;
221     }
222
223     /**
224      * Remove project root from given project file.
225      * @param newProjectRoot replace project root, e.g. with a variable ${project.location}
226      */

227     public static String JavaDoc replaceProjectRoot(String JavaDoc file, IProject project, String JavaDoc newProjectRoot)
228     {
229         String JavaDoc res = removeProjectRoot(file, project);
230         if (res.equals(".")) //$NON-NLS-1$
231
{
232             return newProjectRoot;
233         }
234         if (newProjectRoot == null)
235         {
236             return res;
237         }
238         if (!res.equals(file))
239         {
240             return newProjectRoot + '/' + res;
241         }
242         return res;
243     }
244     
245     /**
246      * Get for given project all directly dependent projects.
247      *
248      * @return set of IJavaProject objects
249      */

250     public static List JavaDoc getClasspathProjects(IJavaProject project) throws JavaModelException
251     {
252         List JavaDoc projects = new ArrayList JavaDoc();
253         IClasspathEntry entries[] = project.getRawClasspath();
254         addClasspathProjects(projects, entries);
255         return sortProjectsUsingBuildOrder(projects);
256     }
257     
258     private static void addClasspathProjects(List JavaDoc projects, IClasspathEntry[] entries) {
259         for (int i = 0; i < entries.length; i++)
260         {
261             IClasspathEntry classpathEntry = entries[i];
262             if (classpathEntry.getContentKind() == IPackageFragmentRoot.K_SOURCE &&
263                 classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
264                     // found required project on build path
265
String JavaDoc subProjectRoot = classpathEntry.getPath().toString();
266                     IJavaProject subProject = ExportUtil.getJavaProject(subProjectRoot);
267                     // is project available in workspace
268
if (subProject != null)
269                     {
270                         projects.add(subProject);
271                     }
272             }
273         }
274     }
275     
276     /**
277      * Get for given project all directly and indirectly dependent projects.
278      *
279      * @return set of IJavaProject objects
280      */

281     public static List JavaDoc getClasspathProjectsRecursive(IJavaProject project) throws JavaModelException
282     {
283         LinkedList JavaDoc result = new LinkedList JavaDoc();
284         getClasspathProjectsRecursive(project, result);
285         return sortProjectsUsingBuildOrder(result);
286     }
287     
288     private static void getClasspathProjectsRecursive(IJavaProject project, LinkedList JavaDoc result) throws JavaModelException
289     {
290         List JavaDoc projects = getClasspathProjects(project);
291         for (Iterator JavaDoc iter = projects.iterator(); iter.hasNext();)
292         {
293             IJavaProject javaProject = (IJavaProject) iter.next();
294             if (!result.contains(javaProject)) {
295                 result.addFirst(javaProject);
296                 getClasspathProjectsRecursive(javaProject, result); // recursion
297
}
298         }
299     }
300     
301     /**
302      * Sort projects according to General -&gt; Workspace -&gt; Build Order.
303      * @param projects list of IJavaProject objects
304      * @return list of IJavaProject objects with new order
305      */

306     private static List JavaDoc sortProjectsUsingBuildOrder(List JavaDoc javaProjects) {
307         if (javaProjects.isEmpty()) {
308             return javaProjects;
309         }
310         List JavaDoc result = new ArrayList JavaDoc(javaProjects.size());
311         IWorkspace workspace = ResourcesPlugin.getWorkspace();
312         String JavaDoc[] buildOrder= workspace.getDescription().getBuildOrder();
313         if (buildOrder == null) {//default build order
314
IProject[] projects= new IProject[javaProjects.size()];
315             int i= 0;
316             for (Iterator JavaDoc iter = javaProjects.iterator(); iter.hasNext(); i++) {
317                 IJavaProject javaProject = (IJavaProject) iter.next();
318                 projects[i]= javaProject.getProject();
319             }
320             IWorkspace.ProjectOrder po = ResourcesPlugin.getWorkspace().computeProjectOrder(projects);
321             projects=po.projects;
322             buildOrder= new String JavaDoc[projects.length];
323             for (i = 0; i < projects.length; i++) {
324                 buildOrder[i]= projects[i].getName();
325             }
326         }
327         
328         for (int i = 0; i < buildOrder.length && !javaProjects.isEmpty(); i++) {
329             String JavaDoc projectName = buildOrder[i];
330             for (Iterator JavaDoc iter = javaProjects.iterator(); iter.hasNext();) {
331                 IJavaProject javaProject = (IJavaProject) iter.next();
332                 if (javaProject.getProject().getName().equals(projectName)) {
333                     result.add(javaProject);
334                     iter.remove();
335                 }
336             }
337         }
338         //add any remaining projects not specified in the build order
339
result.addAll(javaProjects);
340         return result;
341     }
342     
343     /**
344      * Check if given project has a cyclic dependency.
345      *
346      * <p>See org.eclipse.jdt.core.tests.model.ClasspathTests.numberOfCycleMarkers.
347      */

348     public static boolean hasCyclicDependency(IJavaProject javaProject)
349             throws CoreException
350     {
351         IMarker[] markers = javaProject.getProject().findMarkers(
352                 IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false,
353                 IResource.DEPTH_ONE);
354         for (int i = 0; i < markers.length; i++)
355         {
356             IMarker marker = markers[i];
357             String JavaDoc cycleAttr = (String JavaDoc) marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED);
358             if (cycleAttr != null && cycleAttr.equals("true")) //$NON-NLS-1$
359
{
360                 return true;
361             }
362         }
363         return false;
364     }
365
366     /**
367      * Find JUnit tests. Same tests are also returned by Eclipse run configuration wizard.
368      *
369      * <p>NOTE: Copied from <code>org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration#findTestsInContainer}</code>
370      * to use non-api functionality
371      *
372      * @param containerHandle project, package or source folder
373      */

374     public static IType[] findTestsInContainer(String JavaDoc containerHandle)
375     {
376         IJavaElement container= JavaCore.create(containerHandle);
377         if (container == null) {
378             return new IType[0];
379         }
380         final Object JavaDoc[] elements = new Object JavaDoc[] { container };
381         final Set JavaDoc result= new HashSet JavaDoc();
382         if (elements.length > 0) {
383             doFindTests(elements, result);
384         }
385         return (IType[]) result.toArray(new IType[result.size()]) ;
386     }
387     
388     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
389
// to avoid dependency to other component
390
private static class JUnitSearchResultCollector extends SearchRequestor {
391         List JavaDoc fList;
392         Set JavaDoc fFailed = new HashSet JavaDoc();
393         Set JavaDoc fMatches = new HashSet JavaDoc();
394         
395         public JUnitSearchResultCollector(List JavaDoc list) {
396             fList = list;
397         }
398         
399         public void acceptSearchMatch(SearchMatch match) throws CoreException {
400             Object JavaDoc enclosingElement= match.getElement();
401             if (!(enclosingElement instanceof IMethod))
402                 return;
403             
404             IMethod method= (IMethod)enclosingElement;
405             
406             IType declaringType= method.getDeclaringType();
407             if (fMatches.contains(declaringType) || fFailed.contains(declaringType))
408                 return;
409             if (!hasSuiteMethod(declaringType) && !isTestType(declaringType)) {
410                 fFailed.add(declaringType);
411                 return;
412             }
413             fMatches.add(declaringType);
414         }
415         
416         public void endReporting() {
417             fList.addAll(fMatches);
418         }
419     }
420     
421     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
422
private static List JavaDoc searchMethod(final IJavaSearchScope scope) throws CoreException {
423         final List JavaDoc typesFound= new ArrayList JavaDoc(200);
424         searchMethod(typesFound, scope);
425         return typesFound;
426     }
427
428     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
429
private static List JavaDoc searchMethod(final List JavaDoc v, IJavaSearchScope scope) throws CoreException {
430         SearchRequestor requestor= new JUnitSearchResultCollector(v);
431         int matchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_ERASURE_MATCH;
432         SearchPattern suitePattern= SearchPattern.createPattern("suite() Test", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule); //$NON-NLS-1$
433
SearchParticipant[] participants= new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
434         new SearchEngine().search(suitePattern, participants, scope, requestor, null);
435         return v;
436     }
437
438     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
439
private static void doFindTests(Object JavaDoc[] elements, Set JavaDoc result) {
440         int nElements= elements.length;
441         for (int i = 0; i < nElements; i++) {
442             try {
443                 collectTypes(elements[i], result);
444             } catch (CoreException e) {
445                 AntUIPlugin.log(e.getStatus());
446             }
447         }
448     }
449
450     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
451
private static void collectTypes(Object JavaDoc element, Set JavaDoc result) throws CoreException/*, InvocationTargetException*/ {
452         element = computeScope(element);
453         while ((element instanceof ISourceReference) && !(element instanceof ICompilationUnit)) {
454             if (element instanceof IType) {
455                 if (hasSuiteMethod((IType)element) || isTestType((IType)element)) {
456                     result.add(element);
457                     return;
458                 }
459             }
460             element = ((IJavaElement)element).getParent();
461         }
462         if (element instanceof ICompilationUnit) {
463             ICompilationUnit cu= (ICompilationUnit)element;
464             IType[] types= cu.getAllTypes();
465
466             for (int i= 0; i < types.length; i++) {
467                 if (hasSuiteMethod(types[i]) || isTestType(types[i]))
468                     result.add(types[i]);
469             }
470         }
471         else if (element instanceof IJavaElement) {
472             List JavaDoc testCases= findTestCases((IJavaElement)element);
473             List JavaDoc suiteMethods= searchSuiteMethods((IJavaElement)element);
474             while (!suiteMethods.isEmpty()) {
475                 if (!testCases.contains(suiteMethods.get(0))) {
476                     testCases.add(suiteMethods.get(0));
477                 }
478                 suiteMethods.remove(0);
479             }
480             result.addAll(testCases);
481         }
482     }
483
484     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
485
private static List JavaDoc findTestCases(IJavaElement element) throws JavaModelException {
486         List JavaDoc found = new ArrayList JavaDoc();
487         IJavaProject javaProject= element.getJavaProject();
488
489         if (javaProject == null) // bug 120804
490
return found;
491
492         IType testCaseType = testCaseType(javaProject);
493         if (testCaseType == null)
494             return found;
495         
496         IType[] subtypes= javaProject.newTypeHierarchy(testCaseType, getRegion(javaProject), null).getAllSubtypes(testCaseType);
497             
498         if (subtypes == null)
499             throw new JavaModelException(new CoreException(new Status(IStatus.ERROR, AntUIPlugin.PI_ANTUI, IJavaLaunchConfigurationConstants.ERR_UNSPECIFIED_MAIN_TYPE, null/*JUnitMessages.JUnitBaseLaunchConfiguration_error_notests*/, null)));
500
501         for (int i = 0; i < subtypes.length; i++) {
502             try {
503                 if (element.equals(subtypes[i].getAncestor(element.getElementType())) && hasValidModifiers(subtypes[i]))
504                     found.add(subtypes[i]);
505             } catch (JavaModelException e) {
506                 AntUIPlugin.log(e.getStatus());
507             }
508         }
509         return found;
510     }
511
512     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
513
private static IType testCaseType(IJavaProject javaProject) {
514         try {
515             return javaProject.findType("junit.framework.TestCase"); //$NON-NLS-1$
516
} catch (JavaModelException e) {
517             AntUIPlugin.log(e.getStatus());
518             return null;
519         }
520     }
521
522     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
523
private static IRegion getRegion(IJavaProject javaProject) throws JavaModelException{
524         IRegion region = JavaCore.newRegion();
525         IJavaElement[] elements= javaProject.getChildren();
526         for(int i=0; i<elements.length; i++) {
527             if (((IPackageFragmentRoot)elements[i]).isArchive())
528                 continue;
529             region.add(elements[i]);
530         }
531         return region;
532     }
533
534     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
535
private static Object JavaDoc computeScope(Object JavaDoc element) {
536         if (element instanceof IFileEditorInput)
537             element= ((IFileEditorInput)element).getFile();
538         if (element instanceof IResource)
539             element= JavaCore.create((IResource)element);
540         if (element instanceof IClassFile) {
541             IClassFile cf= (IClassFile)element;
542             element= cf.getType();
543         }
544         return element;
545     }
546
547     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
548
private static List JavaDoc searchSuiteMethods(IJavaElement element) throws CoreException {
549         // fix for bug 36449 JUnit should constrain tests to selected project [JUnit]
550
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { element },
551                 IJavaSearchScope.SOURCES);
552         return searchMethod(scope);
553     }
554
555     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
556
private static boolean hasSuiteMethod(IType type) throws JavaModelException {
557         IMethod method= type.getMethod("suite", new String JavaDoc[0]); //$NON-NLS-1$
558
if (method == null || !method.exists())
559             return false;
560         
561         if (!Flags.isStatic(method.getFlags()) ||
562             !Flags.isPublic(method.getFlags()) ||
563             !Flags.isPublic(method.getDeclaringType().getFlags())) {
564             return false;
565         }
566         if (!Signature.getSimpleName(Signature.toString(method.getReturnType())).equals("Test" /*JUnitPlugin.SIMPLE_TEST_INTERFACE_NAME*/)) { //$NON-NLS-1$
567
return false;
568         }
569         return true;
570     }
571
572     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
573
private static boolean isTestType(IType type) throws JavaModelException {
574         if (!hasValidModifiers(type))
575             return false;
576         
577         IType[] interfaces= type.newSupertypeHierarchy(null).getAllSuperInterfaces(type);
578         for (int i= 0; i < interfaces.length; i++)
579             if(interfaces[i].getFullyQualifiedName('.').equals("junit.framework.Test" /*JUnitPlugin.TEST_INTERFACE_NAME*/)) //$NON-NLS-1$
580
return true;
581         return false;
582     }
583
584     // copied from org.eclipse.jdt.internal.junit.util.TestSearchEngine
585
private static boolean hasValidModifiers(IType type) throws JavaModelException {
586         if (Flags.isAbstract(type.getFlags()))
587             return false;
588         if (!Flags.isPublic(type.getFlags()))
589             return false;
590         return true;
591     }
592
593     /**
594      * Compares projects by project name.
595      */

596     public static synchronized Comparator JavaDoc getJavaProjectComparator()
597     {
598         if (javaProjectComparator == null)
599         {
600             javaProjectComparator = new JavaProjectComparator();
601         }
602         return javaProjectComparator;
603     }
604     
605     private static Comparator JavaDoc javaProjectComparator;
606     
607     private static class JavaProjectComparator implements Comparator JavaDoc
608     {
609         public int compare(Object JavaDoc o1, Object JavaDoc o2)
610         {
611             IJavaProject j1 = (IJavaProject) o1;
612             IJavaProject j2 = (IJavaProject) o2;
613             return j1.getProject().getName().compareTo(j2.getProject().getName());
614         }
615         
616         public boolean equals(Object JavaDoc obj)
617         {
618             if (obj == null)
619             {
620                 return false;
621             }
622             return compare(this, obj) == 0;
623         }
624     }
625     
626     /**
627      * Compares objects by classname.
628      */

629     public static synchronized Comparator JavaDoc getClassnameComparator()
630     {
631         if (classnameComparator == null)
632         {
633             classnameComparator = new ClassnameComparator();
634         }
635         return classnameComparator;
636     }
637     
638     private static Comparator JavaDoc classnameComparator;
639     
640     private static class ClassnameComparator implements Comparator JavaDoc
641     {
642         public int compare(Object JavaDoc o1, Object JavaDoc o2)
643         {
644             return o1.getClass().getName().compareTo(o2.getClass().getName());
645         }
646
647         public boolean equals(Object JavaDoc obj)
648         {
649             if (obj == null)
650             {
651                 return false;
652             }
653             return compare(this, obj) == 0;
654         }
655     }
656
657     /**
658      * Compares IFile objects.
659      */

660     public static synchronized Comparator JavaDoc getIFileComparator()
661     {
662         if (fileComparator == null)
663         {
664             fileComparator = new IFileComparator();
665         }
666         return fileComparator;
667     }
668     
669     private static Comparator JavaDoc fileComparator;
670     
671     private static class IFileComparator implements Comparator JavaDoc
672     {
673         public int compare(Object JavaDoc o1, Object JavaDoc o2)
674         {
675             IFile f1 = (IFile) o1;
676             IFile f2 = (IFile) o2;
677             return f1.toString().compareTo(f2.toString());
678         }
679
680         public boolean equals(Object JavaDoc obj)
681         {
682             if (obj == null)
683             {
684                 return false;
685             }
686             return compare(this, obj) == 0;
687         }
688     }
689     
690     /**
691      * Compares IType objects.
692      */

693     public static synchronized Comparator JavaDoc getITypeComparator()
694     {
695         if (typeComparator == null)
696         {
697             typeComparator = new TypeComparator();
698         }
699         return typeComparator;
700     }
701     
702     private static Comparator JavaDoc typeComparator;
703     
704     private static class TypeComparator implements Comparator JavaDoc
705     {
706         public int compare(Object JavaDoc o1, Object JavaDoc o2)
707         {
708             IType t1 = (IType) o1;
709             IType t2 = (IType) o2;
710             return t1.getFullyQualifiedName().compareTo(t2.getFullyQualifiedName());
711         }
712
713         public boolean equals(Object JavaDoc obj)
714         {
715             if (obj == null)
716             {
717                 return false;
718             }
719             return compare(this, obj) == 0;
720         }
721     }
722
723     /**
724      * Platform specific newline character(s).
725      */

726     public static final String JavaDoc NEWLINE = System.getProperty("line.separator"); //$NON-NLS-1$
727

728     public static String JavaDoc removePrefix(String JavaDoc s, String JavaDoc prefix)
729     {
730         if (s == null)
731         {
732             return null;
733         }
734         if (s.startsWith(prefix))
735         {
736             return s.substring(prefix.length());
737         }
738         return s;
739     }
740
741     /**
742      * Remove suffix from given string.
743      */

744     public static String JavaDoc removeSuffix(String JavaDoc s, String JavaDoc suffix)
745     {
746         if (s == null)
747         {
748             return null;
749         }
750         if (s.endsWith(suffix))
751         {
752             return s.substring(0, s.length() - suffix.length());
753         }
754         return s;
755     }
756
757     /**
758      * Remove prefix and suffix from given string.
759      */

760     public static String JavaDoc removePrefixAndSuffix(String JavaDoc s, String JavaDoc prefix, String JavaDoc suffix)
761     {
762         return removePrefix(removeSuffix(s, suffix), prefix);
763     }
764     
765     /**
766      * Convert document to formatted XML string.
767      */

768     public static String JavaDoc toString(Document JavaDoc doc) throws TransformerConfigurationException JavaDoc, TransformerFactoryConfigurationError JavaDoc, TransformerException JavaDoc
769     {
770         // NOTE: There are different transformer implementations in the wild, which are configured differently
771
// regarding the indent size:
772
// Java 1.4: org.apache.xalan.transformer.TransformerIdentityImpl
773
// Java 1.5: com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
774

775         StringWriter JavaDoc writer = new StringWriter JavaDoc();
776         Source JavaDoc source = new DOMSource JavaDoc(doc);
777         Result JavaDoc result = new StreamResult JavaDoc(writer);
778         TransformerFactory JavaDoc factory = TransformerFactory.newInstance();
779         boolean indentFallback = false;
780         try
781         {
782             // indent using TransformerImpl
783
factory.setAttribute("indent-number", "4"); //$NON-NLS-1$ //$NON-NLS-2$
784
}
785         catch (IllegalArgumentException JavaDoc e)
786         {
787             // option not supported, set indent size below
788
indentFallback = true;
789         }
790         Transformer JavaDoc transformer = factory.newTransformer();
791         transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
792
if (indentFallback)
793         {
794             // indent using TransformerIdentityImpl
795
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
796
}
797         transformer.transform(source, result);
798         return writer.toString();
799     }
800    
801     /**
802      * Read XML file.
803      */

804     public static Document JavaDoc parseXmlFile(File JavaDoc file) throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc
805     {
806         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
807         factory.setValidating(false);
808         Document JavaDoc doc = factory.newDocumentBuilder().parse(file);
809         return doc;
810     }
811
812     /**
813      * Read XML string.
814      */

815     public static Document JavaDoc parseXmlString(String JavaDoc s) throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc
816     {
817         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
818         factory.setValidating(false);
819         Document JavaDoc doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream JavaDoc(s.getBytes()));
820         return doc;
821     }
822
823     /**
824      * Converts collection to a separated string.
825      * @param c collection
826      * @param separator string to separate items
827      * @return collection items separated with given separator
828      */

829     public static String JavaDoc toString(Collection JavaDoc c, String JavaDoc separator)
830     {
831         StringBuffer JavaDoc b = new StringBuffer JavaDoc();
832         for (Iterator JavaDoc iter = c.iterator(); iter.hasNext();)
833         {
834             b.append((String JavaDoc) iter.next());
835             b.append(separator);
836         }
837         if (c.size() > 0) {
838             b.delete(b.length() - separator.length(), b.length());
839         }
840         return b.toString();
841     }
842
843     /**
844      * Remove duplicates preserving original order.
845      * @param l list to remove duplicates from
846      * @return new list without duplicates
847      */

848     public static List JavaDoc removeDuplicates(List JavaDoc l)
849     {
850         List JavaDoc res = new ArrayList JavaDoc();
851         for (Iterator JavaDoc iter = l.iterator(); iter.hasNext();)
852         {
853             Object JavaDoc element = iter.next();
854             if (!res.contains(element))
855             {
856                 res.add(element);
857             }
858         }
859         return res;
860     }
861
862     /**
863      * Check if given file exists that was not written by this export.
864      */

865     public static boolean existsUserFile(String JavaDoc filename)
866     {
867         File JavaDoc buildFile = new File JavaDoc(filename);
868         if (buildFile.exists())
869         {
870             BufferedReader JavaDoc in = null;
871             try
872             {
873                 in = new BufferedReader JavaDoc(new FileReader JavaDoc(buildFile));
874                 int i = BuildFileCreator.WARNING.indexOf(NEWLINE);
875                 String JavaDoc warning = BuildFileCreator.WARNING.substring(0, i);
876                 String JavaDoc line;
877                 while ((line = in.readLine()) != null)
878                 {
879                     if (line.indexOf(warning) != -1)
880                     {
881                         return false;
882                     }
883                 }
884                 return true;
885             } catch (FileNotFoundException JavaDoc e) {
886                return false;
887             } catch (IOException JavaDoc e) {
888                return false;
889             } finally
890             {
891                 try
892                 {
893                     if (in != null)
894                     {
895                         in.close();
896                     }
897                 }
898                 catch (IOException JavaDoc e)
899                 {
900                     // ignore
901
}
902             }
903         }
904         return false;
905     }
906
907     /**
908      * Request write access to given file.
909      * Depending on the version control plug-in opens a confirm checkout dialog.
910      *
911      * @param shell parent instance for dialogs
912      * @param file file to request write access for
913      * @return <code>true</code> if user confirmed checkout
914      */

915     public static boolean validateEdit(Shell shell, IFile file) {
916         return file.getWorkspace().validateEdit(new IFile[] {file}, shell).isOK();
917     }
918     
919     /**
920      * Request write access to given files.
921      * Depending on the version control plug-in opens a confirm checkout dialog.
922      *
923      * @param shell parent instance for dialogs
924      * @return <code>IFile</code> objects for which user confirmed checkout
925      * @throws CoreException thrown if project is under version control,
926      * but not connected
927      */

928     public static Set JavaDoc validateEdit(Shell shell, List JavaDoc files) throws CoreException
929     {
930         Set JavaDoc confirmedFiles = new TreeSet JavaDoc(getIFileComparator());
931         IStatus status = ((IFile) files.get(0)).getWorkspace().validateEdit((IFile[]) files.toArray(new IFile[files.size()]), shell);
932         if (status.isMultiStatus() && status.getChildren().length > 0)
933         {
934             for (int i = 0; i < status.getChildren().length; i++)
935             {
936                 IStatus statusChild = status.getChildren()[i];
937                 if (statusChild.isOK())
938                 {
939                     confirmedFiles.add(files.get(i));
940                 }
941             }
942         }
943         else if (status.isOK())
944         {
945             for (Iterator JavaDoc iterator = files.iterator(); iterator.hasNext();)
946             {
947                 IFile file = (IFile) iterator.next();
948                 confirmedFiles.add(file);
949             }
950         }
951         if (status.getSeverity() == IStatus.ERROR) {
952             // not possible to checkout files: not connected to version
953
// control plugin or hijacked files and made read-only, so
954
// collect error messages provided by validator and rethrow
955
StringBuffer JavaDoc message = new StringBuffer JavaDoc(status.getPlugin() + ": " //$NON-NLS-1$
956
+ status.getMessage() + NEWLINE);
957             if (status.isMultiStatus())
958             {
959                 for (int i = 0; i < status.getChildren().length; i++)
960                 {
961                     IStatus statusChild = status.getChildren()[i];
962                     message.append(statusChild.getMessage() + NEWLINE);
963                 }
964             }
965             throw new CoreException(new Status(IStatus.ERROR, AntUIPlugin.PI_ANTUI, 0,
966                     message.toString(), null));
967         }
968
969         return confirmedFiles;
970     }
971     
972     /**
973      * Check if given classpath is a reference to the default classpath of the project.
974      * Ideal for testing if runtime classpath was customized.
975      */

976     public static boolean isDefaultClasspath(IJavaProject project, EclipseClasspath classpath)
977     {
978         List JavaDoc list = removeDuplicates(classpath.rawClassPathEntries);
979         if (list.size() != 1)
980         {
981             return false;
982         }
983         String JavaDoc entry = (String JavaDoc) list.iterator().next();
984         if (EclipseClasspath.isProjectReference(entry))
985         {
986             IJavaProject referencedProject = EclipseClasspath.resolveProjectReference(entry);
987             if (referencedProject == null)
988             {
989                 // project was not loaded in workspace
990
return false;
991             }
992             else if (referencedProject.getProject().getName().equals(project.getProject().getName()))
993             {
994                 return true;
995             }
996         }
997             
998         return false;
999     }
1000
1001    /**
1002     * Add variable/value for Eclipse variable. If given string is no variable, nothing is added.
1003     *
1004     * @param variable2valueMap property map to add variable/value
1005     * @param s String which may contain Eclipse variables, e.g. ${project_name}
1006     */

1007    public static void addVariable(Map JavaDoc variable2valueMap, String JavaDoc s, String JavaDoc projectRoot)
1008    {
1009        if (s == null || s.equals("")) //$NON-NLS-1$
1010
{
1011            return;
1012        }
1013        Pattern JavaDoc pattern = Pattern.compile("\\$\\{.*?\\}"); // ${var} //$NON-NLS-1$
1014
Matcher JavaDoc matcher = pattern.matcher(s);
1015        while (matcher.find())
1016        {
1017            String JavaDoc variable = matcher.group();
1018            String JavaDoc value;
1019            try
1020            {
1021                value = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(variable);
1022            }
1023            catch (CoreException e)
1024            {
1025                // cannot resolve variable
1026
value = variable;
1027            }
1028            variable = removePrefixAndSuffix(variable, "${", "}"); //$NON-NLS-1$ //$NON-NLS-2$
1029
// if it is an environment variable, convert to Ant environment syntax
1030
if (variable.startsWith("env_var:")) //$NON-NLS-1$
1031
{
1032                value = "env." + variable.substring("env_var:".length()); //$NON-NLS-1$ //$NON-NLS-2$
1033
}
1034            File JavaDoc file = new File JavaDoc(value);
1035            if (file.exists()) {
1036                value = ExportUtil.getRelativePath(file.getAbsolutePath(), projectRoot);
1037            }
1038            variable2valueMap.put(variable, value);
1039        }
1040    }
1041
1042    /**
1043     * Returns a path which is equivalent to the given location relative to the
1044     * specified base path.
1045     */

1046    public static String JavaDoc getRelativePath(String JavaDoc otherLocation, String JavaDoc basePath) {
1047
1048        IPath location= new Path(otherLocation);
1049        IPath base= new Path(basePath);
1050        if ((location.getDevice() != null && !location.getDevice().equalsIgnoreCase(base.getDevice())) || !location.isAbsolute()) {
1051            return otherLocation;
1052        }
1053        int baseCount = base.segmentCount();
1054        int count = base.matchingFirstSegments(location);
1055        String JavaDoc temp = ""; //$NON-NLS-1$
1056
for (int j = 0; j < baseCount - count; j++) {
1057            temp += "../"; //$NON-NLS-1$
1058
}
1059        String JavaDoc relative= new Path(temp).append(location.removeFirstSegments(count)).toString();
1060        if (relative.length() == 0) {
1061            relative= "."; //$NON-NLS-1$
1062
}
1063        
1064        return relative;
1065    }
1066}
Popular Tags