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