380a3258877ebdbd2159af9d6fd0fcd246f1ce6d
[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 java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.Map;
28 import javax.annotation.Nonnull;
29 import javax.annotation.concurrent.GuardedBy;
30 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
34 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
35 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
36 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
37 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
38 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
39 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Abstract base class for {@link SchemaRepository} implementations. It handles registration
46  * and lookup of schema sources, subclasses need only to provide their own
47  * {@link #createSchemaContextFactory(SchemaSourceFilter)} 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 Collection<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(
86             @Nonnull final SourceIdentifier id, @Nonnull 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         Collections.sort(sortedSchemaSourceRegistrations, 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(@Nonnull 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     private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source,
147             final SchemaSourceRegistration<?> reg) {
148         final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m =
149             sources.get(source.getSourceIdentifier());
150         if (m != null) {
151             m.remove(source.getRepresentation(), reg);
152
153             for (SchemaListenerRegistration l : listeners) {
154                 l.getInstance().schemaSourceUnregistered(source);
155             }
156
157             if (m.isEmpty()) {
158                 sources.remove(source.getSourceIdentifier());
159             }
160         }
161     }
162
163     @Override
164     public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(
165             final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
166         final PotentialSchemaSource<T> src = source.cachedReference();
167
168         final AbstractSchemaSourceRegistration<T> ret = new AbstractSchemaSourceRegistration<T>(provider, src) {
169             @Override
170             protected void removeRegistration() {
171                 removeSource(src, this);
172             }
173         };
174
175         addSource(src, ret);
176         return ret;
177     }
178
179     @Override
180     public SchemaListenerRegistration registerSchemaSourceListener(final SchemaSourceListener listener) {
181         final SchemaListenerRegistration ret = new AbstractSchemaListenerRegistration(listener) {
182             @Override
183             protected void removeRegistration() {
184                 listeners.remove(this);
185             }
186         };
187
188         synchronized (this) {
189             final Collection<PotentialSchemaSource<?>> col = new ArrayList<>();
190             for (Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m
191                     : sources.values()) {
192                 for (AbstractSchemaSourceRegistration<?> r : m.values()) {
193                     col.add(r.getInstance());
194                 }
195             }
196
197             // Notify first, so translator-type listeners, who react by registering a source
198             // do not cause infinite loop.
199             listener.schemaSourceRegistered(col);
200             listeners.add(ret);
201         }
202         return ret;
203     }
204
205     private static class SchemaProviderCostComparator implements Comparator<AbstractSchemaSourceRegistration<?>> {
206         public static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
207
208         @Override
209         public int compare(final AbstractSchemaSourceRegistration<?> o1, final AbstractSchemaSourceRegistration<?> o2) {
210             return o1.getInstance().getCost() - o2.getInstance().getCost();
211         }
212     }
213 }