2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.mdsal.binding.dom.adapter;
11 import com.google.common.base.Predicate;
12 import com.google.common.util.concurrent.SettableFuture;
14 import java.util.Collection;
15 import java.util.Date;
16 import java.util.List;
17 import java.util.concurrent.CopyOnWriteArrayList;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
21 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
22 import org.opendaylight.yangtools.yang.binding.Augmentation;
24 class FutureSchema implements AutoCloseable {
26 private final List<FutureSchemaPredicate> postponedOperations = new CopyOnWriteArrayList<>();
27 private final SettableFuture<Void> schemaPromise = SettableFuture.create();
28 private final long duration;
29 private final TimeUnit unit;
31 protected FutureSchema(final long time, final TimeUnit unit) {
36 void onRuntimeContextUpdated(final BindingRuntimeContext context) {
37 for (final FutureSchemaPredicate op : postponedOperations) {
38 op.unlockIfPossible(context);
52 for (final FutureSchemaPredicate op : postponedOperations) {
57 private static boolean isSchemaAvailable(final Class<?> clz, final BindingRuntimeContext context) {
59 if (Augmentation.class.isAssignableFrom(clz)) {
60 schema = context.getAugmentationDefinition(clz);
62 schema = context.getSchemaDefinition(clz);
64 return schema != null;
67 boolean waitForSchema(final URI namespace, final Date revision) {
68 final FutureSchemaPredicate postponedOp = new FutureSchemaPredicate() {
71 public boolean apply(final BindingRuntimeContext input) {
72 return input.getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision) != null;
75 return postponedOp.waitForSchema();
78 boolean waitForSchema(final Collection<Class<?>> bindingClasses) {
79 final FutureSchemaPredicate postponedOp = new FutureSchemaPredicate() {
82 public boolean apply(final BindingRuntimeContext context) {
83 for (final Class<?> clz : bindingClasses) {
84 if (!isSchemaAvailable(clz, context)) {
91 return postponedOp.waitForSchema();
94 private abstract class FutureSchemaPredicate implements Predicate<BindingRuntimeContext> {
96 final boolean waitForSchema() {
98 schemaPromise.get(duration, unit);
100 } catch (final InterruptedException | ExecutionException e) {
101 throw new RuntimeException(e);
102 } catch (final TimeoutException e) {
105 postponedOperations.remove(this);
109 final void unlockIfPossible(final BindingRuntimeContext context) {
110 if (!schemaPromise.isDone() && apply(context)) {
111 schemaPromise.set(null);
115 final void cancel() {
116 schemaPromise.cancel(true);