BUG-997 Add tests for shared schema context and fix dependency resolution bug
[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/eplv10.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.HashMultimap;
12 import com.google.common.collect.Multimap;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureFallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.Map;
24
25 import javax.annotation.concurrent.GuardedBy;
26
27 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
28 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
29 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
30 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
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     private static final ExceptionMapper<SchemaSourceException> FETCH_MAPPER = ReflectiveExceptionMapper.create("Schema source fetch", SchemaSourceException.class);
53
54     /*
55      * Source identifier -> representation -> provider map. We usually are looking for
56      * a specific representation of a source.
57      */
58     @GuardedBy("this")
59     private final Map<SourceIdentifier, Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>>> sources = new HashMap<>();
60
61     /*
62      * Schema source listeners.
63      */
64     @GuardedBy("this")
65     private final Collection<SchemaListenerRegistration> listeners = new ArrayList<>();
66
67     private static final <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> fetchSource(final SourceIdentifier id, final Iterator<AbstractSchemaSourceRegistration<?>> it) {
68         final AbstractSchemaSourceRegistration<?> reg = it.next();
69
70         @SuppressWarnings("unchecked")
71         final CheckedFuture<? extends T, SchemaSourceException> f = ((SchemaSourceProvider<T>)reg.getProvider()).getSource(id);
72         return Futures.makeChecked(Futures.withFallback(f, new FutureFallback<T>() {
73             @Override
74             public ListenableFuture<T> create(final Throwable t) throws SchemaSourceException {
75                 LOG.debug("Failed to acquire source from {}", reg, t);
76
77                 if (it.hasNext()) {
78                     return fetchSource(id, it);
79                 }
80
81                 throw new MissingSchemaSourceException("All available providers exhausted", t);
82             }
83         }), FETCH_MAPPER);
84     }
85
86     @Override
87     public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(final SourceIdentifier id, final Class<T> representation) {
88         final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs = sources.get(id);
89         if (srcs == null) {
90             return Futures.<T, SchemaSourceException>immediateFailedCheckedFuture(new MissingSchemaSourceException("No providers registered for source" + id));
91         }
92
93         final Iterator<AbstractSchemaSourceRegistration<?>> regs = srcs.get(representation).iterator();
94         if (!regs.hasNext()) {
95             return Futures.<T, SchemaSourceException>immediateFailedCheckedFuture(
96                     new MissingSchemaSourceException("No providers for source " + id + " representation " + representation + " available"));
97         }
98
99         return fetchSource(id, regs);
100     }
101
102     private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source, final AbstractSchemaSourceRegistration<T> reg) {
103         Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m = sources.get(source.getSourceIdentifier());
104         if (m == null) {
105             m = HashMultimap.create();
106             sources.put(source.getSourceIdentifier(), m);
107         }
108
109         m.put(source.getRepresentation(), reg);
110
111         final Collection<PotentialSchemaSource<?>> reps = Collections.<PotentialSchemaSource<?>>singleton(source);
112         for (SchemaListenerRegistration l : listeners) {
113             l.getInstance().schemaSourceRegistered(reps);
114         }
115     }
116
117     private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source, final SchemaSourceRegistration<?> reg) {
118         final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m = sources.get(source.getSourceIdentifier());
119         if (m != null) {
120             m.remove(source.getRepresentation(), reg);
121
122             for (SchemaListenerRegistration l : listeners) {
123                 l.getInstance().schemaSourceUnregistered(source);
124             }
125
126             if (m.isEmpty()) {
127                 sources.remove(m);
128             }
129         }
130     }
131
132     @Override
133     public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
134         final AbstractSchemaSourceRegistration<T> ret = new AbstractSchemaSourceRegistration<T>(provider, source) {
135             @Override
136             protected void removeRegistration() {
137                 removeSource(source, this);
138             }
139         };
140
141         addSource(source, ret);
142         return ret;
143     }
144
145     @Override
146     public SchemaListenerRegistration registerSchemaSourceListener(final SchemaSourceListener listener) {
147         final SchemaListenerRegistration ret = new AbstractSchemaListenerRegistration(listener) {
148             @Override
149             protected void removeRegistration() {
150                 listeners.remove(this);
151             }
152         };
153
154         synchronized (this) {
155             final Collection<PotentialSchemaSource<?>> col = new ArrayList<>();
156             for (Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m : sources.values()) {
157                 for (AbstractSchemaSourceRegistration<?> r : m.values()) {
158                     col.add(r.getInstance());
159                 }
160             }
161
162             // Notify first, so translator-type listeners, who react by registering a source
163             // do not cause infinite loop.
164             listener.schemaSourceRegistered(col);
165             listeners.add(ret);
166         }
167         return ret;
168     }
169 }