1838e6effc97c288cd70b5d8f860ecd8469d37b7
[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         @Override
18         public DeclaredStatement<?> apply(StmtContext<?,?,?> input) {
19             return input.buildDeclared();
20         }
21     };
22
23     private static final Function<StmtContext<?, ?,?>, EffectiveStatement<?,?>> BUILD_EFFECTIVE = new Function<StmtContext<?,?,?>, EffectiveStatement<?,?>>() {
24         @Override
25         public EffectiveStatement<?,?> apply(StmtContext<?,?,?> input) {
26             return input.buildEffective();
27         }
28     };
29
30     private StmtContextUtils() {
31         throw new UnsupportedOperationException("Utility class");
32     }
33
34     @SuppressWarnings("unchecked")
35     public static <D extends DeclaredStatement<?>> Function<StmtContext<?, ? extends D, ?>, D> buildDeclared() {
36         return Function.class.cast(BUILD_DECLARED);
37     }
38
39     @SuppressWarnings("unchecked")
40     public static <E extends EffectiveStatement<?,?>> Function<StmtContext<?, ?,? extends E>, E> buildEffective() {
41         return Function.class.cast(BUILD_EFFECTIVE);
42     }
43
44     @SuppressWarnings("unchecked")
45     public static <AT,DT extends DeclaredStatement<AT>> AT firstAttributeOf(Iterable<? extends StmtContext<?,?,?>> contexts, Class<DT> declaredType) {
46         for(StmtContext<?, ?, ?> ctx : contexts) {
47             if(producesDeclared(ctx,declaredType)) {
48                 return (AT) ctx.getStatementArgument();
49             }
50         }
51         return null;
52     }
53
54     public static boolean producesDeclared(StmtContext<?, ?, ?> ctx, Class<? extends DeclaredStatement<?>> type) {
55         return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
56     }
57 }