View Javadoc
1   package org.eclipse.aether.impl;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   * 
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.lang.reflect.Constructor;
23  import java.lang.reflect.Modifier;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.Collections;
27  import java.util.HashMap;
28  import java.util.LinkedHashSet;
29  import java.util.List;
30  import java.util.Map;
31  import static java.util.Objects.requireNonNull;
32  
33  import org.eclipse.aether.RepositorySystem;
34  import org.eclipse.aether.internal.impl.DefaultArtifactResolver;
35  import org.eclipse.aether.internal.impl.DefaultChecksumPolicyProvider;
36  import org.eclipse.aether.internal.impl.DefaultTrackingFileManager;
37  import org.eclipse.aether.internal.impl.TrackingFileManager;
38  import org.eclipse.aether.internal.impl.collect.DefaultDependencyCollector;
39  import org.eclipse.aether.internal.impl.DefaultDeployer;
40  import org.eclipse.aether.internal.impl.DefaultFileProcessor;
41  import org.eclipse.aether.internal.impl.DefaultInstaller;
42  import org.eclipse.aether.internal.impl.DefaultLocalRepositoryProvider;
43  import org.eclipse.aether.internal.impl.DefaultMetadataResolver;
44  import org.eclipse.aether.internal.impl.DefaultOfflineController;
45  import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager;
46  import org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider;
47  import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher;
48  import org.eclipse.aether.internal.impl.DefaultRepositoryLayoutProvider;
49  import org.eclipse.aether.internal.impl.DefaultRepositorySystem;
50  import org.eclipse.aether.internal.impl.DefaultTransporterProvider;
51  import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager;
52  import org.eclipse.aether.internal.impl.DefaultUpdatePolicyAnalyzer;
53  import org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManagerFactory;
54  import org.eclipse.aether.internal.impl.Maven2RepositoryLayoutFactory;
55  import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
56  import org.eclipse.aether.internal.impl.slf4j.Slf4jLoggerFactory;
57  import org.eclipse.aether.internal.impl.synccontext.DefaultSyncContextFactory;
58  import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactorySelector;
59  import org.eclipse.aether.internal.impl.synccontext.named.SimpleNamedLockFactorySelector;
60  import org.eclipse.aether.spi.connector.checksum.ChecksumPolicyProvider;
61  import org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory;
62  import org.eclipse.aether.spi.connector.layout.RepositoryLayoutProvider;
63  import org.eclipse.aether.spi.connector.transport.TransporterProvider;
64  import org.eclipse.aether.spi.io.FileProcessor;
65  import org.eclipse.aether.spi.localrepo.LocalRepositoryManagerFactory;
66  import org.eclipse.aether.spi.locator.Service;
67  import org.eclipse.aether.spi.locator.ServiceLocator;
68  import org.eclipse.aether.spi.log.LoggerFactory;
69  import org.eclipse.aether.spi.synccontext.SyncContextFactory;
70  
71  /**
72   * A simple service locator that is already setup with all components from this library. To acquire a complete
73   * repository system, clients need to add an artifact descriptor reader, a version resolver, a version range resolver
74   * and optionally some repository connector and transporter factories to access remote repositories. Once the locator is
75   * fully populated, the repository system can be created like this:
76   * 
77   * <pre>
78   * RepositorySystem repoSystem = serviceLocator.getService( RepositorySystem.class );
79   * </pre>
80   * 
81   * <em>Note:</em> This class is not thread-safe. Clients are expected to create the service locator and the repository
82   * system on a single thread.
83   *
84   * @deprecated Use some out-of-the-box DI implementation instead.
85   */
86  @Deprecated
87  public final class DefaultServiceLocator
88      implements ServiceLocator
89  {
90  
91      private class Entry<T>
92      {
93  
94          private final Class<T> type;
95  
96          private final Collection<Object> providers;
97  
98          private List<T> instances;
99  
100         Entry( Class<T> type )
101         {
102             this.type = requireNonNull( type, "service type cannot be null" );
103             providers = new LinkedHashSet<>( 8 );
104         }
105 
106         public synchronized void setServices( T... services )
107         {
108             providers.clear();
109             if ( services != null )
110             {
111                 for ( T service : services )
112                 {
113                     providers.add( requireNonNull( service, "service instance cannot be null" ) );
114                 }
115             }
116             instances = null;
117         }
118 
119         public synchronized void setService( Class<? extends T> impl )
120         {
121             providers.clear();
122             addService( impl );
123         }
124 
125         public synchronized void addService( Class<? extends T> impl )
126         {
127             providers.add( requireNonNull( impl, "implementation class cannot be null" ) );
128             instances = null;
129         }
130 
131         public T getInstance()
132         {
133             List<T> instances = getInstances();
134             return instances.isEmpty() ? null : instances.get( 0 );
135         }
136 
137         public synchronized List<T> getInstances()
138         {
139             if ( instances == null )
140             {
141                 instances = new ArrayList<>( providers.size() );
142                 for ( Object provider : providers )
143                 {
144                     T instance;
145                     if ( provider instanceof Class )
146                     {
147                         instance = newInstance( (Class<?>) provider );
148                     }
149                     else
150                     {
151                         instance = type.cast( provider );
152                     }
153                     if ( instance != null )
154                     {
155                         instances.add( instance );
156                     }
157                 }
158                 instances = Collections.unmodifiableList( instances );
159             }
160             return instances;
161         }
162 
163         private T newInstance( Class<?> impl )
164         {
165             try
166             {
167                 Constructor<?> constr = impl.getDeclaredConstructor();
168                 if ( !Modifier.isPublic( constr.getModifiers() ) )
169                 {
170                     constr.setAccessible( true );
171                 }
172                 Object obj = constr.newInstance();
173 
174                 T instance = type.cast( obj );
175                 if ( instance instanceof Service )
176                 {
177                     ( (Service) instance ).initService( DefaultServiceLocator.this );
178                 }
179                 return instance;
180             }
181             catch ( Exception | LinkageError e )
182             {
183                 serviceCreationFailed( type, impl, e );
184             }
185             return null;
186         }
187 
188     }
189 
190     private final Map<Class<?>, Entry<?>> entries;
191 
192     private ErrorHandler errorHandler;
193 
194     /**
195      * Creates a new service locator that already knows about all service implementations included this library.
196      */
197     public DefaultServiceLocator()
198     {
199         entries = new HashMap<>();
200 
201         addService( RepositorySystem.class, DefaultRepositorySystem.class );
202         addService( ArtifactResolver.class, DefaultArtifactResolver.class );
203         addService( DependencyCollector.class, DefaultDependencyCollector.class );
204         addService( Deployer.class, DefaultDeployer.class );
205         addService( Installer.class, DefaultInstaller.class );
206         addService( MetadataResolver.class, DefaultMetadataResolver.class );
207         addService( RepositoryLayoutProvider.class, DefaultRepositoryLayoutProvider.class );
208         addService( RepositoryLayoutFactory.class, Maven2RepositoryLayoutFactory.class );
209         addService( TransporterProvider.class, DefaultTransporterProvider.class );
210         addService( ChecksumPolicyProvider.class, DefaultChecksumPolicyProvider.class );
211         addService( RepositoryConnectorProvider.class, DefaultRepositoryConnectorProvider.class );
212         addService( RemoteRepositoryManager.class, DefaultRemoteRepositoryManager.class );
213         addService( UpdateCheckManager.class, DefaultUpdateCheckManager.class );
214         addService( UpdatePolicyAnalyzer.class, DefaultUpdatePolicyAnalyzer.class );
215         addService( FileProcessor.class, DefaultFileProcessor.class );
216         addService( org.eclipse.aether.impl.SyncContextFactory.class,
217             org.eclipse.aether.internal.impl.synccontext.legacy.DefaultSyncContextFactory.class );
218         addService( SyncContextFactory.class, DefaultSyncContextFactory.class );
219         addService( RepositoryEventDispatcher.class, DefaultRepositoryEventDispatcher.class );
220         addService( OfflineController.class, DefaultOfflineController.class );
221         addService( LocalRepositoryProvider.class, DefaultLocalRepositoryProvider.class );
222         addService( LocalRepositoryManagerFactory.class, SimpleLocalRepositoryManagerFactory.class );
223         addService( LocalRepositoryManagerFactory.class, EnhancedLocalRepositoryManagerFactory.class );
224         addService( LoggerFactory.class, Slf4jLoggerFactory.class );
225         addService( TrackingFileManager.class, DefaultTrackingFileManager.class );
226         addService( NamedLockFactorySelector.class, SimpleNamedLockFactorySelector.class );
227     }
228 
229     private <T> Entry<T> getEntry( Class<T> type, boolean create )
230     {
231         @SuppressWarnings( "unchecked" )
232         Entry<T> entry = (Entry<T>) entries.get( requireNonNull( type, "service type cannot be null" ) );
233         if ( entry == null && create )
234         {
235             entry = new Entry<>( type );
236             entries.put( type, entry );
237         }
238         return entry;
239     }
240 
241     /**
242      * Sets the implementation class for a service. The specified class must have a no-arg constructor (of any
243      * visibility). If the service implementation itself requires other services for its operation, it should implement
244      * {@link Service} to gain access to this service locator.
245      * 
246      * @param <T> The service type.
247      * @param type The interface describing the service, must not be {@code null}.
248      * @param impl The implementation class of the service, must not be {@code null}.
249      * @return This locator for chaining, never {@code null}.
250      */
251     public <T> DefaultServiceLocator setService( Class<T> type, Class<? extends T> impl )
252     {
253         getEntry( type, true ).setService( impl );
254         return this;
255     }
256 
257     /**
258      * Adds an implementation class for a service. The specified class must have a no-arg constructor (of any
259      * visibility). If the service implementation itself requires other services for its operation, it should implement
260      * {@link Service} to gain access to this service locator.
261      * 
262      * @param <T> The service type.
263      * @param type The interface describing the service, must not be {@code null}.
264      * @param impl The implementation class of the service, must not be {@code null}.
265      * @return This locator for chaining, never {@code null}.
266      */
267     public <T> DefaultServiceLocator addService( Class<T> type, Class<? extends T> impl )
268     {
269         getEntry( type, true ).addService( impl );
270         return this;
271     }
272 
273     /**
274      * Sets the instances for a service.
275      * 
276      * @param <T> The service type.
277      * @param type The interface describing the service, must not be {@code null}.
278      * @param services The instances of the service, may be {@code null} but must not contain {@code null} elements.
279      * @return This locator for chaining, never {@code null}.
280      */
281     public <T> DefaultServiceLocator setServices( Class<T> type, T... services )
282     {
283         getEntry( type, true ).setServices( services );
284         return this;
285     }
286 
287     public <T> T getService( Class<T> type )
288     {
289         Entry<T> entry = getEntry( type, false );
290         return ( entry != null ) ? entry.getInstance() : null;
291     }
292 
293     public <T> List<T> getServices( Class<T> type )
294     {
295         Entry<T> entry = getEntry( type, false );
296         return ( entry != null ) ? entry.getInstances() : null;
297     }
298 
299     private void serviceCreationFailed( Class<?> type, Class<?> impl, Throwable exception )
300     {
301         if ( errorHandler != null )
302         {
303             errorHandler.serviceCreationFailed( type, impl, exception );
304         }
305     }
306 
307     /**
308      * Sets the error handler to use.
309      * 
310      * @param errorHandler The error handler to use, may be {@code null} to ignore/swallow errors.
311      */
312     public void setErrorHandler( ErrorHandler errorHandler )
313     {
314         this.errorHandler = errorHandler;
315     }
316 
317     /**
318      * A hook to customize the handling of errors encountered while locating a service implementation.
319      */
320     public abstract static class ErrorHandler
321     {
322 
323         /**
324          * Handles errors during creation of a service. The default implemention does nothing.
325          * 
326          * @param type The interface describing the service, must not be {@code null}.
327          * @param impl The implementation class of the service, must not be {@code null}.
328          * @param exception The error that occurred while trying to instantiate the implementation class, must not be
329          *            {@code null}.
330          */
331         public void serviceCreationFailed( Class<?> type, Class<?> impl, Throwable exception )
332         {
333         }
334 
335     }
336 
337 }