Source Code Cross Referenced for MavenEmbedder.java in  » Build » maven » org » apache » maven » embedder » 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 » Build » maven » org.apache.maven.embedder 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package org.apache.maven.embedder;
002:
003:        /*
004:         * Licensed to the Apache Software Foundation (ASF) under one
005:         * or more contributor license agreements.  See the NOTICE file
006:         * distributed with this work for additional information
007:         * regarding copyright ownership.  The ASF licenses this file
008:         * to you under the Apache License, Version 2.0 (the
009:         * "License"); you may not use this file except in compliance
010:         * with the License.  You may obtain a copy of the License at
011:         *
012:         *  http://www.apache.org/licenses/LICENSE-2.0
013:         *
014:         * Unless required by applicable law or agreed to in writing,
015:         * software distributed under the License is distributed on an
016:         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017:         * KIND, either express or implied.  See the License for the
018:         * specific language governing permissions and limitations
019:         * under the License.
020:         */
021:
022:        import org.apache.maven.Maven;
023:        import org.apache.maven.artifact.Artifact;
024:        import org.apache.maven.artifact.factory.ArtifactFactory;
025:        import org.apache.maven.artifact.handler.ArtifactHandler;
026:        import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
027:        import org.apache.maven.artifact.repository.ArtifactRepository;
028:        import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
029:        import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
030:        import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
031:        import org.apache.maven.artifact.resolver.ArtifactResolutionException;
032:        import org.apache.maven.artifact.resolver.ArtifactResolver;
033:        import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
034:        import org.apache.maven.embedder.execution.MavenExecutionRequestPopulator;
035:        import org.apache.maven.embedder.writer.WriterUtils;
036:        import org.apache.maven.execution.DefaultMavenExecutionRequest;
037:        import org.apache.maven.execution.DefaultMavenExecutionResult;
038:        import org.apache.maven.execution.MavenExecutionRequest;
039:        import org.apache.maven.execution.MavenExecutionResult;
040:        import org.apache.maven.execution.MavenSession;
041:        import org.apache.maven.execution.ReactorManager;
042:        import org.apache.maven.lifecycle.LifecycleUtils;
043:        import org.apache.maven.model.Model;
044:        import org.apache.maven.model.Plugin;
045:        import org.apache.maven.model.io.jdom.MavenJDOMWriter;
046:        import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
047:        import org.apache.maven.plugin.InvalidPluginException;
048:        import org.apache.maven.plugin.PluginManager;
049:        import org.apache.maven.plugin.PluginManagerException;
050:        import org.apache.maven.plugin.PluginNotFoundException;
051:        import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder;
052:        import org.apache.maven.plugin.version.PluginVersionNotFoundException;
053:        import org.apache.maven.plugin.version.PluginVersionResolutionException;
054:        import org.apache.maven.project.MavenProject;
055:        import org.apache.maven.project.MavenProjectBuilder;
056:        import org.apache.maven.project.MavenProjectBuildingResult;
057:        import org.apache.maven.project.ProjectBuildingException;
058:        import org.apache.maven.settings.Settings;
059:        import org.apache.maven.settings.SettingsConfigurationException;
060:        import org.apache.maven.settings.io.jdom.SettingsJDOMWriter;
061:        import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader;
062:        import org.apache.maven.settings.validation.DefaultSettingsValidator;
063:        import org.apache.maven.settings.validation.SettingsValidationResult;
064:        import org.apache.maven.settings.validation.SettingsValidator;
065:        import org.codehaus.plexus.ContainerConfiguration;
066:        import org.codehaus.plexus.DefaultContainerConfiguration;
067:        import org.codehaus.plexus.DefaultPlexusContainer;
068:        import org.codehaus.plexus.MutablePlexusContainer;
069:        import org.codehaus.plexus.PlexusContainer;
070:        import org.codehaus.plexus.PlexusContainerException;
071:        import org.codehaus.plexus.classworlds.ClassWorld;
072:        import org.codehaus.plexus.classworlds.realm.ClassRealm;
073:        import org.codehaus.plexus.classworlds.realm.DuplicateRealmException;
074:        import org.codehaus.plexus.classworlds.realm.NoSuchRealmException;
075:        import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
076:        import org.codehaus.plexus.component.repository.exception.ComponentRepositoryException;
077:        import org.codehaus.plexus.configuration.PlexusConfigurationException;
078:        import org.codehaus.plexus.logging.LoggerManager;
079:        import org.codehaus.plexus.util.IOUtil;
080:        import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
081:        import org.jdom.Document;
082:        import org.jdom.Element;
083:        import org.jdom.output.Format;
084:
085:        import java.io.File;
086:        import java.io.FileReader;
087:        import java.io.FileWriter;
088:        import java.io.IOException;
089:        import java.io.Reader;
090:        import java.io.Writer;
091:        import java.net.URL;
092:        import java.util.Arrays;
093:        import java.util.HashMap;
094:        import java.util.Iterator;
095:        import java.util.List;
096:        import java.util.Map;
097:
098:        /**
099:         * Class intended to be used by clients who wish to embed Maven into their applications
100:         *
101:         * @author Jason van Zyl
102:         */
103:        public class MavenEmbedder {
104:            public static final String DEFAULT_LOCAL_REPO_ID = "local";
105:
106:            public static final String userHome = System
107:                    .getProperty("user.home");
108:
109:            public static final File userMavenConfigurationHome = new File(
110:                    userHome, ".m2");
111:
112:            public static final File defaultUserLocalRepository = new File(
113:                    userMavenConfigurationHome, "repository");
114:
115:            public static final File DEFAULT_USER_SETTINGS_FILE = new File(
116:                    userMavenConfigurationHome, "settings.xml");
117:
118:            public static final File DEFAULT_GLOBAL_SETTINGS_FILE = new File(
119:                    System.getProperty("maven.home", System.getProperty(
120:                            "user.dir", "")), "conf/settings.xml");
121:
122:            // ----------------------------------------------------------------------------
123:            //
124:            // ----------------------------------------------------------------------------
125:
126:            private MutablePlexusContainer container;
127:
128:            // ----------------------------------------------------------------------
129:            // Components
130:            // ----------------------------------------------------------------------
131:
132:            private MavenProjectBuilder mavenProjectBuilder;
133:
134:            private MavenXpp3Reader modelReader;
135:
136:            private MavenJDOMWriter modelWriter;
137:
138:            private PluginDescriptorBuilder pluginDescriptorBuilder;
139:
140:            private ArtifactRepositoryFactory artifactRepositoryFactory;
141:
142:            private ArtifactFactory artifactFactory;
143:
144:            private ArtifactResolver artifactResolver;
145:
146:            private ArtifactRepositoryLayout defaultArtifactRepositoryLayout;
147:
148:            private ArtifactHandlerManager artifactHandlerManager;
149:
150:            private Maven maven;
151:
152:            private MavenExecutionRequestPopulator populator;
153:
154:            // ----------------------------------------------------------------------
155:            // Configuration
156:            // ----------------------------------------------------------------------
157:
158:            private ClassWorld classWorld;
159:
160:            private ClassRealm realm;
161:
162:            private MavenEmbedderLogger logger;
163:
164:            private boolean activateSystemManager;
165:
166:            // ----------------------------------------------------------------------
167:            // User options
168:            // ----------------------------------------------------------------------
169:
170:            private Configuration configuration;
171:
172:            // ----------------------------------------------------------------------------
173:            // Constructors
174:            // ----------------------------------------------------------------------------
175:
176:            public MavenEmbedder(Configuration embedderConfiguration)
177:                    throws MavenEmbedderException {
178:                start(embedderConfiguration);
179:            }
180:
181:            // ----------------------------------------------------------------------
182:            // Accessors
183:            // ----------------------------------------------------------------------
184:
185:            public ClassWorld getClassWorld() {
186:                return classWorld;
187:            }
188:
189:            public ArtifactRepository getLocalRepository() {
190:                return request.getLocalRepository();
191:            }
192:
193:            public Settings getSettings() {
194:                return request.getSettings();
195:            }
196:
197:            public MavenEmbedderLogger getLogger() {
198:                return logger;
199:            }
200:
201:            public void setLogger(MavenEmbedderLogger logger) {
202:                this .logger = logger;
203:            }
204:
205:            public Model readModel(File file) throws XmlPullParserException,
206:                    IOException {
207:                Reader reader = new FileReader(file);
208:
209:                Model model;
210:
211:                try {
212:                    model = modelReader.read(reader);
213:                } finally {
214:                    IOUtil.close(reader);
215:                }
216:
217:                return model;
218:            }
219:
220:            public void writeModel(Writer writer, Model model,
221:                    boolean namespaceDeclaration) throws IOException {
222:                WriterUtils.write(writer, model, true);
223:            }
224:
225:            public void writeModel(Writer writer, Model model)
226:                    throws IOException {
227:                WriterUtils.write(writer, model, false);
228:            }
229:
230:            // ----------------------------------------------------------------------
231:            // Settings
232:            // ----------------------------------------------------------------------
233:
234:            public static void writeSettings(File file, Settings settings)
235:                    throws IOException {
236:                Writer fileWriter = new FileWriter(file);
237:
238:                SettingsValidator settingsValidator = new DefaultSettingsValidator();
239:
240:                SettingsValidationResult validationResult = settingsValidator
241:                        .validate(settings);
242:
243:                if (validationResult.getMessageCount() > 0) {
244:                    throw new IOException("Failed to validate Settings.\n"
245:                            + validationResult.render("\n"));
246:                }
247:
248:                Element root = new Element("settings");
249:
250:                Document doc = new Document(root);
251:
252:                SettingsJDOMWriter writer = new SettingsJDOMWriter();
253:
254:                String encoding = settings.getModelEncoding() != null ? settings
255:                        .getModelEncoding()
256:                        : "UTF-8";
257:
258:                Format format = Format.getPrettyFormat().setEncoding(encoding);
259:
260:                try {
261:                    writer.write(settings, doc, fileWriter, format);
262:                } finally {
263:                    fileWriter.close();
264:                }
265:            }
266:
267:            public static Settings readSettings(File file) throws IOException,
268:                    SettingsConfigurationException {
269:                Reader fileReader = new FileReader(file);
270:
271:                SettingsValidator settingsValidator = new DefaultSettingsValidator();
272:
273:                SettingsXpp3Reader reader = new SettingsXpp3Reader();
274:
275:                try {
276:                    Settings settings = reader.read(fileReader);
277:
278:                    SettingsValidationResult validationResult = settingsValidator
279:                            .validate(settings);
280:
281:                    if (validationResult.getMessageCount() > 0) {
282:                        throw new IOException("Failed to validate Settings.\n"
283:                                + validationResult.render("\n"));
284:                    }
285:
286:                    return settings;
287:                } catch (XmlPullParserException e) {
288:                    throw new SettingsConfigurationException(
289:                            "Failed to parse settings.", e);
290:                } finally {
291:                    IOUtil.close(fileReader);
292:                }
293:            }
294:
295:            /**
296:             * mkleint: protected so that IDE integrations can selectively allow downloading artifacts
297:             * from remote repositories (if they prohibit by default on project loading)
298:             */
299:            protected void verifyPlugin(Plugin plugin, MavenProject project)
300:                    throws ComponentLookupException,
301:                    ArtifactResolutionException,
302:                    PluginVersionResolutionException,
303:                    ArtifactNotFoundException,
304:                    InvalidVersionSpecificationException,
305:                    InvalidPluginException, PluginManagerException,
306:                    PluginNotFoundException, PluginVersionNotFoundException {
307:                PluginManager pluginManager = (PluginManager) container
308:                        .lookup(PluginManager.ROLE);
309:
310:                MavenSession session = new MavenSession(container, request,
311:                        null, null);
312:
313:                pluginManager.verifyPlugin(plugin, project, session);
314:            }
315:
316:            /** protected for tests only.. */
317:            protected Map getPluginExtensionComponents(Plugin plugin)
318:                    throws PluginManagerException {
319:                try {
320:                    PluginManager pluginManager = (PluginManager) container
321:                            .lookup(PluginManager.ROLE);
322:                    return pluginManager.getPluginComponents(plugin,
323:                            ArtifactHandler.ROLE);
324:                } catch (ComponentLookupException e) {
325:                    getLogger()
326:                            .debug(
327:                                    "Unable to find the lifecycle component in the extension",
328:                                    e);
329:                    return new HashMap();
330:                }
331:            }
332:
333:            /**
334:             * mkleint: copied from DefaultLifecycleExecutor
335:             *
336:             * @todo Not particularly happy about this. Would like WagonManager and ArtifactTypeHandlerManager to be able to
337:             * lookup directly, or have them passed in
338:             * @todo Move this sort of thing to the tail end of the project-building process
339:             */
340:            private Map findArtifactTypeHandlers(MavenProject project)
341:                    throws Exception {
342:                Map map = new HashMap();
343:
344:                for (Iterator i = project.getBuildPlugins().iterator(); i
345:                        .hasNext();) {
346:                    Plugin plugin = (Plugin) i.next();
347:
348:                    if (plugin.isExtensions()) {
349:                        verifyPlugin(plugin, project);
350:
351:                        map.putAll(getPluginExtensionComponents(plugin));
352:
353:                        // shudder...
354:                        for (Iterator j = map.values().iterator(); j.hasNext();) {
355:                            ArtifactHandler handler = (ArtifactHandler) j
356:                                    .next();
357:                            if (project.getPackaging().equals(
358:                                    handler.getPackaging())) {
359:                                project.getArtifact().setArtifactHandler(
360:                                        handler);
361:                            }
362:                        }
363:                    }
364:                }
365:
366:                return map;
367:            }
368:
369:            // ----------------------------------------------------------------------
370:            // Project
371:            // ----------------------------------------------------------------------
372:
373:            public MavenProject readProject(File mavenProject)
374:                    throws ProjectBuildingException {
375:                return mavenProjectBuilder.build(mavenProject, request
376:                        .getLocalRepository(), request.getProfileManager(),
377:                        false);
378:            }
379:
380:            /**
381:             * This method is used to grab the list of dependencies that belong to a project so that a UI
382:             * can be populated. For example, a list of libraries that are used by an Eclipse, Netbeans, or
383:             * IntelliJ project.
384:             */
385:            public MavenExecutionResult readProjectWithDependencies(
386:                    MavenExecutionRequest request) {
387:                MavenExecutionResult result = new DefaultMavenExecutionResult();
388:
389:                try {
390:                    request = populator
391:                            .populateDefaults(request, configuration);
392:
393:                    // This is necessary to make the MavenEmbedderProjectWithExtensionReadingTest work which uses
394:                    // a custom type for a dependency like this:
395:                    //
396:                    // <dependency>
397:                    //   <groupId>junit</groupId>
398:                    //   <artifactId>junit</artifactId>
399:                    //   <version>3.8.1</version>
400:                    //   <scope>test</scope>
401:                    //   <type>mkleint</type>
402:                    // </dependency>
403:                    //
404:                    // If the artifact handlers are not loaded up-front then this dependency element is not
405:                    // registered as an artifact and is not added to the classpath elements.
406:
407:                    MavenProject project = readProject(new File(request
408:                            .getPomFile()));
409:
410:                    Map handlers = findArtifactTypeHandlers(project);
411:
412:                    artifactHandlerManager.addHandlers(handlers);
413:                } catch (Exception e) {
414:                    return result.addException(e);
415:                }
416:
417:                ReactorManager reactorManager = maven.createReactorManager(
418:                        request, result);
419:
420:                if (result.hasExceptions()) {
421:                    return result;
422:                }
423:
424:                MavenProjectBuildingResult projectBuildingResult = null;
425:
426:                try {
427:                    projectBuildingResult = mavenProjectBuilder
428:                            .buildWithDependencies(new File(request
429:                                    .getPomFile()), request
430:                                    .getLocalRepository(), request
431:                                    .getProfileManager(), request
432:                                    .getTransferListener());
433:                } catch (ProjectBuildingException e) {
434:                    result.addException(e);
435:                }
436:
437:                if (reactorManager.hasMultipleProjects()) {
438:                    result.setProject(projectBuildingResult.getProject());
439:
440:                    result.setTopologicallySortedProjects(reactorManager
441:                            .getSortedProjects());
442:                } else {
443:                    result.setProject(projectBuildingResult.getProject());
444:
445:                    result.setTopologicallySortedProjects(Arrays
446:                            .asList(new MavenProject[] { projectBuildingResult
447:                                    .getProject() }));
448:                }
449:
450:                result.setArtifactResolutionResult(projectBuildingResult
451:                        .getArtifactResolutionResult());
452:
453:                // From this I could produce something that would help IDE integrators create importers:
454:                // - topo sorted list of projects
455:                // - binary dependencies
456:                // - source dependencies (projects in the reactor)
457:                //
458:                // We could create a layer approach here. As to do anything you must resolve a projects artifacts,
459:                // and with that set you could then subsequently execute goals for each of those project.
460:
461:                return result;
462:            }
463:
464:            // ----------------------------------------------------------------------
465:            // Artifacts
466:            // ----------------------------------------------------------------------
467:
468:            public Artifact createArtifact(String groupId, String artifactId,
469:                    String version, String scope, String type) {
470:                return artifactFactory.createArtifact(groupId, artifactId,
471:                        version, scope, type);
472:            }
473:
474:            public Artifact createArtifactWithClassifier(String groupId,
475:                    String artifactId, String version, String type,
476:                    String classifier) {
477:                return artifactFactory.createArtifactWithClassifier(groupId,
478:                        artifactId, version, type, classifier);
479:            }
480:
481:            public void resolve(Artifact artifact, List remoteRepositories,
482:                    ArtifactRepository localRepository)
483:                    throws ArtifactResolutionException,
484:                    ArtifactNotFoundException {
485:                artifactResolver.resolve(artifact, remoteRepositories,
486:                        localRepository);
487:            }
488:
489:            public ArtifactHandler getArtifactHandler(Artifact artifact) {
490:                return artifactHandlerManager.getArtifactHandler(artifact
491:                        .getType());
492:            }
493:
494:            // ----------------------------------------------------------------------
495:            // Plugins
496:            // ----------------------------------------------------------------------
497:            // ----------------------------------------------------------------------
498:            // Execution of phases/goals
499:            // ----------------------------------------------------------------------
500:            // ----------------------------------------------------------------------
501:            // LegacyLifecycle information
502:            // ----------------------------------------------------------------------
503:
504:            public List getLifecyclePhases() {
505:                return getBuildLifecyclePhases();
506:            }
507:
508:            public List getAllLifecyclePhases() {
509:                return LifecycleUtils.getValidPhaseNames();
510:            }
511:
512:            public List getDefaultLifecyclePhases() {
513:                return getBuildLifecyclePhases();
514:            }
515:
516:            public List getBuildLifecyclePhases() {
517:                return LifecycleUtils.getValidBuildPhaseNames();
518:            }
519:
520:            public List getCleanLifecyclePhases() {
521:                return LifecycleUtils.getValidCleanPhaseNames();
522:            }
523:
524:            public List getSiteLifecyclePhases() {
525:                return LifecycleUtils.getValidSitePhaseNames();
526:            }
527:
528:            // ----------------------------------------------------------------------
529:            //  LegacyLifecycle
530:            // ----------------------------------------------------------------------
531:
532:            private MavenExecutionRequest request;
533:
534:            private void start(Configuration configuration)
535:                    throws MavenEmbedderException {
536:                this .classWorld = configuration.getClassWorld();
537:
538:                this .logger = configuration.getMavenEmbedderLogger();
539:
540:                // ----------------------------------------------------------------------------
541:                // Don't override any existing SecurityManager if one has been installed. Our
542:                // SecurityManager just checks to make sure
543:                // ----------------------------------------------------------------------------
544:
545:                try {
546:                    if (System.getSecurityManager() == null
547:                            && activateSystemManager) {
548:                        System
549:                                .setSecurityManager(new MavenEmbedderSecurityManager());
550:                    }
551:                } catch (RuntimeException e) {
552:                    logger.warn("Error trying to set the SecurityManager: "
553:                            + e.getMessage());
554:                }
555:
556:                this .configuration = configuration;
557:
558:                try {
559:                    ContainerConfiguration cc = new DefaultContainerConfiguration()
560:                            .setClassWorld(classWorld).setParentContainer(
561:                                    configuration.getParentContainer())
562:                            .setName("embedder");
563:
564:                    container = new DefaultPlexusContainer(cc);
565:                } catch (PlexusContainerException e) {
566:                    throw new MavenEmbedderException(
567:                            "Error creating Plexus container for Maven Embedder",
568:                            e);
569:                }
570:
571:                if (logger != null) {
572:                    MavenEmbedderLoggerManager loggerManager = new MavenEmbedderLoggerManager(
573:                            new PlexusLoggerAdapter(logger));
574:
575:                    container.setLoggerManager(loggerManager);
576:                }
577:
578:                try {
579:                    if (configuration.getContainerCustomizer() != null) {
580:                        configuration.getContainerCustomizer().customize(
581:                                container);
582:                    }
583:
584:                    handleExtensions(configuration.getExtensions());
585:
586:                    // ----------------------------------------------------------------------
587:                    // Lookup each of the components we need to provide the desired
588:                    // client interface.
589:                    // ----------------------------------------------------------------------
590:
591:                    modelReader = new MavenXpp3Reader();
592:
593:                    modelWriter = new MavenJDOMWriter();
594:
595:                    maven = (Maven) container.lookup(Maven.ROLE);
596:
597:                    pluginDescriptorBuilder = new PluginDescriptorBuilder();
598:
599:                    mavenProjectBuilder = (MavenProjectBuilder) container
600:                            .lookup(MavenProjectBuilder.ROLE);
601:
602:                    // ----------------------------------------------------------------------
603:                    // Artifact related components
604:                    // ----------------------------------------------------------------------
605:
606:                    artifactRepositoryFactory = (ArtifactRepositoryFactory) container
607:                            .lookup(ArtifactRepositoryFactory.ROLE);
608:
609:                    artifactFactory = (ArtifactFactory) container
610:                            .lookup(ArtifactFactory.ROLE);
611:
612:                    artifactResolver = (ArtifactResolver) container.lookup(
613:                            ArtifactResolver.ROLE, "default");
614:
615:                    defaultArtifactRepositoryLayout = (ArtifactRepositoryLayout) container
616:                            .lookup(ArtifactRepositoryLayout.ROLE, "default");
617:
618:                    populator = (MavenExecutionRequestPopulator) container
619:                            .lookup(MavenExecutionRequestPopulator.ROLE);
620:
621:                    artifactHandlerManager = (ArtifactHandlerManager) container
622:                            .lookup(ArtifactHandlerManager.ROLE);
623:
624:                    // This is temporary as we can probably cache a single request and use it for default values and
625:                    // simply cascade values in from requests used for individual executions.
626:                    request = new DefaultMavenExecutionRequest();
627:
628:                    populator.populateDefaults(request, configuration);
629:                } catch (ComponentLookupException e) {
630:                    throw new MavenEmbedderException(
631:                            "Cannot lookup required component.", e);
632:                }
633:            }
634:
635:            // ----------------------------------------------------------------------
636:            // LegacyLifecycle
637:            // ----------------------------------------------------------------------
638:
639:            private void handleExtensions(List extensions)
640:                    throws MavenEmbedderException {
641:                ClassRealm childRealm;
642:                try {
643:                    childRealm = container.getContainerRealm()
644:                            .createChildRealm("embedder-extensions");
645:                } catch (DuplicateRealmException e1) {
646:                    try {
647:                        childRealm = classWorld.getRealm("embedder-extensions");
648:                    } catch (NoSuchRealmException e) {
649:                        throw new MavenEmbedderException(
650:                                "Cannot create realm 'extensions'", e);
651:                    }
652:                }
653:
654:                for (Iterator it = extensions.iterator(); it.hasNext();) {
655:                    childRealm.addURL((URL) it.next());
656:                }
657:
658:                try {
659:                    container.discoverComponents(childRealm, true);
660:                } catch (PlexusConfigurationException e) {
661:                    throw new MavenEmbedderException(
662:                            "Configuration error while discovering extension components",
663:                            e);
664:                } catch (ComponentRepositoryException e) {
665:                    throw new MavenEmbedderException(
666:                            "Component repository error while discovering extension components",
667:                            e);
668:                }
669:            }
670:
671:            public void stop() throws MavenEmbedderException {
672:                container.dispose();
673:            }
674:
675:            // ----------------------------------------------------------------------------
676:            // Validation
677:            // ----------------------------------------------------------------------------
678:
679:            // ----------------------------------------------------------------------------
680:            // Options for settings
681:            //
682:            // 1. No settings
683:            // 2. User settings only
684:            // 3. Global settings only
685:            // 4. Both Users settings and Global settings. In the case that both are present
686:            //    the User settings take priority.
687:            //
688:            // What we would like to provide is a way that the client code does not have
689:            // to deal with settings configuration at all.
690:            // ----------------------------------------------------------------------------
691:
692:            public static ConfigurationValidationResult validateConfiguration(
693:                    Configuration configuration) {
694:                DefaultConfigurationValidationResult result = new DefaultConfigurationValidationResult();
695:
696:                Reader fileReader = null;
697:
698:                // User settings
699:
700:                if (configuration.getUserSettingsFile() != null) {
701:                    try {
702:                        fileReader = new FileReader(configuration
703:                                .getUserSettingsFile());
704:
705:                        result.setUserSettings(new SettingsXpp3Reader()
706:                                .read(fileReader));
707:                    } catch (IOException e) {
708:                        result.setUserSettingsException(e);
709:                    } catch (XmlPullParserException e) {
710:                        result.setUserSettingsException(e);
711:                    } finally {
712:                        IOUtil.close(fileReader);
713:                    }
714:                }
715:
716:                // Global settings
717:
718:                if (configuration.getGlobalSettingsFile() != null) {
719:                    try {
720:                        fileReader = new FileReader(configuration
721:                                .getGlobalSettingsFile());
722:
723:                        result.setGlobalSettings(new SettingsXpp3Reader()
724:                                .read(fileReader));
725:                    } catch (IOException e) {
726:                        result.setGlobalSettingsException(e);
727:                    } catch (XmlPullParserException e) {
728:                        result.setGlobalSettingsException(e);
729:                    } finally {
730:                        IOUtil.close(fileReader);
731:                    }
732:                }
733:
734:                return result;
735:            }
736:
737:            // ----------------------------------------------------------------------------
738:            // Configuration
739:            // ----------------------------------------------------------------------------
740:
741:            public Configuration getConfiguration() {
742:                return configuration;
743:            }
744:
745:            // ----------------------------------------------------------------------
746:            // Start of new embedder API
747:            // ----------------------------------------------------------------------
748:
749:            public MavenExecutionResult execute(MavenExecutionRequest request) {
750:                LoggerManager loggerManager = container.getLoggerManager();
751:
752:                int oldThreshold = loggerManager.getThreshold();
753:
754:                try {
755:                    loggerManager.setThresholds(request.getLoggingLevel());
756:
757:                    try {
758:                        request = populator.populateDefaults(request,
759:                                configuration);
760:                    } catch (MavenEmbedderException e) {
761:                        MavenExecutionResult result = new DefaultMavenExecutionResult();
762:
763:                        result.addException(e);
764:
765:                        return result;
766:                    }
767:
768:                    return maven.execute(request);
769:                } finally {
770:                    loggerManager.setThresholds(oldThreshold);
771:                }
772:            }
773:
774:            /**
775:             * Return the instance of the plexus container being used in the embedder.
776:             *
777:             * @return The plexus container used in the embedder.
778:             */
779:            public PlexusContainer getPlexusContainer() {
780:                return container;
781:            }
782:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.