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