1 /* ***************************************************************************
2 * Copyright (c) 2008 Brabenetz Harald, Austria.
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 *****************************************************************************/
17 package org.settings4j.contentresolver;
18
19 import org.settings4j.ContentResolver;
20
21 /**
22 * The UnionContentResolver can be an container for many other {@link ContentResolver}
23 * which will be processed in sequence.
24 * <p>
25 * the first result of a ContentResolver which are a not-null value will be used as result.
26 *
27 * @author Harald.Brabenetz
28 */
29 public class UnionContentResolver implements ContentResolver {
30
31 private ContentResolver[] contentResolvers = new ContentResolver[0];
32
33 /**
34 * Default Constructor.
35 */
36 public UnionContentResolver() {
37 super();
38 }
39
40 /**
41 * Constructor with the first {@link ContentResolver}.
42 *
43 * @param contentResolver with the first ContentResolver.
44 */
45 public UnionContentResolver(final ContentResolver contentResolver) {
46 super();
47 addContentResolverInternal(contentResolver);
48 }
49
50 /** {@inheritDoc} */
51 public void addContentResolver(final ContentResolver contentResolver) {
52 synchronized (this) {
53 addContentResolverInternal(contentResolver);
54 }
55 }
56
57 private void addContentResolverInternal(final ContentResolver contentResolver) {
58 final ContentResolver[] contentResolversNew = new ContentResolver[this.contentResolvers.length + 1];
59 for (int i = 0; i < this.contentResolvers.length; i++) {
60 contentResolversNew[i] = this.contentResolvers[i];
61 }
62 contentResolversNew[this.contentResolvers.length] = contentResolver;
63
64 this.contentResolvers = contentResolversNew;
65 }
66
67 /** {@inheritDoc} */
68 public byte[] getContent(final String key) {
69 byte[] result = null;
70 for (ContentResolver contentResolver : contentResolvers) {
71 result = contentResolver.getContent(key);
72 if (result != null) {
73 return result;
74 }
75 }
76 return result;
77 }
78 }