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_GLOBAL_SETTINGS_FILE = new File(System.getProperty("maven.conf"), "settings.xml");
73  
74      private static final Logger LOGGER = LoggerFactory.getLogger(SettingsXmlConfigurationProcessor.class);
75  
76      private final SettingsBuilder settingsBuilder;
77      private final SettingsDecrypter settingsDecrypter;
78  
79      @Inject
80      public SettingsXmlConfigurationProcessor(SettingsBuilder settingsBuilder, SettingsDecrypter settingsDecrypter) {
81          this.settingsBuilder = settingsBuilder;
82          this.settingsDecrypter = settingsDecrypter;
83      }
84  
85      @Override
86      public void process(CliRequest cliRequest) throws Exception {
87          CommandLine commandLine = cliRequest.getCommandLine();
88          String workingDirectory = cliRequest.getWorkingDirectory();
89          MavenExecutionRequest request = cliRequest.getRequest();
90  
91          File userSettingsFile;
92  
93          if (commandLine.hasOption(CLIManager.ALTERNATE_USER_SETTINGS)) {
94              userSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_USER_SETTINGS));
95              userSettingsFile = resolveFile(userSettingsFile, workingDirectory);
96  
97              if (!userSettingsFile.isFile()) {
98                  throw new FileNotFoundException("The specified user settings file does not exist: " + userSettingsFile);
99              }
100         } else {
101             userSettingsFile = DEFAULT_USER_SETTINGS_FILE;
102         }
103 
104         File projectSettingsFile;
105 
106         if (commandLine.hasOption(CLIManager.ALTERNATE_PROJECT_SETTINGS)) {
107             projectSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_PROJECT_SETTINGS));
108             projectSettingsFile = resolveFile(projectSettingsFile, workingDirectory);
109 
110             if (!projectSettingsFile.isFile()) {
111                 throw new FileNotFoundException(
112                         "The specified project settings file does not exist: " + projectSettingsFile);
113             }
114         } else if (cliRequest.getRootDirectory() != null) {
115             projectSettingsFile = DEFAULT_PROJECT_SETTINGS_FILE;
116             projectSettingsFile = resolveFile(
117                     projectSettingsFile, cliRequest.getRootDirectory().toString());
118         } else {
119             projectSettingsFile = null;
120         }
121 
122         File globalSettingsFile;
123 
124         if (commandLine.hasOption(CLIManager.ALTERNATE_GLOBAL_SETTINGS)) {
125             globalSettingsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_GLOBAL_SETTINGS));
126             globalSettingsFile = resolveFile(globalSettingsFile, workingDirectory);
127 
128             if (!globalSettingsFile.isFile()) {
129                 throw new FileNotFoundException(
130                         "The specified global settings file does not exist: " + globalSettingsFile);
131             }
132         } else {
133             globalSettingsFile = DEFAULT_GLOBAL_SETTINGS_FILE;
134         }
135 
136         request.setGlobalSettingsFile(globalSettingsFile);
137         request.setProjectSettingsFile(projectSettingsFile);
138         request.setUserSettingsFile(userSettingsFile);
139 
140         SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
141         settingsRequest.setGlobalSettingsFile(globalSettingsFile);
142         settingsRequest.setProjectSettingsFile(projectSettingsFile);
143         settingsRequest.setUserSettingsFile(userSettingsFile);
144         settingsRequest.setSystemProperties(cliRequest.getSystemProperties());
145         Properties props = cliRequest.getUserProperties();
146         if (cliRequest.getRootDirectory() != null) {
147             props = new Properties();
148             props.putAll(cliRequest.getUserProperties());
149             props.put("session.rootDirectory", cliRequest.getRootDirectory().toString());
150         }
151         settingsRequest.setUserProperties(props);
152 
153         if (request.getEventSpyDispatcher() != null) {
154             request.getEventSpyDispatcher().onEvent(settingsRequest);
155         }
156 
157         LOGGER.debug(
158                 "Reading global settings from '{}'",
159                 getLocation(settingsRequest.getGlobalSettingsSource(), settingsRequest.getGlobalSettingsFile()));
160         LOGGER.debug(
161                 "Reading project settings from '{}'",
162                 getLocation(settingsRequest.getProjectSettingsSource(), settingsRequest.getProjectSettingsFile()));
163         LOGGER.debug(
164                 "Reading user settings from '{}'",
165                 getLocation(settingsRequest.getUserSettingsSource(), settingsRequest.getUserSettingsFile()));
166 
167         SettingsBuildingResult settingsResult = settingsBuilder.build(settingsRequest);
168 
169         if (request.getEventSpyDispatcher() != null) {
170             request.getEventSpyDispatcher().onEvent(settingsResult);
171         }
172 
173         populateFromSettings(request, settingsResult.getEffectiveSettings());
174 
175         if (!settingsResult.getProblems().isEmpty() && LOGGER.isWarnEnabled()) {
176             LOGGER.warn("");
177             LOGGER.warn("Some problems were encountered while building the effective settings");
178 
179             for (SettingsProblem problem : settingsResult.getProblems()) {
180                 LOGGER.warn("{} @ {}", problem.getMessage(), problem.getLocation());
181             }
182             LOGGER.warn("");
183         }
184     }
185 
186     private MavenExecutionRequest populateFromSettings(MavenExecutionRequest request, Settings settings)
187             throws MavenExecutionRequestPopulationException {
188         if (settings == null) {
189             return request;
190         }
191 
192         request.setOffline(settings.isOffline());
193 
194         request.setInteractiveMode(settings.isInteractiveMode());
195 
196         request.setPluginGroups(settings.getPluginGroups());
197 
198         request.setLocalRepositoryPath(settings.getLocalRepository());
199 
200         for (Server server : settings.getServers()) {
201             request.addServer(server);
202         }
203 
204         //  <proxies>
205         //    <proxy>
206         //      <active>true</active>
207         //      <protocol>http</protocol>
208         //      <host>proxy.somewhere.com</host>
209         //      <port>8080</port>
210         //      <username>proxyuser</username>
211         //      <password>somepassword</password>
212         //      <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
213         //    </proxy>
214         //  </proxies>
215 
216         for (Proxy proxy : settings.getProxies()) {
217             if (!proxy.isActive()) {
218                 continue;
219             }
220 
221             request.addProxy(proxy);
222         }
223 
224         // <mirrors>
225         //   <mirror>
226         //     <id>nexus</id>
227         //     <mirrorOf>*</mirrorOf>
228         //     <url>http://repository.sonatype.org/content/groups/public</url>
229         //   </mirror>
230         // </mirrors>
231 
232         for (Mirror mirror : settings.getMirrors()) {
233             request.addMirror(mirror);
234         }
235 
236         for (Repository remoteRepository : settings.getRepositories()) {
237             try {
238                 request.addRemoteRepository(MavenRepositorySystem.buildArtifactRepository(remoteRepository));
239             } catch (InvalidRepositoryException e) {
240                 // do nothing for now
241             }
242         }
243 
244         for (Repository pluginRepository : settings.getPluginRepositories()) {
245             try {
246                 request.addPluginArtifactRepository(MavenRepositorySystem.buildArtifactRepository(pluginRepository));
247             } catch (InvalidRepositoryException e) {
248                 // do nothing for now
249             }
250         }
251 
252         request.setActiveProfiles(settings.getActiveProfiles());
253 
254         for (Profile rawProfile : settings.getProfiles()) {
255             request.addProfile(SettingsUtils.convertFromSettingsProfile(rawProfile));
256 
257             if (settings.getActiveProfiles().contains(rawProfile.getId())) {
258                 List<Repository> remoteRepositories = rawProfile.getRepositories();
259                 for (Repository remoteRepository : remoteRepositories) {
260                     try {
261                         request.addRemoteRepository(MavenRepositorySystem.buildArtifactRepository(remoteRepository));
262                     } catch (InvalidRepositoryException e) {
263                         // do nothing for now
264                     }
265                 }
266 
267                 List<Repository> pluginRepositories = rawProfile.getPluginRepositories();
268                 for (Repository pluginRepository : pluginRepositories) {
269                     try {
270                         request.addPluginArtifactRepository(
271                                 MavenRepositorySystem.buildArtifactRepository(pluginRepository));
272                     } catch (InvalidRepositoryException e) {
273                         // do nothing for now
274                     }
275                 }
276             }
277         }
278         return request;
279     }
280 
281     private Object getLocation(Source source, File defaultLocation) {
282         if (source != null) {
283             return source.getLocation();
284         }
285         return defaultLocation;
286     }
287 }