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