View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.cli.configuration;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.io.File;
26  import java.io.FileNotFoundException;
27  import java.util.List;
28  import java.util.Properties;
29  
30  import org.apache.commons.cli.CommandLine;
31  import org.apache.maven.artifact.InvalidRepositoryException;
32  import org.apache.maven.bridge.MavenRepositorySystem;
33  import org.apache.maven.building.Source;
34  import org.apache.maven.cli.CLIManager;
35  import org.apache.maven.cli.CliRequest;
36  import org.apache.maven.execution.MavenExecutionRequest;
37  import org.apache.maven.execution.MavenExecutionRequestPopulationException;
38  import org.apache.maven.settings.Mirror;
39  import org.apache.maven.settings.Profile;
40  import org.apache.maven.settings.Proxy;
41  import org.apache.maven.settings.Repository;
42  import org.apache.maven.settings.Server;
43  import org.apache.maven.settings.Settings;
44  import org.apache.maven.settings.SettingsUtils;
45  import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
46  import org.apache.maven.settings.building.SettingsBuilder;
47  import org.apache.maven.settings.building.SettingsBuildingRequest;
48  import org.apache.maven.settings.building.SettingsBuildingResult;
49  import org.apache.maven.settings.building.SettingsProblem;
50  import org.apache.maven.settings.crypto.SettingsDecrypter;
51  import org.slf4j.Logger;
52  import org.slf4j.LoggerFactory;
53  
54  import static org.apache.maven.cli.ResolveFile.resolveFile;
55  
56  /**
57   * SettingsXmlConfigurationProcessor
58   */
59  @Named(SettingsXmlConfigurationProcessor.HINT)
60  @Singleton
61  public class SettingsXmlConfigurationProcessor implements ConfigurationProcessor {
62      public static final String HINT = "settings";
63  
64      public static final String USER_HOME = System.getProperty("user.home");
65  
66      public static final File USER_MAVEN_CONFIGURATION_HOME = new File(USER_HOME, ".m2");
67  
68      public static final File DEFAULT_USER_SETTINGS_FILE = new File(USER_MAVEN_CONFIGURATION_HOME, "settings.xml");
69  
70      public static final File DEFAULT_PROJECT_SETTINGS_FILE = new File(".mvn", "settings.xml");
71  
72      public static final File DEFAULT_INSTALLATION_SETTINGS_FILE =
73              new File(System.getProperty("maven.conf"), "settings.xml");
74  
75      private static final Logger LOGGER = LoggerFactory.getLogger(SettingsXmlConfigurationProcessor.class);
76  
77      private final SettingsBuilder settingsBuilder;
78      private final SettingsDecrypter settingsDecrypter;
79  
80      @Inject
81      public SettingsXmlConfigurationProcessor(SettingsBuilder settingsBuilder, SettingsDecrypter settingsDecrypter) {
82          this.settingsBuilder = settingsBuilder;
83          this.settingsDecrypter = settingsDecrypter;
84      }
85  
86      @Override
87      public void process(CliRequest cliRequest) throws Exception {
88          CommandLine commandLine = cliRequest.getCommandLine();
89          String workingDirectory = cliRequest.getWorkingDirectory();
90          MavenExecutionRequest request = cliRequest.getRequest();
91  
92          File userSettingsFile;
93  
94          if (commandLine.hasOption(CLIManager.ALTERNATE_USER_SETTINGS)) {
95              userSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_USER_SETTINGS));
96              userSettingsFile = resolveFile(userSettingsFile, workingDirectory);
97  
98              if (!userSettingsFile.isFile()) {
99                  throw new FileNotFoundException("The specified user settings file does not exist: " + userSettingsFile);
100             }
101         } else {
102             userSettingsFile = DEFAULT_USER_SETTINGS_FILE;
103         }
104 
105         File projectSettingsFile;
106 
107         if (commandLine.hasOption(CLIManager.ALTERNATE_PROJECT_SETTINGS)) {
108             projectSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_PROJECT_SETTINGS));
109             projectSettingsFile = resolveFile(projectSettingsFile, workingDirectory);
110 
111             if (!projectSettingsFile.isFile()) {
112                 throw new FileNotFoundException(
113                         "The specified project settings file does not exist: " + projectSettingsFile);
114             }
115         } else if (cliRequest.getRootDirectory() != null) {
116             projectSettingsFile = DEFAULT_PROJECT_SETTINGS_FILE;
117             projectSettingsFile = resolveFile(
118                     projectSettingsFile, cliRequest.getRootDirectory().toString());
119         } else {
120             projectSettingsFile = null;
121         }
122 
123         File installationSettingsFile;
124 
125         if (commandLine.hasOption(CLIManager.ALTERNATE_INSTALLATION_SETTINGS)) {
126             installationSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_INSTALLATION_SETTINGS));
127             installationSettingsFile = resolveFile(installationSettingsFile, workingDirectory);
128 
129             if (!installationSettingsFile.isFile()) {
130                 throw new FileNotFoundException(
131                         "The specified installation settings file does not exist: " + installationSettingsFile);
132             }
133         } else if (commandLine.hasOption(CLIManager.ALTERNATE_GLOBAL_SETTINGS)) {
134             installationSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_GLOBAL_SETTINGS));
135             installationSettingsFile = resolveFile(installationSettingsFile, workingDirectory);
136 
137             if (!installationSettingsFile.isFile()) {
138                 throw new FileNotFoundException(
139                         "The specified installation settings file does not exist: " + installationSettingsFile);
140             }
141         } else {
142             installationSettingsFile = DEFAULT_INSTALLATION_SETTINGS_FILE;
143         }
144 
145         request.setInstallationSettingsFile(installationSettingsFile);
146         request.setProjectSettingsFile(projectSettingsFile);
147         request.setUserSettingsFile(userSettingsFile);
148 
149         SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
150         settingsRequest.setGlobalSettingsFile(installationSettingsFile);
151         settingsRequest.setProjectSettingsFile(projectSettingsFile);
152         settingsRequest.setUserSettingsFile(userSettingsFile);
153         settingsRequest.setSystemProperties(cliRequest.getSystemProperties());
154         Properties props = cliRequest.getUserProperties();
155         if (cliRequest.getRootDirectory() != null) {
156             props = new Properties();
157             props.putAll(cliRequest.getUserProperties());
158             props.put("session.rootDirectory", cliRequest.getRootDirectory().toString());
159         }
160         settingsRequest.setUserProperties(props);
161 
162         if (request.getEventSpyDispatcher() != null) {
163             request.getEventSpyDispatcher().onEvent(settingsRequest);
164         }
165 
166         LOGGER.debug(
167                 "Reading installation settings from '{}'",
168                 getLocation(settingsRequest.getGlobalSettingsSource(), settingsRequest.getGlobalSettingsFile()));
169         LOGGER.debug(
170                 "Reading project settings from '{}'",
171                 getLocation(settingsRequest.getProjectSettingsSource(), settingsRequest.getProjectSettingsFile()));
172         LOGGER.debug(
173                 "Reading user settings from '{}'",
174                 getLocation(settingsRequest.getUserSettingsSource(), settingsRequest.getUserSettingsFile()));
175 
176         SettingsBuildingResult settingsResult = settingsBuilder.build(settingsRequest);
177 
178         if (request.getEventSpyDispatcher() != null) {
179             request.getEventSpyDispatcher().onEvent(settingsResult);
180         }
181 
182         populateFromSettings(request, settingsResult.getEffectiveSettings());
183 
184         if (!settingsResult.getProblems().isEmpty() && LOGGER.isWarnEnabled()) {
185             LOGGER.warn("");
186             LOGGER.warn("Some problems were encountered while building the effective settings");
187 
188             for (SettingsProblem problem : settingsResult.getProblems()) {
189                 LOGGER.warn("{} @ {}", problem.getMessage(), problem.getLocation());
190             }
191             LOGGER.warn("");
192         }
193     }
194 
195     private MavenExecutionRequest populateFromSettings(MavenExecutionRequest request, Settings settings)
196             throws MavenExecutionRequestPopulationException {
197         if (settings == null) {
198             return request;
199         }
200 
201         request.setOffline(settings.isOffline());
202 
203         request.setInteractiveMode(settings.isInteractiveMode());
204 
205         request.setPluginGroups(settings.getPluginGroups());
206 
207         request.setLocalRepositoryPath(settings.getLocalRepository());
208 
209         for (Server server : settings.getServers()) {
210             request.addServer(server);
211         }
212 
213         //  <proxies>
214         //    <proxy>
215         //      <active>true</active>
216         //      <protocol>http</protocol>
217         //      <host>proxy.somewhere.com</host>
218         //      <port>8080</port>
219         //      <username>proxyuser</username>
220         //      <password>somepassword</password>
221         //      <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
222         //    </proxy>
223         //  </proxies>
224 
225         for (Proxy proxy : settings.getProxies()) {
226             if (!proxy.isActive()) {
227                 continue;
228             }
229 
230             request.addProxy(proxy);
231         }
232 
233         // <mirrors>
234         //   <mirror>
235         //     <id>nexus</id>
236         //     <mirrorOf>*</mirrorOf>
237         //     <url>http://repository.sonatype.org/content/groups/public</url>
238         //   </mirror>
239         // </mirrors>
240 
241         for (Mirror mirror : settings.getMirrors()) {
242             request.addMirror(mirror);
243         }
244 
245         for (Repository remoteRepository : settings.getRepositories()) {
246             try {
247                 request.addRemoteRepository(MavenRepositorySystem.buildArtifactRepository(remoteRepository));
248             } catch (InvalidRepositoryException e) {
249                 // do nothing for now
250             }
251         }
252 
253         for (Repository pluginRepository : settings.getPluginRepositories()) {
254             try {
255                 request.addPluginArtifactRepository(MavenRepositorySystem.buildArtifactRepository(pluginRepository));
256             } catch (InvalidRepositoryException e) {
257                 // do nothing for now
258             }
259         }
260 
261         request.setActiveProfiles(settings.getActiveProfiles());
262 
263         for (Profile rawProfile : settings.getProfiles()) {
264             request.addProfile(SettingsUtils.convertFromSettingsProfile(rawProfile));
265 
266             if (settings.getActiveProfiles().contains(rawProfile.getId())) {
267                 List<Repository> remoteRepositories = rawProfile.getRepositories();
268                 for (Repository remoteRepository : remoteRepositories) {
269                     try {
270                         request.addRemoteRepository(MavenRepositorySystem.buildArtifactRepository(remoteRepository));
271                     } catch (InvalidRepositoryException e) {
272                         // do nothing for now
273                     }
274                 }
275 
276                 List<Repository> pluginRepositories = rawProfile.getPluginRepositories();
277                 for (Repository pluginRepository : pluginRepositories) {
278                     try {
279                         request.addPluginArtifactRepository(
280                                 MavenRepositorySystem.buildArtifactRepository(pluginRepository));
281                     } catch (InvalidRepositoryException e) {
282                         // do nothing for now
283                     }
284                 }
285             }
286         }
287         return request;
288     }
289 
290     private Object getLocation(Source source, File defaultLocation) {
291         if (source != null) {
292             return source.getLocation();
293         }
294         return defaultLocation;
295     }
296 }