Introduce odl-bytebuddy
[yangtools.git] / binding / binding-lib / src / main / java / org / opendaylight / yangtools / binding / lib / ResourceYangModuleInfo.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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.binding.lib;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * Base utility class for providing YANG module info backed by class resources.
21  *
22  * @author Robert Varga
23  */
24 @Beta
25 @NonNullByDefault
26 public abstract class ResourceYangModuleInfo implements YangModuleInfo {
27     @Override
28     public final InputStream openYangTextStream() throws IOException {
29         final Class<?> subclass = getClass();
30         final String name = verifyNotNull(resourceName(), "%s provided a null resource name", subclass);
31         final InputStream ret = subclass.getResourceAsStream(name);
32         if (ret == null) {
33             String message = "Failed to open resource " + name + " in context of " + subclass;
34             final ClassLoader loader = subclass.getClassLoader();
35             if (!ResourceYangModuleInfo.class.getClassLoader().equals(loader)) {
36                 message = message + " (loaded in " + loader + ")";
37             }
38             throw new IOException(message);
39         }
40         return ret;
41     }
42
43     @Override
44     public final String toString() {
45         return addToStringHelperAttributes(MoreObjects.toStringHelper(this)).toString();
46     }
47
48     protected ToStringHelper addToStringHelperAttributes(final ToStringHelper helper) {
49         return helper.add("resource", verifyNotNull(resourceName()));
50     }
51
52     protected abstract String resourceName();
53 }