View Javadoc

1   package org.apache.onami.logging.core;
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 static java.lang.String.format;
23  import static java.lang.reflect.Modifier.isFinal;
24  
25  import java.lang.reflect.Field;
26  
27  import com.google.inject.MembersInjector;
28  import com.google.inject.ProvisionException;
29  
30  /**
31   * The abstract Logger injector implementation, takes care of injecting the
32   * concrete Logger implementation to the logged filed.
33   */
34  public abstract class AbstractLoggerInjector<L>
35      implements MembersInjector<L>
36  {
37  
38      /**
39       * The logger field has to be injected.
40       */
41      private final Field field;
42  
43      /**
44       * Creates a new Logger injector.
45       *
46       * @param field the logger field has to be injected.
47       */
48      public AbstractLoggerInjector( Field field )
49      {
50          this.field = field;
51          this.field.setAccessible(true);
52      }
53  
54      /**
55       * {@inheritDoc}
56       */
57      public final void injectMembers( Object target )
58      {
59          if ( isFinal( field.getModifiers() ) )
60          {
61              return;
62          }
63  
64          try
65          {
66              if ( field.get( target ) == null )
67              {
68                  field.set( target, createLogger( target.getClass() ) );
69              }
70          }
71          catch ( Exception e )
72          {
73              throw new ProvisionException( format( "Impossible to set logger for field '%s', see nested exception: %s",
74                                                    field, e.getMessage() ) );
75          }
76      }
77  
78      /**
79       * Creates a new Logger implementation for the specified Class.
80       *
81       * @return a new Logger implementation.
82       */
83      protected abstract L createLogger(Class<?> klass);
84  
85  }