View Javadoc
1   /*
2    * Copyright 2018 SPF4J.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.spf4j.test.log;
17  
18  import com.google.common.annotations.VisibleForTesting;
19  import com.google.common.collect.Interner;
20  import com.google.common.collect.Interners;
21  import java.util.List;
22  import java.util.Objects;
23  import javax.annotation.Nullable;
24  import javax.annotation.ParametersAreNonnullByDefault;
25  
26  /**
27   * @author Zoltan Farkas
28   */
29  @ParametersAreNonnullByDefault
30  final class CompositeLogHandler implements LogConsumer {
31  
32    private static final Interner<CompositeLogHandler> INTERNER =
33            Interners.newBuilder().concurrencyLevel(8).weak().build();
34  
35    private int hash = 0;
36  
37    @VisibleForTesting
38    final List<LogHandler> logHandlers;
39  
40    private CompositeLogHandler(final List<LogHandler> logHandlers) {
41      this.logHandlers = logHandlers;
42    }
43  
44    @Nullable
45    static LogConsumer from(final List<LogHandler> logHandlers) {
46      if (logHandlers.isEmpty()) {
47        return null;
48      } else {
49        return INTERNER.intern(new CompositeLogHandler(logHandlers));
50      }
51    }
52  
53    @Override
54    public void accept(final TestLogRecord record) {
55      TestLogRecord logRecord = record;
56      for (LogHandler handler : logHandlers) {
57        logRecord = handler.handle(logRecord);
58        if (logRecord == null) {
59          break;
60        }
61      }
62    }
63  
64    @Override
65    public int hashCode() {
66      if (hash == 0) {
67        hash = Objects.hashCode(this.logHandlers);
68        return hash;
69      } else {
70        return hash;
71      }
72    }
73  
74    @Override
75    public boolean equals(final Object obj) {
76      if (this == obj) {
77        return true;
78      }
79      if (obj == null) {
80        return false;
81      }
82      if (getClass() != obj.getClass()) {
83        return false;
84      }
85      final CompositeLogHandler other = (CompositeLogHandler) obj;
86      return Objects.equals(this.logHandlers, other.logHandlers);
87    }
88  
89    @Override
90    public String toString() {
91      return "CompositeLogHandler{" + "logHandlers=" + logHandlers + '}';
92    }
93  
94  }