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.logging;
20  
21  import java.io.IOException;
22  import java.net.URL;
23  import java.util.Enumeration;
24  import java.util.Properties;
25  
26  import org.apache.maven.cli.logging.impl.UnsupportedSlf4jBindingConfiguration;
27  import org.codehaus.plexus.util.PropertyUtils;
28  import org.slf4j.ILoggerFactory;
29  
30  /**
31   * Slf4jConfiguration factory, loading implementations from <code>META-INF/maven/slf4j-configuration.properties</code>
32   * configuration files in class loader: key is the class name of the ILoggerFactory, value is the class name of
33   * the corresponding Slf4jConfiguration.
34   *
35   * @author Hervé Boutemy
36   * @since 3.1.0
37   */
38  public class Slf4jConfigurationFactory {
39      public static final String RESOURCE = "META-INF/maven/slf4j-configuration.properties";
40  
41      public static Slf4jConfiguration getConfiguration(ILoggerFactory loggerFactory) {
42          String slf4jBinding = loggerFactory.getClass().getCanonicalName();
43  
44          try {
45              Enumeration<URL> resources =
46                      Slf4jConfigurationFactory.class.getClassLoader().getResources(RESOURCE);
47  
48              while (resources.hasMoreElements()) {
49                  URL resource = resources.nextElement();
50                  try {
51                      Properties conf = PropertyUtils.loadProperties(resource.openStream());
52                      String impl = conf.getProperty(slf4jBinding);
53                      if (impl != null) {
54                          return (Slf4jConfiguration) Class.forName(impl).newInstance();
55                      }
56                  } catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
57                      // ignore and move on to the next
58                  }
59              }
60          } catch (IOException ex) {
61              // ignore
62          }
63  
64          return new UnsupportedSlf4jBindingConfiguration();
65      }
66  }