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