1 package org.apache.maven.it;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.PrintStream;
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
28 import java.util.Properties;
29
30
31
32
33
34
35
36 class Classpath3xLauncher
37 implements MavenLauncher
38 {
39
40 private final Object mavenCli;
41
42 private final Method doMain;
43
44 public Classpath3xLauncher()
45 throws LauncherException
46 {
47 ClassLoader coreLoader = Thread.currentThread().getContextClassLoader();
48
49 try
50 {
51 Class cliClass = coreLoader.loadClass( "org.apache.maven.cli.MavenCli" );
52
53 mavenCli = cliClass.newInstance();
54
55 Class[] parameterTypes = { String[].class, String.class, PrintStream.class, PrintStream.class };
56 doMain = cliClass.getMethod( "doMain", parameterTypes );
57 }
58 catch ( ClassNotFoundException e )
59 {
60 throw new LauncherException( e.getMessage(), e );
61 }
62 catch ( NoSuchMethodException e )
63 {
64 throw new LauncherException( e.getMessage(), e );
65 }
66 catch ( InstantiationException e )
67 {
68 throw new LauncherException( e.getMessage(), e );
69 }
70 catch ( IllegalAccessException e )
71 {
72 throw new LauncherException( e.getMessage(), e );
73 }
74 }
75
76 public int run( String[] cliArgs, String workingDirectory, File logFile )
77 throws IOException, LauncherException
78 {
79 PrintStream out = ( logFile != null ) ? new PrintStream( new FileOutputStream( logFile ) ) : System.out;
80 try
81 {
82 Properties originalProperties = System.getProperties();
83 System.setProperties( null );
84 System.setProperty( "maven.home", originalProperties.getProperty( "maven.home", "" ) );
85 System.setProperty( "user.dir", new File( workingDirectory ).getAbsolutePath() );
86
87 ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
88 Thread.currentThread().setContextClassLoader( mavenCli.getClass().getClassLoader() );
89 try
90 {
91 Object result = doMain.invoke( mavenCli, new Object[] { cliArgs, workingDirectory, out, out } );
92
93 return ( (Number) result ).intValue();
94 }
95 finally
96 {
97 Thread.currentThread().setContextClassLoader( originalClassLoader );
98
99 System.setProperties( originalProperties );
100 }
101 }
102 catch ( IllegalAccessException e )
103 {
104 throw new LauncherException( "Failed to run Maven: " + e.getMessage(), e );
105 }
106 catch ( InvocationTargetException e )
107 {
108 throw new LauncherException( "Failed to run Maven: " + e.getMessage(), e );
109 }
110 finally
111 {
112 if ( logFile != null )
113 {
114 out.close();
115 }
116 }
117 }
118
119 }