Bug 2361: Added meta-level SPI for building any statement-based models.
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / StmtContextUtils.java
1 /*
2  * Copyright (c) 2015 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.parser.spi.meta;
9
10 import com.google.common.base.Function;
11 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
12 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
13
14 public final class StmtContextUtils {
15
16     private static final Function<StmtContext<?, ?,?>, DeclaredStatement<?>> BUILD_DECLARED = new Function<StmtContext<?,?,?>, DeclaredStatement<?>>() {
17
18         @Override
19         public DeclaredStatement<?> apply(StmtContext<?,?,?> input) {
20             return input.buildDeclared();
21         }
22
23     };
24
25     private static final Function<StmtContext<?, ?,?>, EffectiveStatement<?,?>> BUILD_EFFECTIVE = new Function<StmtContext<?,?,?>, EffectiveStatement<?,?>>() {
26
27         @Override
28         public EffectiveStatement<?,?> apply(StmtContext<?,?,?> input) {
29             return input.buildEffective();
30         }
31
32     };
33
34     private StmtContextUtils() {
35         throw new UnsupportedOperationException("Utility class");
36     }
37
38
39     @SuppressWarnings("unchecked")
40     public static final <D extends DeclaredStatement<?>> Function<StmtContext<?, ? extends D, ?>, D> buildDeclared() {
41         return Function.class.cast(BUILD_DECLARED);
42     }
43
44     @SuppressWarnings("unchecked")
45     public static final <E extends EffectiveStatement<?,?>> Function<StmtContext<?, ?,? extends E>, E> buildEffective() {
46         return Function.class.cast(BUILD_EFFECTIVE);
47     }
48
49     @SuppressWarnings("unchecked")
50     public static final <AT,DT extends DeclaredStatement<AT>> AT firstAttributeOf(Iterable<? extends StmtContext<?,?,?>> contexts, Class<DT> declaredType) {
51         for(StmtContext<?, ?, ?> ctx : contexts) {
52             if(producesDeclared(ctx,declaredType)) {
53                 return (AT) ctx.getStatementArgument();
54             }
55         }
56         return null;
57     }
58
59     public static final boolean producesDeclared(StmtContext<?, ?, ?> ctx, Class<? extends DeclaredStatement<?>> type) {
60         return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
61     }
62
63
64
65 }