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