Bump odlparent dependency to 2.0.0
[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.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
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     @SuppressWarnings("unchecked")
72     private static <T extends SchemaSourceRepresentation> ListenableFuture<T> fetchSource(
73             final SourceIdentifier id, final Iterator<AbstractSchemaSourceRegistration<?>> it) {
74         final AbstractSchemaSourceRegistration<?> reg = it.next();
75
76         return Futures.catchingAsync(((SchemaSourceProvider<T>)reg.getProvider()).getSource(id), Throwable.class,
77             input -> {
78                 LOG.debug("Failed to acquire source from {}", reg, input);
79
80                 if (it.hasNext()) {
81                     return fetchSource(id, it);
82                 }
83
84                 throw new MissingSchemaSourceException("All available providers exhausted", id, input);
85             }, MoreExecutors.directExecutor());
86     }
87
88     @Override
89     public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(
90             @Nonnull final SourceIdentifier id, @Nonnull final Class<T> representation) {
91         final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations;
92
93         synchronized (this) {
94             final ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs =
95                 sources.get(id);
96             if (srcs == null) {
97                 return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
98                             "No providers registered for source" + id, id));
99             }
100
101             sortedSchemaSourceRegistrations = Lists.newArrayList(srcs.get(representation));
102         }
103
104         // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
105         Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);
106
107         final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
108         if (!regs.hasNext()) {
109             return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
110                         "No providers for source " + id + " representation " + representation + " available", id));
111         }
112
113         final ListenableFuture<T> fetchSourceFuture = fetchSource(id, regs);
114         // Add callback to notify cache listeners about encountered schema
115         Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
116             @Override
117             public void onSuccess(final T result) {
118                 for (final SchemaListenerRegistration listener : listeners) {
119                     listener.getInstance().schemaSourceEncountered(result);
120                 }
121             }
122
123             @Override
124             @SuppressWarnings("checkstyle:parameterName")
125             public void onFailure(@Nonnull final Throwable t) {
126                 LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
127             }
128         }, MoreExecutors.directExecutor());
129
130         return Futures.makeChecked(fetchSourceFuture, FETCH_MAPPER);
131     }
132
133     private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source,
134             final AbstractSchemaSourceRegistration<T> reg) {
135         ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> map =
136             sources.get(source.getSourceIdentifier());
137         if (map == null) {
138             map = ArrayListMultimap.create();
139             sources.put(source.getSourceIdentifier(), map);
140         }
141
142         map.put(source.getRepresentation(), reg);
143
144         final Collection<PotentialSchemaSource<?>> reps = Collections.singleton(source);
145         for (SchemaListenerRegistration l : listeners) {
146             l.getInstance().schemaSourceRegistered(reps);
147         }
148     }
149
150     private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source,
151             final SchemaSourceRegistration<?> reg) {
152         final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m =
153             sources.get(source.getSourceIdentifier());
154         if (m != null) {
155             m.remove(source.getRepresentation(), reg);
156
157             for (SchemaListenerRegistration l : listeners) {
158                 l.getInstance().schemaSourceUnregistered(source);
159             }
160
161             if (m.isEmpty()) {
162                 sources.remove(source.getSourceIdentifier());
163             }
164         }
165     }
166
167     @Override
168     public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(
169             final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
170         final PotentialSchemaSource<T> src = source.cachedReference();
171
172         final AbstractSchemaSourceRegistration<T> ret = new AbstractSchemaSourceRegistration<T>(provider, src) {
173             @Override
174             protected void removeRegistration() {
175                 removeSource(src, this);
176             }
177         };
178
179         addSource(src, ret);
180         return ret;
181     }
182
183     @Override
184     public SchemaListenerRegistration registerSchemaSourceListener(final SchemaSourceListener listener) {
185         final SchemaListenerRegistration ret = new AbstractSchemaListenerRegistration(listener) {
186             @Override
187             protected void removeRegistration() {
188                 listeners.remove(this);
189             }
190         };
191
192         synchronized (this) {
193             final Collection<PotentialSchemaSource<?>> col = new ArrayList<>();
194             for (Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m
195                     : sources.values()) {
196                 for (AbstractSchemaSourceRegistration<?> r : m.values()) {
197                     col.add(r.getInstance());
198                 }
199             }
200
201             // Notify first, so translator-type listeners, who react by registering a source
202             // do not cause infinite loop.
203             listener.schemaSourceRegistered(col);
204             listeners.add(ret);
205         }
206         return ret;
207     }
208
209     private static class SchemaProviderCostComparator implements Comparator<AbstractSchemaSourceRegistration<?>> {
210         public static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
211
212         @Override
213         public int compare(final AbstractSchemaSourceRegistration<?> o1, final AbstractSchemaSourceRegistration<?> o2) {
214             return o1.getInstance().getCost() - o2.getInstance().getCost();
215         }
216     }
217 }