b887c2d95a50150bd696aeb34a0eeafc0ec3ed06
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / repo / util / AbstractSchemaRepository.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.model.repo.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.collect.ArrayListMultimap;
12 import com.google.common.collect.ListMultimap;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Multimap;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.FutureFallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.Map;
27 import javax.annotation.Nonnull;
28 import javax.annotation.concurrent.GuardedBy;
29 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
30 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
31 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
38 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
39 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
42 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Abstract base class for {@link SchemaRepository} implementations. It handles registration
48  * and lookup of schema sources, subclasses need only to provide their own
49  * {@link #createSchemaContextFactory(SchemaSourceFilter)} implementation.
50  */
51 @Beta
52 public abstract class AbstractSchemaRepository implements SchemaRepository, SchemaSourceRegistry {
53     private static final Logger LOG = LoggerFactory.getLogger(AbstractSchemaRepository.class);
54     private static final ExceptionMapper<SchemaSourceException> FETCH_MAPPER = ReflectiveExceptionMapper.create(
55             "Schema source fetch", SchemaSourceException.class);
56
57     /*
58      * Source identifier -> representation -> provider map. We usually are looking for
59      * a specific representation of a source.
60      */
61     @GuardedBy("this")
62     private final Map<SourceIdentifier, ListMultimap<Class<? extends SchemaSourceRepresentation>,
63             AbstractSchemaSourceRegistration<?>>> sources = new HashMap<>();
64
65     /*
66      * Schema source listeners.
67      */
68     @GuardedBy("this")
69     private final Collection<SchemaListenerRegistration> listeners = new ArrayList<>();
70
71     private static <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> fetchSource(
72             final SourceIdentifier id, final Iterator<AbstractSchemaSourceRegistration<?>> it) {
73         final AbstractSchemaSourceRegistration<?> reg = it.next();
74
75         @SuppressWarnings("unchecked")
76         final CheckedFuture<? extends T, SchemaSourceException> f =
77             ((SchemaSourceProvider<T>)reg.getProvider()).getSource(id);
78
79         return Futures.makeChecked(Futures.withFallback(f, new FutureFallback<T>() {
80             @Override
81             public ListenableFuture<T> create(@Nonnull final Throwable cause) throws SchemaSourceException {
82                 LOG.debug("Failed to acquire source from {}", reg, cause);
83
84                 if (it.hasNext()) {
85                     return fetchSource(id, it);
86                 }
87
88                 throw new MissingSchemaSourceException("All available providers exhausted", id, cause);
89             }
90         }), FETCH_MAPPER);
91     }
92
93     @Override
94     public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(
95             @Nonnull final SourceIdentifier id, @Nonnull final Class<T> representation) {
96         final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations;
97
98         synchronized (this) {
99             final ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs =
100                 sources.get(id);
101             if (srcs == null) {
102                 return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
103                             "No providers registered for source" + id, id));
104             }
105
106             sortedSchemaSourceRegistrations = Lists.newArrayList(srcs.get(representation));
107         }
108
109         // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
110         Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);
111
112         final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
113         if (!regs.hasNext()) {
114             return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
115                         "No providers for source " + id + " representation " + representation + " available", id));
116         }
117
118         CheckedFuture<T, SchemaSourceException> fetchSourceFuture = fetchSource(id, regs);
119         // Add callback to notify cache listeners about encountered schema
120         Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
121             @Override
122             public void onSuccess(final T result) {
123                 for (final SchemaListenerRegistration listener : listeners) {
124                     listener.getInstance().schemaSourceEncountered(result);
125                 }
126             }
127
128             @Override
129             @SuppressWarnings("checkstyle:parameterName")
130             public void onFailure(@Nonnull final Throwable t) {
131                 LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
132             }
133         });
134
135         return fetchSourceFuture;
136     }
137
138     private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source,
139             final AbstractSchemaSourceRegistration<T> reg) {
140         ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> map =
141             sources.get(source.getSourceIdentifier());
142         if (map == null) {
143             map = ArrayListMultimap.create();
144             sources.put(source.getSourceIdentifier(), map);
145         }
146
147         map.put(source.getRepresentation(), reg);
148
149         final Collection<PotentialSchemaSource<?>> reps = Collections.singleton(source);
150         for (SchemaListenerRegistration l : listeners) {
151             l.getInstance().schemaSourceRegistered(reps);
152         }
153     }
154
155     private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source,
156             final SchemaSourceRegistration<?> reg) {
157         final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m =
158             sources.get(source.getSourceIdentifier());
159         if (m != null) {
160             m.remove(source.getRepresentation(), reg);
161
162             for (SchemaListenerRegistration l : listeners) {
163                 l.getInstance().schemaSourceUnregistered(source);
164             }
165
166             if (m.isEmpty()) {
167                 sources.remove(source.getSourceIdentifier());
168             }
169         }
170     }
171
172     @Override
173     public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(
174             final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
175         final PotentialSchemaSource<T> src = source.cachedReference();
176
177         final AbstractSchemaSourceRegistration<T> ret = new AbstractSchemaSourceRegistration<T>(provider, src) {
178             @Override
179             protected void removeRegistration() {
180                 removeSource(src, this);
181             }
182         };
183
184         addSource(src, ret);
185         return ret;
186     }
187
188     @Override
189     public SchemaListenerRegistration registerSchemaSourceListener(final SchemaSourceListener listener) {
190         final SchemaListenerRegistration ret = new AbstractSchemaListenerRegistration(listener) {
191             @Override
192             protected void removeRegistration() {
193                 listeners.remove(this);
194             }
195         };
196
197         synchronized (this) {
198             final Collection<PotentialSchemaSource<?>> col = new ArrayList<>();
199             for (Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m
200                     : sources.values()) {
201                 for (AbstractSchemaSourceRegistration<?> r : m.values()) {
202                     col.add(r.getInstance());
203                 }
204             }
205
206             // Notify first, so translator-type listeners, who react by registering a source
207             // do not cause infinite loop.
208             listener.schemaSourceRegistered(col);
209             listeners.add(ret);
210         }
211         return ret;
212     }
213
214     private static class SchemaProviderCostComparator implements Comparator<AbstractSchemaSourceRegistration<?>> {
215         public static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
216
217         @Override
218         public int compare(final AbstractSchemaSourceRegistration<?> o1, final AbstractSchemaSourceRegistration<?> o2) {
219             return o1.getInstance().getCost() - o2.getInstance().getCost();
220         }
221     }
222 }