e059265d4d21d83b9095bc675076a22c94864867
[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.FutureFallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
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("Schema source fetch", SchemaSourceException.class);
55
56     /*
57      * Source identifier -> representation -> provider map. We usually are looking for
58      * a specific representation of a source.
59      */
60     @GuardedBy("this")
61     private final Map<SourceIdentifier, ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>>> sources = new HashMap<>();
62
63     /*
64      * Schema source listeners.
65      */
66     @GuardedBy("this")
67     private final Collection<SchemaListenerRegistration> listeners = new ArrayList<>();
68
69     private static <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> fetchSource(final SourceIdentifier id, final Iterator<AbstractSchemaSourceRegistration<?>> it) {
70         final AbstractSchemaSourceRegistration<?> reg = it.next();
71
72         @SuppressWarnings("unchecked")
73         final CheckedFuture<? extends T, SchemaSourceException> f = ((SchemaSourceProvider<T>)reg.getProvider()).getSource(id);
74
75         return Futures.makeChecked(Futures.withFallback(f, new FutureFallback<T>() {
76             @Override
77             public ListenableFuture<T> create(@Nonnull final Throwable t) throws SchemaSourceException {
78                 LOG.debug("Failed to acquire source from {}", reg, t);
79
80                 if (it.hasNext()) {
81                     return fetchSource(id, it);
82                 }
83
84                 throw new MissingSchemaSourceException("All available providers exhausted", id, t);
85             }
86         }), FETCH_MAPPER);
87     }
88
89     @Override
90     public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(@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 = sources.get(id);
95             if (srcs == null) {
96                 return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("No providers registered for source" + id, id));
97             }
98
99             sortedSchemaSourceRegistrations = Lists.newArrayList(srcs.get(representation));
100         }
101
102         // TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
103         Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);
104
105         final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
106         if (!regs.hasNext()) {
107             return Futures.immediateFailedCheckedFuture(
108                     new MissingSchemaSourceException("No providers for source " + id + " representation " + representation + " available", id));
109         }
110
111         CheckedFuture<T, SchemaSourceException> fetchSourceFuture = fetchSource(id, regs);
112         // Add callback to notify cache listeners about encountered schema
113         Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
114             @Override
115             public void onSuccess(final T result) {
116                 for (final SchemaListenerRegistration listener : listeners) {
117                     listener.getInstance().schemaSourceEncountered(result);
118                 }
119             }
120
121             @Override
122             public void onFailure(@Nonnull final Throwable t) {
123                 LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
124             }
125         });
126
127         return fetchSourceFuture;
128     }
129
130     private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source, final AbstractSchemaSourceRegistration<T> reg) {
131         ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m = sources.get(source.getSourceIdentifier());
132         if (m == null) {
133             m = ArrayListMultimap.create();
134             sources.put(source.getSourceIdentifier(), m);
135         }
136
137         m.put(source.getRepresentation(), reg);
138
139         final Collection<PotentialSchemaSource<?>> reps = Collections.singleton(source);
140         for (SchemaListenerRegistration l : listeners) {
141             l.getInstance().schemaSourceRegistered(reps);
142         }
143     }
144
145     private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source, final SchemaSourceRegistration<?> reg) {
146         final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m = sources.get(source.getSourceIdentifier());
147         if (m != null) {
148             m.remove(source.getRepresentation(), reg);
149
150             for (SchemaListenerRegistration l : listeners) {
151                 l.getInstance().schemaSourceUnregistered(source);
152             }
153
154             if (m.isEmpty()) {
155                 sources.remove(source.getSourceIdentifier());
156             }
157         }
158     }
159
160     @Override
161     public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
162         final PotentialSchemaSource<T> src = source.cachedReference();
163
164         final AbstractSchemaSourceRegistration<T> ret = new AbstractSchemaSourceRegistration<T>(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 : sources.values()) {
187                 for (AbstractSchemaSourceRegistration<?> r : m.values()) {
188                     col.add(r.getInstance());
189                 }
190             }
191
192             // Notify first, so translator-type listeners, who react by registering a source
193             // do not cause infinite loop.
194             listener.schemaSourceRegistered(col);
195             listeners.add(ret);
196         }
197         return ret;
198     }
199
200     private static class SchemaProviderCostComparator implements Comparator<AbstractSchemaSourceRegistration<?>> {
201         public static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
202
203         @Override
204         public int compare(final AbstractSchemaSourceRegistration<?> o1, final AbstractSchemaSourceRegistration<?> o2) {
205             return o1.getInstance().getCost() - o2.getInstance().getCost();
206         }
207     }
208 }