Source Code Cross Referenced for ProjectUtilities.java in  » IDE-Netbeans » profiler » org » netbeans » modules » profiler » projectsupport » utilities » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » IDE Netbeans » profiler » org.netbeans.modules.profiler.projectsupport.utilities 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003:         *
004:         * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005:         *
006:         * The contents of this file are subject to the terms of either the GNU
007:         * General Public License Version 2 only ("GPL") or the Common
008:         * Development and Distribution License("CDDL") (collectively, the
009:         * "License"). You may not use this file except in compliance with the
010:         * License. You can obtain a copy of the License at
011:         * http://www.netbeans.org/cddl-gplv2.html
012:         * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013:         * specific language governing permissions and limitations under the
014:         * License.  When distributing the software, include this License Header
015:         * Notice in each file and include the License file at
016:         * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
017:         * particular file as subject to the "Classpath" exception as provided
018:         * by Sun in the GPL Version 2 section of the License file that
019:         * accompanied this code. If applicable, add the following below the
020:         * License Header, with the fields enclosed by brackets [] replaced by
021:         * your own identifying information:
022:         * "Portions Copyrighted [year] [name of copyright owner]"
023:         *
024:         * Contributor(s):
025:         * The Original Software is NetBeans. The Initial Developer of the Original
026:         * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
027:         * Microsystems, Inc. All Rights Reserved.
028:         *
029:         * If you wish your version of this file to be governed by only the CDDL
030:         * or only the GPL Version 2, indicate your decision by adding
031:         * "[Contributor] elects to include this software in this distribution
032:         * under the [CDDL or GPL Version 2] license." If you do not indicate a
033:         * single choice of license, a recipient has the option to distribute
034:         * your version of this file under either the CDDL, the GPL Version 2 or
035:         * to extend the choice of license to its licensees as provided above.
036:         * However, if you add GPL Version 2 code and therefore, elected the GPL
037:         * Version 2 license, then the option applies only if the new code is
038:         * made subject to such option by the copyright holder.
039:         */
040:        package org.netbeans.modules.profiler.projectsupport.utilities;
041:
042:        import org.netbeans.api.java.classpath.ClassPath;
043:        import org.netbeans.api.java.project.JavaProjectConstants;
044:        import org.netbeans.api.java.queries.SourceForBinaryQuery;
045:        import org.netbeans.api.java.source.ClasspathInfo;
046:        import org.netbeans.api.project.Project;
047:        import org.netbeans.api.project.ProjectInformation;
048:        import org.netbeans.api.project.ProjectManager;
049:        import org.netbeans.api.project.ProjectUtils;
050:        import org.netbeans.api.project.SourceGroup;
051:        import org.netbeans.api.project.Sources;
052:        import org.netbeans.api.project.ui.OpenProjects;
053:        import org.netbeans.lib.profiler.ProfilerLogger;
054:        import org.netbeans.lib.profiler.client.ClientUtils;
055:        import org.netbeans.spi.java.classpath.support.ClassPathSupport;
056:        import org.netbeans.spi.project.SubprojectProvider;
057:        import org.netbeans.spi.project.support.ant.PropertyUtils;
058:        import org.openide.ErrorManager;
059:        import org.openide.filesystems.FileObject;
060:        import org.openide.filesystems.FileUtil;
061:        import org.openide.util.NbBundle;
062:        import java.io.File;
063:        import java.io.FileNotFoundException;
064:        import java.io.IOException;
065:        import java.io.RandomAccessFile;
066:        import java.io.UnsupportedEncodingException;
067:        import java.net.URL;
068:        import java.text.MessageFormat;
069:        import java.util.ArrayList;
070:        import java.util.Arrays;
071:        import java.util.Collection;
072:        import java.util.Collections;
073:        import java.util.Comparator;
074:        import java.util.HashSet;
075:        import java.util.List;
076:        import java.util.Set;
077:        import java.util.logging.Level;
078:        import java.util.logging.Logger;
079:        import javax.swing.Icon;
080:        import javax.swing.ImageIcon;
081:        import org.netbeans.api.java.queries.UnitTestForSourceQuery;
082:        import org.netbeans.lib.profiler.common.filters.SimpleFilter;
083:        import org.netbeans.spi.java.classpath.PathResourceImplementation;
084:        import org.netbeans.spi.project.ActionProvider;
085:        import org.openide.util.Lookup;
086:
087:        /**
088:         *
089:         * @author Jaroslav Bachorik
090:         */
091:        public class ProjectUtilities {
092:            //~ Static fields/initializers -----------------------------------------------------------------------------------------------
093:            private static final Logger LOGGER = Logger
094:                    .getLogger(ProjectUtilities.class.getName());
095:            private static final String PROFILE_PROJECT_CLASSES_STRING = NbBundle
096:                    .getMessage(ProjectUtilities.class,
097:                            "ProjectUtilities_ProfileProjectClassesString"); // NOI18N
098:            private static final String PROFILE_PROJECT_SUBPROJECT_CLASSES_STRING = NbBundle
099:                    .getMessage(ProjectUtilities.class,
100:                            "ProjectUtilities_ProfileProjectSubprojectClassesString"); // NOI18N
101:            public static final SimpleFilter FILTER_PROJECT_ONLY = new SimpleFilter(
102:                    PROFILE_PROJECT_CLASSES_STRING,
103:                    SimpleFilter.SIMPLE_FILTER_INCLUSIVE,
104:                    "{$project.classes.only}"); // NOI18N
105:            public static final SimpleFilter FILTER_PROJECT_SUBPROJECTS_ONLY = new SimpleFilter(
106:                    PROFILE_PROJECT_SUBPROJECT_CLASSES_STRING,
107:                    SimpleFilter.SIMPLE_FILTER_INCLUSIVE,
108:                    "{$project.subprojects.classes.only}"); // NOI18N
109:
110:            //~ Methods ------------------------------------------------------------------------------------------------------------------
111:            public static ClasspathInfo getClasspathInfo(final Project project) {
112:                return getClasspathInfo(project, true);
113:            }
114:
115:            public static ClasspathInfo getClasspathInfo(final Project project,
116:                    final boolean includeSubprojects) {
117:                return getClasspathInfo(project, includeSubprojects, true, true);
118:            }
119:
120:            public static ClasspathInfo getClasspathInfo(final Project project,
121:                    final boolean includeSubprojects,
122:                    final boolean includeSources, final boolean includeLibraries) {
123:                FileObject[] sourceRoots = getSourceRoots(project,
124:                        includeSubprojects);
125:                Set<FileObject> srcRootSet = new HashSet<FileObject>(
126:                        sourceRoots.length);
127:                java.util.List<URL> urlList = new ArrayList<URL>();
128:
129:                srcRootSet.addAll(Arrays.asList(sourceRoots));
130:
131:                if (((sourceRoots == null) || (sourceRoots.length == 0))
132:                        && !includeSubprojects) {
133:                    sourceRoots = getSourceRoots(project, true);
134:                }
135:
136:                final ClassPath cpEmpty = ClassPathSupport
137:                        .createClassPath(new FileObject[0]);
138:
139:                if (sourceRoots.length == 0) {
140:                    return null; // fail early
141:                }
142:
143:                ClassPath cpSource = ClassPathSupport
144:                        .createClassPath(sourceRoots);
145:
146:                // cleaning up compile classpatth; we need to get rid off all project's class file references in the classpath
147:                ClassPath cpCompile = ClassPath.getClassPath(sourceRoots[0],
148:                        ClassPath.COMPILE);
149:
150:                for (ClassPath.Entry entry : cpCompile.entries()) {
151:                    SourceForBinaryQuery.Result rslt = SourceForBinaryQuery
152:                            .findSourceRoots(entry.getURL());
153:                    FileObject[] roots = rslt.getRoots();
154:
155:                    if ((roots == null) || (roots.length == 0)) {
156:                        urlList.add(entry.getURL());
157:                    }
158:                }
159:
160:                cpCompile = ClassPathSupport.createClassPath(urlList
161:                        .toArray(new URL[urlList.size()]));
162:
163:                return ClasspathInfo.create(
164:                        includeLibraries ? ClassPath.getClassPath(
165:                                sourceRoots[0], ClassPath.BOOT) : cpEmpty,
166:                        includeLibraries ? cpCompile : cpEmpty,
167:                        includeSources ? cpSource : cpEmpty);
168:            }
169:
170:            /**
171:             * @return The current main project or null if no project is main.
172:             */
173:            public static Project getMainProject() {
174:                return OpenProjects.getDefault().getMainProject();
175:            }
176:
177:            public static Project[] getOpenedProjects() {
178:                return OpenProjects.getDefault().getOpenProjects();
179:            }
180:
181:            public static Project[] getSortedProjects(Project[] projects) {
182:                ArrayList projectsArray = new ArrayList(projects.length);
183:
184:                for (int i = 0; i < projects.length; i++) {
185:                    projectsArray.add(projects[i]);
186:                }
187:
188:                try {
189:                    Collections.sort(projectsArray, new Comparator() {
190:
191:                        public int compare(Object o1, Object o2) {
192:                            Project p1 = (Project) o1;
193:                            Project p2 = (Project) o2;
194:
195:                            return ProjectUtils.getInformation(p1)
196:                                    .getDisplayName().toLowerCase().compareTo(
197:                                            ProjectUtils.getInformation(p2)
198:                                                    .getDisplayName()
199:                                                    .toLowerCase());
200:                        }
201:                    });
202:                } catch (Exception e) {
203:                    ErrorManager.getDefault().log(ErrorManager.ERROR,
204:                            e.getMessage()); // just in case ProjectUtils doesn't provide expected information
205:                }
206:
207:                ;
208:
209:                projectsArray.toArray(projects);
210:
211:                return projects;
212:            }
213:
214:            public static boolean hasAction(Project project, String actionName) {
215:                ActionProvider ap = project.getLookup().lookup(
216:                        ActionProvider.class);
217:
218:                if (ap == null) {
219:                    return false; // return false if no ActionProvider available
220:                }
221:
222:                String[] actions = ap.getSupportedActions();
223:
224:                for (int i = 0; i < actions.length; i++) {
225:                    if ((actions[i] != null) && actionName.equals(actions[i])) {
226:                        return true;
227:                    }
228:                }
229:
230:                return false;
231:            }
232:
233:            public static FileObject getOrCreateBuildFolder(Project project,
234:                    String buildDirProp) {
235:                FileObject buildDir = FileUtil.toFileObject(PropertyUtils
236:                        .resolveFile(FileUtil.toFile(project
237:                                .getProjectDirectory()), buildDirProp));
238:
239:                if (buildDir == null) {
240:                    try {
241:                        // TODO: if buildDirProp is absolute, relativize via PropertyUtils
242:                        buildDir = FileUtil.createFolder(project
243:                                .getProjectDirectory(), buildDirProp);
244:                    } catch (IOException e) {
245:                        MessageFormat.format(NbBundle.getMessage(
246:                                ProjectUtilities.class,
247:                                "FailedCreateOutputFolderMsg"),
248:                                new Object[] { e.getMessage() }); // NOI18N
249:
250:                        ErrorManager.getDefault().notify(ErrorManager.ERROR, e);
251:
252:                        return null;
253:                    }
254:                }
255:
256:                return buildDir;
257:            }
258:
259:            public static String getProjectBuildScript(final Project project) {
260:                final FileObject buildFile = project.getProjectDirectory()
261:                        .getFileObject("build.xml"); //NOI18N
262:                RandomAccessFile file = null;
263:                byte[] data = null;
264:
265:                try {
266:                    file = new RandomAccessFile(FileUtil.toFile(buildFile), "r");
267:                    data = new byte[(int) buildFile.getSize()];
268:                    file.readFully(data);
269:                } catch (FileNotFoundException e2) {
270:                    ProfilerLogger.log(e2);
271:
272:                    return null;
273:                } catch (IOException e2) {
274:                    ProfilerLogger.log(e2);
275:
276:                    return null;
277:                } finally {
278:                    if (file != null) {
279:                        try {
280:                            file.close();
281:                        } catch (IOException e2) {
282:                            ProfilerLogger.log(e2);
283:                        }
284:                    }
285:                }
286:
287:                try {
288:                    return new String(data, "UTF-8" //NOI18N
289:                    ); // According to Issue 65557, build.xml uses UTF-8, not default encoding!
290:                } catch (UnsupportedEncodingException ex) {
291:                    ErrorManager.getDefault().notify(ErrorManager.ERROR, ex);
292:
293:                    return null;
294:                }
295:            }
296:
297:            public static java.util.List<SimpleFilter> getProjectDefaultInstrFilters(
298:                    Project project) {
299:                java.util.List<SimpleFilter> v = new ArrayList<SimpleFilter>();
300:
301:                if (ProjectUtils.getSources(project).getSourceGroups(
302:                        JavaProjectConstants.SOURCES_TYPE_JAVA).length > 0) {
303:                    v.add(FILTER_PROJECT_ONLY);
304:                }
305:
306:                if (hasSubprojects(project)) {
307:                    v.add(FILTER_PROJECT_SUBPROJECTS_ONLY);
308:                }
309:
310:                return v;
311:            }
312:
313:            public static ClientUtils.SourceCodeSelection[] getProjectDefaultRoots(
314:                    Project project, String[][] projectPackagesDescr) {
315:                computeProjectPackages(project, true, projectPackagesDescr);
316:
317:                ClientUtils.SourceCodeSelection[] ret = new ClientUtils.SourceCodeSelection[projectPackagesDescr[1].length];
318:
319:                for (int i = 0; i < projectPackagesDescr[1].length; i++) {
320:                    if ("".equals(projectPackagesDescr[1][i])) { //NOI18N
321:                        ret[i] = new ClientUtils.SourceCodeSelection("", "", ""); //NOI18N
322:                    } else {
323:                        ret[i] = new ClientUtils.SourceCodeSelection(
324:                                projectPackagesDescr[1][i] + ".", "", ""); //NOI18N
325:                    }
326:                }
327:
328:                return ret;
329:            }
330:
331:            public static Project getProjectForBuildScript(String fileName) {
332:                FileObject projectFO = FileUtil
333:                        .toFileObject(new File(fileName));
334:
335:                while (projectFO != null) {
336:                    try {
337:                        if (projectFO.isFolder()) {
338:                            if (LOGGER.isLoggable(Level.FINEST)) {
339:                                LOGGER.finest("Trying: " + projectFO); //NOI18N
340:                            }
341:
342:                            Project p = ProjectManager.getDefault()
343:                                    .findProject(projectFO);
344:
345:                            if (LOGGER.isLoggable(Level.FINEST)) {
346:                                LOGGER.finest("Got: "
347:                                        + ((p != null) ? getProjectName(p)
348:                                                : null)); //NOI18N
349:                            }
350:
351:                            if (p != null) {
352:                                return p;
353:                            }
354:                        }
355:
356:                        projectFO = projectFO.getParent();
357:                    } catch (IOException e) {
358:                        ProfilerLogger.severe("Got: IOException : "
359:                                + e.getMessage()); //NOI18N
360:                    }
361:                }
362:
363:                return null;
364:            }
365:
366:            public static Icon getProjectIcon(Project project) {
367:                ProjectInformation info = project.getLookup().lookup(
368:                        ProjectInformation.class);
369:
370:                if (info == null) {
371:                    return new ImageIcon();
372:                } else {
373:                    return info.getIcon();
374:                }
375:            }
376:
377:            public static String getProjectName(Project project) {
378:                ProjectInformation info = project.getLookup().lookup(
379:                        ProjectInformation.class);
380:
381:                return (info != null) ? info.getDisplayName() : "UNKNOWN";
382:            }
383:
384:            /**
385:             * Provides a list of source roots for the given project.
386:             *
387:             * @param project The project
388:             * @return an array of FileObjects that are the source roots for this project
389:             */
390:            public static FileObject[] getSourceRoots(final Project project) {
391:                return getSourceRoots(project, true);
392:            }
393:
394:            /**
395:             * Provides a list of source roots for the given project.
396:             *
397:             * @param project The project
398:             * @param traverse Include subprojects
399:             * @return an array of FileObjects that are the source roots for this project
400:             */
401:            public static FileObject[] getSourceRoots(final Project project,
402:                    final boolean traverse) {
403:                Set<FileObject> set = new HashSet<FileObject>();
404:                Set<Project> projects = new HashSet<Project>();
405:
406:                projects.add(project);
407:                getSourceRoots(project, traverse, projects, set);
408:
409:                return set.toArray(new FileObject[set.size()]);
410:            }
411:
412:            public static void fetchSubprojects(final Project project,
413:                    final Set<Project> projects) {
414:                // process possible subprojects
415:                SubprojectProvider spp = project.getLookup().lookup(
416:                        SubprojectProvider.class);
417:
418:                if (spp != null) {
419:                    for (Project p : spp.getSubprojects()) {
420:                        if (projects.add(p)) {
421:                            fetchSubprojects(p, projects);
422:                        }
423:                    }
424:                }
425:            }
426:
427:            public static SimpleFilter computeProjectOnlyInstrumentationFilter(
428:                    Project project, SimpleFilter predefinedInstrFilter,
429:                    String[][] projectPackagesDescr) {
430:                // TODO: projectPackagesDescr[1] should only contain packages from subprojects, currently contains also toplevel project packages
431:                if (FILTER_PROJECT_ONLY.equals(predefinedInstrFilter)) {
432:                    computeProjectPackages(project, false, projectPackagesDescr);
433:
434:                    StringBuffer projectPackages = new StringBuffer();
435:
436:                    for (int i = 0; i < projectPackagesDescr[0].length; i++) {
437:                        projectPackages
438:                                .append("".equals(projectPackagesDescr[0][i]) ? getDefaultPackageClassNames(project)
439:                                        : (projectPackagesDescr[0][i] + ". ")); //NOI18N
440:                    }
441:
442:                    return new SimpleFilter(PROFILE_PROJECT_CLASSES_STRING,
443:                            SimpleFilter.SIMPLE_FILTER_INCLUSIVE,
444:                            projectPackages.toString().trim());
445:                } else if (FILTER_PROJECT_SUBPROJECTS_ONLY
446:                        .equals(predefinedInstrFilter)) {
447:                    computeProjectPackages(project, true, projectPackagesDescr);
448:
449:                    StringBuffer projectPackages = new StringBuffer();
450:
451:                    for (int i = 0; i < projectPackagesDescr[1].length; i++) {
452:                        projectPackages
453:                                .append("".equals(projectPackagesDescr[1][i]) ? getDefaultPackageClassNames(project)
454:                                        : (projectPackagesDescr[1][i] + ". ")); //NOI18N // TODO: default packages need to be processed also for subprojects!!!
455:                    }
456:
457:                    return new SimpleFilter(
458:                            PROFILE_PROJECT_SUBPROJECT_CLASSES_STRING,
459:                            SimpleFilter.SIMPLE_FILTER_INCLUSIVE,
460:                            projectPackages.toString().trim());
461:                }
462:
463:                return null;
464:            }
465:
466:            public static String getDefaultPackageClassNames(Project project) {
467:                Collection<String> classNames = SourceUtils
468:                        .getDefaultPackageClassNames(project);
469:                StringBuffer classNamesBuf = new StringBuffer();
470:
471:                for (String className : classNames) {
472:                    classNamesBuf.append(className).append(" "); //NOI18N
473:                }
474:
475:                return classNamesBuf.toString();
476:            }
477:
478:            public static void computeProjectPackages(final Project project,
479:                    boolean subprojects, String[][] storage) {
480:                if ((storage == null) || (storage.length != 2)) {
481:                    throw new IllegalArgumentException(
482:                            "Storage must be a non-null String[2][] array"); // NOI18N
483:                }
484:
485:                if (storage[0] == null) {
486:                    Collection<String> packages1 = new ArrayList<String>();
487:
488:                    for (FileObject root : getSourceRoots(project, false)) {
489:                        addSubpackages(packages1, "", root); //NOI18N
490:                    }
491:
492:                    storage[0] = packages1.toArray(new String[0]);
493:                }
494:
495:                if (subprojects && (storage[1] == null)) {
496:                    FileObject[] srcRoots2 = getSourceRoots(project, true); // TODO: should be computed based on already known srcRoots1
497:                    ArrayList<String> packages2 = new ArrayList<String>();
498:
499:                    for (FileObject root : srcRoots2) {
500:                        addSubpackages(packages2, "", root); //NOI18N
501:                    }
502:
503:                    storage[1] = packages2.toArray(new String[0]);
504:                }
505:            }
506:
507:            /**
508:             * Will find
509:             * Copied from JUnit module implementation in 4.1 and modified
510:             */
511:            public static FileObject findTestForFile(final FileObject selectedFO) {
512:                if ((selectedFO == null)
513:                        || !selectedFO.getExt().equalsIgnoreCase("java")) {
514:                    return null; // NOI18N
515:                }
516:
517:                ClassPath cp = ClassPath.getClassPath(selectedFO,
518:                        ClassPath.SOURCE);
519:
520:                if (cp == null) {
521:                    return null;
522:                }
523:
524:                FileObject packageRoot = cp.findOwnerRoot(selectedFO);
525:
526:                if (packageRoot == null) {
527:                    return null; // not a file in the source dirs - e.g. generated class in web app
528:                }
529:
530:                URL[] testRoots = UnitTestForSourceQuery
531:                        .findUnitTests(packageRoot);
532:                FileObject fileToOpen = null;
533:
534:                for (int j = 0; j < testRoots.length; j++) {
535:                    fileToOpen = findUnitTestInTestRoot(cp, selectedFO,
536:                            testRoots[j]);
537:
538:                    if (fileToOpen != null) {
539:                        return fileToOpen;
540:                    }
541:                }
542:
543:                return null;
544:            }
545:
546:            public static void invokeAction(Project project, String s) {
547:                ActionProvider ap = project.getLookup().lookup(
548:                        ActionProvider.class);
549:
550:                if (ap == null) {
551:                    return; // fail early
552:                }
553:
554:                ap.invokeAction(s, Lookup.getDefault());
555:            }
556:
557:            // Returns true if the project contains any Java sources (does not check subprojects!)
558:            public static boolean isJavaProject(Project project) {
559:                if (project == null)
560:                    return false;
561:
562:                Sources sources = ProjectUtils.getSources(project);
563:                SourceGroup[] sourceGroups = sources
564:                        .getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
565:
566:                return sourceGroups.length > 0;
567:            }
568:
569:            private static void getSourceRoots(final Project project,
570:                    final boolean traverse, Set<Project> projects,
571:                    Set<FileObject> roots) {
572:                final Sources sources = ProjectUtils.getSources(project);
573:
574:                for (SourceGroup sg : sources
575:                        .getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)) {
576:                    roots.add(sg.getRootFolder());
577:                }
578:
579:                if (traverse) {
580:                    // process possible subprojects
581:                    SubprojectProvider spp = project.getLookup().lookup(
582:                            SubprojectProvider.class);
583:
584:                    if (spp != null) {
585:                        for (Project p : spp.getSubprojects()) {
586:                            if (projects.add(p)) {
587:                                getSourceRoots(p, traverse, projects, roots);
588:                            }
589:                        }
590:                    }
591:                }
592:            }
593:
594:            private static void addSubpackages(Collection<String> packages,
595:                    String prefix, FileObject packageFO) {
596:                if (!packageFO.isFolder()) { // not a folder
597:
598:                    return;
599:                }
600:
601:                FileObject[] children = packageFO.getChildren();
602:
603:                // 1. check if there are java sources in this folder and if so, add to the list of packages
604:                if (!packages.contains(prefix)) { // already in there, skip this
605:
606:                    for (int i = 0; i < children.length; i++) {
607:                        FileObject child = children[i];
608:
609:                        if (child.getExt().equals("java")) { //NOI18N
610:                            packages.add(prefix);
611:
612:                            break;
613:                        }
614:                    }
615:                }
616:
617:                // 2. recurse into subfolders
618:                for (int i = 0; i < children.length; i++) {
619:                    FileObject child = children[i];
620:
621:                    if (child.isFolder()) {
622:                        if ("".equals(prefix)) { //NOI18N
623:                            addSubpackages(packages, child.getName(), child);
624:                        } else {
625:                            addSubpackages(packages, prefix + "."
626:                                    + child.getName(), child); //NOI18N
627:                        }
628:                    }
629:                }
630:            }
631:
632:            private static boolean hasSubprojects(Project project) {
633:                SubprojectProvider spp = project.getLookup().lookup(
634:                        SubprojectProvider.class);
635:
636:                if (spp == null) {
637:                    return false;
638:                }
639:
640:                return spp.getSubprojects().size() > 0;
641:            }
642:
643:            /**
644:             * Copied from JUnit module implementation in 4.1 and modified
645:             */
646:            private static FileObject findUnitTestInTestRoot(ClassPath cp,
647:                    FileObject selectedFO, URL testRoot) {
648:                ClassPath testClassPath = null;
649:
650:                if (testRoot == null) { //no tests, use sources instead
651:                    testClassPath = cp;
652:                } else {
653:                    try {
654:                        List<PathResourceImplementation> cpItems = new ArrayList<PathResourceImplementation>();
655:                        cpItems.add(ClassPathSupport.createResource(testRoot));
656:                        testClassPath = ClassPathSupport
657:                                .createClassPath(cpItems);
658:                    } catch (IllegalArgumentException ex) {
659:                        ErrorManager.getDefault().notify(
660:                                ErrorManager.INFORMATIONAL, ex);
661:                        testClassPath = cp;
662:                    }
663:                }
664:
665:                String testName = getTestName(cp, selectedFO);
666:
667:                return testClassPath.findResource(testName + ".java"); // NOI18N
668:            }
669:
670:            /**
671:             * Copied from JUnit module implementation in 4.1 and modified
672:             */
673:            private static String getTestName(ClassPath cp,
674:                    FileObject selectedFO) {
675:                String resource = cp.getResourceName(selectedFO, '/', false); //NOI18N
676:                String testName = null;
677:
678:                if (selectedFO.isFolder()) {
679:                    //find Suite for package
680:                    testName = convertPackage2SuiteName(resource);
681:                } else {
682:                    // find Test for class
683:                    testName = convertClass2TestName(resource);
684:                }
685:
686:                return testName;
687:            }
688:
689:            /**
690:             * Copied from JUnit module implementation in 4.1 and modified
691:             * Hardcoded test name prefix/suffix.
692:             */
693:            private static String convertClass2TestName(String classFileName) {
694:                if ((classFileName == null) || "".equals(classFileName)) {
695:                    return ""; //NOI18N
696:                }
697:
698:                int index = classFileName.lastIndexOf('/'); //NOI18N
699:                String pkg = (index > -1) ? classFileName.substring(0, index)
700:                        : ""; // NOI18N
701:                String clazz = (index > -1) ? classFileName
702:                        .substring(index + 1) : classFileName;
703:                clazz = clazz.substring(0, 1).toUpperCase()
704:                        + clazz.substring(1);
705:
706:                if (pkg.length() > 0) {
707:                    pkg += "/"; // NOI18N
708:                }
709:
710:                return pkg + clazz + "Test"; // NOI18N
711:            }
712:
713:            /**
714:             * Copied from JUnit module implementation in 4.1 and modified
715:             * Hardcoded test name prefix/suffix.
716:             */
717:            private static String convertPackage2SuiteName(
718:                    String packageFileName) {
719:                if ((packageFileName == null) || "".equals(packageFileName)) {
720:                    return ""; //NOI18N
721:                }
722:
723:                int index = packageFileName.lastIndexOf('/'); //NOI18N
724:                String pkg = (index > -1) ? packageFileName
725:                        .substring(index + 1) : packageFileName;
726:                pkg = pkg.substring(0, 1).toUpperCase() + pkg.substring(1);
727:
728:                return packageFileName + "/" + pkg + "Test"; // NOI18N
729:            }
730:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.