View Javadoc
1   /*
2    * #%L
3    * settings4j
4    * ===============================================================
5    * Copyright (C) 2008 - 2015 Brabenetz Harald, Austria
6    * ===============================================================
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * 
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   * 
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package org.settings4j.contentresolver;
21  
22  import org.apache.commons.lang3.Validate;
23  import org.settings4j.ContentResolver;
24  import org.settings4j.Filter;
25  
26  /**
27   * Wrapper to add a {@link Filter} which is used before the given {@link ContentResolver} is called.
28   *
29   * @author Harald.Brabenetz
30   *
31   */
32  public class FilteredContentResolverWrapper implements ContentResolver {
33  
34      private final ContentResolver targetContentResolver;
35      private final Filter filter;
36  
37      /**
38       * @param targetContentResolver The {@link ContentResolver} where the settings
39       *  should be read if the Filter allows it.
40       * @param filter the {@link Filter} which defines if an key should be read from the given {@link ContentResolver}.
41       */
42      public FilteredContentResolverWrapper(final ContentResolver targetContentResolver, final Filter filter) {
43          super();
44          Validate.notNull(targetContentResolver, "FilteredContentResolverWrapper needs a ContentResolver Object");
45          Validate.notNull(filter, "FilteredContentResolverWrapper needs a Filter Object");
46          this.targetContentResolver = targetContentResolver;
47          this.filter = filter;
48      }
49  
50      @Override
51      public void addContentResolver(final ContentResolver contentResolver) {
52          this.targetContentResolver.addContentResolver(contentResolver);
53      }
54  
55      @Override
56      public byte[] getContent(final String key) {
57          if (!this.filter.isValid(key)) {
58              return null;
59          }
60          return this.targetContentResolver.getContent(key);
61      }
62  }