Fixes violations and activates enforcement.
Change-Id: Iaa11d659549fa62a35201dea77992b32aebbd998
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
</dependency>
</dependencies>
- <!--
- Maven Site Configuration
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
- The following configuration is necessary for maven-site-plugin to
- correctly identify the correct deployment path for OpenDaylight Maven
- sites.
- -->
- <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
+ <!--
+ Maven Site Configuration
- <distributionManagement>
- <site>
- <id>opendaylight-site</id>
- <url>${nexus.site.url}/${project.artifactId}/</url>
- </site>
- </distributionManagement>
+ The following configuration is necessary for maven-site-plugin to
+ correctly identify the correct deployment path for OpenDaylight Maven
+ sites.
+ -->
+ <url>${odl.site.url}/${project.groupId}/${stream}/${project.artifactId}/</url>
+
+ <distributionManagement>
+ <site>
+ <id>opendaylight-site</id>
+ <url>${nexus.site.url}/${project.artifactId}/</url>
+ </site>
+ </distributionManagement>
</project>
package org.opendaylight.yangtools.yang.binding;
/**
- * Augmentable (extensible) object which could carry additional data defined by
- * third-party extension, without introducing conflict between various
- * extension.
- *
- * This interface uses extended version of ExtensibleInterface pattern which
- * also adds marker interface for augmentations (extensions) -
- * {@link Augmentable}
- *
- * @author Tony Tkacik
+ * Augmentable (extensible) object which could carry additional data defined by a third-party extension, without
+ * introducing conflict between various extension.
+ *
+ * <p>
+ * This interface uses extended version of ExtensibleInterface pattern which also adds marker interface for
+ * augmentations (extensions) - {@link Augmentable}.
+ *
* @param <T>
* Base class which should implements this interface and is target
* for augmentation.
+ * @author Tony Tkacik
*/
public interface Augmentable<T> {
-
/**
* Returns instance of augmentation.
- *
+ *
* @param augmentationType
* Type of augmentation to be returned.
* @return instance of augmentation.
package org.opendaylight.yangtools.yang.binding;
/**
- * Augmentation (extension) of other interface.
- *
- * This interface uniquely bounds Augmentation to generated
- * interface.
- *
- * All interfaces generated from YANG Augmentation statement
- * must implement this interface with parameter <code>P</code>
+ * Augmentation (extension) of other interface. This interface uniquely bounds Augmentation to generated interface.
+ *
+ * <p>
+ * All interfaces generated from YANG Augmentation statement must implement this interface with parameter <code>P</code>
* which uniquely points to it's target class.
- *
- *
*
* @param <T> Class to which this implementation is extension.
*/
import java.util.Map;
/**
+ * Augmentable (extensible) object which could carry additional data defined by third-party extension, without
+ * introducing conflict between various extension.
*
- * Augmentable (extensible) object which could carry additional data defined by
- * third-party extension, without introducing conflict between various
- * extension.
- *
- *
- * @author Tony Tkacik
* @param <T>
* Base class which should is target
* for augmentations.
+ * @author Tony Tkacik
*/
public interface AugmentationHolder<T> {
-
/**
* Returns map of all augmentations.
*
package org.opendaylight.yangtools.yang.binding;
/**
- * Base Identity
- *
+ * Base Identity.
*/
public abstract class BaseIdentity {
- public static final BaseIdentity INSTANCE = new BaseIdentity() {
- };
+ public static final BaseIdentity INSTANCE = new BaseIdentity() { };
protected BaseIdentity() {
package org.opendaylight.yangtools.yang.binding;
import static com.google.common.base.Preconditions.checkArgument;
+
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
final char[] chars = namespace.toCharArray();
for (int i = 0; i < chars.length; ++i) {
switch (chars[i]) {
- case '/':
- case ':':
- case '-':
- case '@':
- case '$':
- case '#':
- case '\'':
- case '*':
- case '+':
- case ',':
- case ';':
- case '=':
- chars[i] = '.';
+ case '/':
+ case ':':
+ case '-':
+ case '@':
+ case '$':
+ case '#':
+ case '\'':
+ case '*':
+ case '+':
+ case ',':
+ case ';':
+ case '=':
+ chars[i] = '.';
+ break;
+ default:
+ // no-op
}
}
return PACKAGE_INTERNER.intern(builder.toString());
}
- public static String getMethodName(final QName name) {
- checkArgument(name != null, "Name should not be null.");
- return getMethodName(name.getLocalName());
- }
-
public static String getClassName(final String localName) {
checkArgument(localName != null, "Name should not be null.");
return toFirstUpper(toCamelCase(localName));
}
+ public static String getClassName(final QName name) {
+ checkArgument(name != null, "Name should not be null.");
+ return toFirstUpper(toCamelCase(name.getLocalName()));
+ }
+
public static String getMethodName(final String yangIdentifier) {
checkArgument(yangIdentifier != null,"Identifier should not be null");
return toFirstLower(toCamelCase(yangIdentifier));
}
- public static String getClassName(final QName name) {
+ public static String getMethodName(final QName name) {
checkArgument(name != null, "Name should not be null.");
- return toFirstUpper(toCamelCase(name.getLocalName()));
+ return getMethodName(name.getLocalName());
}
public static String getGetterSuffix(final QName name) {
}
/**
- * Returns the {@link String} {@code s} with an
- * {@link Character#isUpperCase(char) upper case} first character. This
+ * Returns the {@link String} {@code s} with an {@link Character#isUpperCase(char) upper case} first character. This
* function is null-safe.
*
- * @param s
- * the string that should get an upper case first character. May
- * be <code>null</code>.
- * @return the {@link String} {@code s} with an upper case first character
- * or <code>null</code> if the input {@link String} {@code s} was
- * <code>null</code>.
+ * @param str the string that should get an upper case first character. May be <code>null</code>.
+ * @return the {@link String} {@code str} with an upper case first character or <code>null</code> if the input
+ * {@link String} {@code str} was <code>null</code>.
*/
- public static String toFirstUpper(final String s) {
- if (s == null || s.length() == 0) {
- return s;
+ public static String toFirstUpper(final String str) {
+ if (str == null || str.length() == 0) {
+ return str;
}
- if (Character.isUpperCase(s.charAt(0))) {
- return s;
+ if (Character.isUpperCase(str.charAt(0))) {
+ return str;
}
- if (s.length() == 1) {
- return s.toUpperCase();
+ if (str.length() == 1) {
+ return str.toUpperCase();
}
- return s.substring(0, 1).toUpperCase() + s.substring(1);
+ return str.substring(0, 1).toUpperCase() + str.substring(1);
}
/**
- * Returns the {@link String} {@code s} with an
- * {@link Character#isLowerCase(char) lower case} first character. This
+ * Returns the {@link String} {@code s} with a {@link Character#isLowerCase(char) lower case} first character. This
* function is null-safe.
*
- * @param s
- * the string that should get an lower case first character. May
- * be <code>null</code>.
- * @return the {@link String} {@code s} with an lower case first character
- * or <code>null</code> if the input {@link String} {@code s} was
- * <code>null</code>.
+ * @param str the string that should get an lower case first character. May be <code>null</code>.
+ * @return the {@link String} {@code str} with an lower case first character or <code>null</code> if the input
+ * {@link String} {@code str} was <code>null</code>.
*/
- private static String toFirstLower(final String s) {
- if (s == null || s.length() == 0) {
- return s;
+ private static String toFirstLower(final String str) {
+ if (str == null || str.length() == 0) {
+ return str;
}
- if (Character.isLowerCase(s.charAt(0))) {
- return s;
+ if (Character.isLowerCase(str.charAt(0))) {
+ return str;
}
- if (s.length() == 1) {
- return s.toLowerCase();
+ if (str.length() == 1) {
+ return str.toLowerCase();
}
- return s.substring(0, 1).toLowerCase() + s.substring(1);
+ return str.substring(0, 1).toLowerCase() + str.substring(1);
}
}
/**
- * Event Stream Writer for Binding Representation
- *
+ * Event Stream Writer for Binding Representation.
*
* <h3>Emmiting Event Stream</h3>
*
* {@link #startMapNode(Class, int)} and is ended using {@link #endNode()}. Each map
* entry start is emitted using {@link #startMapEntryNode(Identifier, int)} with Map of keys
* and finished using {@link #endNode()}.</li>
- *
* <li><code>UnkeyedList</code> - Unkeyed list represent list without keys,
* unkeyed list start is emitted using {@link #startUnkeyedList(Class, int)} list
* end is emitted using {@link #endNode()}. Each list item is emitted using
* {@link #startUnkeyedListItem(int)} and ended using {@link #endNode()}.</li>
* </ul></li>
- *
* <li><code>leaf</code> - Leaf node event is emitted using
* {@link #leafNode(String, Object)}. {@link #endNode()} MUST be not emitted for
* leaf node.</li>
- *
* <li><code>leaf-list</code> - Leaf list start is emitted using
* {@link #startLeafSet(String, int)}. Leaf list end is emitted using
* {@link #endNode()}. Leaf list entries are emitted using
* {@link #leafSetEntryNode(Object)}.
- *
* <li><code>anyxml - Anyxml node event is emitted using
* {@link #leafNode(String, Object)}. {@link #endNode()} MUST be not emitted
* for anyxml node.</code></li>
- *
- *
* <li><code>choice</code> Choice node event is emitted by
* {@link #startChoiceNode(Class, int)} event and must be immediately followed by
* {@link #startCase(Class, int)} event. Choice node is finished by emitting an
* {@link #endNode()} event.</li>
- *
* <li>
* <code>case</code> - Case node may be emitted only inside choice node by
* invoking {@link #startCase(Class, int)}. Case node is finished be emitting an
* {@link #endNode()} event.</li>
- *
* <li>
* <code>augment</code> - Represents augmentation, augmentation node is started
* by invoking {@link #startAugmentationNode(Class)} and
* finished by invoking {@link #endNode()}.</li>
- *
* </ul>
*
- * <h3>Implementation notes</h3> This interface is not intended to be
- * implemented by users of generated Binding DTOs but to be used by utilities,
- * which needs to emit NormalizedNode model from Binding DTOs.
- * <p>
- * This interface is intended as API definition of facade for real Event /
- * Stream Writer, without explicitly requiring stream writer and related
- * interfaces to be imported by all generated Binding DTOs.
- * <p>
- * Existence of this interface in base Java Binding package is required to
- * support runtime generation of users of this interface in OSGI and OSGI-like
- * environment, since this package is only package which is imported by all
- * generated Binding DTOs and wired in OSGI.
+ * <h3>Implementation notes</h3> This interface is not intended to be implemented by users of generated Binding DTOs
+ * but to be used by utilities, which needs to emit NormalizedNode model from Binding DTOs.
*
+ * <p>
+ * This interface is intended as API definition of facade for real Event / Stream Writer, without explicitly requiring
+ * stream writer and related interfaces to be imported by all generated Binding DTOs.
*
+ * <p>
+ * Existence of this interface in base Java Binding package is required to support runtime generation of users of this
+ * interface in OSGI and OSGI-like environment, since this package is only package which is imported by all generated
+ * Binding DTOs and wired in OSGI.
*/
public interface BindingStreamEventWriter extends Closeable, Flushable {
/**
- * Methods in this interface allow users to hint the underlying
- * implementation about the sizing of container-like constructors
- * (leafLists, containers, etc.). These hints may be taken into account by a
- * particular implementation to improve performance, but clients are not
- * required to provide hints. This constant should be used by clients who
- * either do not have the sizing information, or do not wish to divulge it
- * (for whatever reasons). Implementations are free to ignore these hints
- * completely, but if they do use them, they are expected to be resilient in
- * face of missing and mismatched hints, which is to say the user can
- * specify startLeafSet(..., 1) and then call leafNode() 15 times.
+ * Methods in this interface allow users to hint the underlying implementation about the sizing of container-like
+ * constructors (leafLists, containers, etc.). These hints may be taken into account by a particular implementation
+ * to improve performance, but clients are not required to provide hints. This constant should be used by clients
+ * who either do not have the sizing information, or do not wish to divulge it (for whatever reasons).
+ * Implementations are free to ignore these hints completely, but if they do use them, they are expected to be
+ * resilient in face of missing and mismatched hints, which is to say the user can specify startLeafSet(..., 1)
+ * and then call leafNode() 15 times.
+ *
* <p>
- * The acceptable hint values are non-negative integers and this constant,
- * all other values will result, based on implementation preference, in the
- * hint being completely ignored or IllegalArgumentException being thrown.
+ * The acceptable hint values are non-negative integers and this constant, all other values will result, based on
+ * implementation preference, in the hint being completely ignored or IllegalArgumentException being thrown.
*/
int UNKNOWN_SIZE = -1;
/**
- *
* Emits a leaf node event with supplied value.
*
* @param localName
void leafNode(String localName, Object value) throws IOException;
/**
- *
- * Emits a start of leaf set (leaf-list).
- * <p>
- * Emits start of leaf set, during writing leaf set event, only
- * {@link #leafSetEntryNode(Object)} calls are valid. Leaf set event is
- * finished by calling {@link #endNode()}.
+ * Emits a start of leaf set (leaf-list). Emits start of leaf set, during writing leaf set event, only
+ * {@link #leafSetEntryNode(Object)} calls are valid. Leaf set event is finished by calling {@link #endNode()}.
*
* @param localName
* name of node as defined in schema, namespace and revision are
void startLeafSet(String localName, int childSizeHint) throws IOException;
/**
- *
* Emits a start of leaf set (leaf-list).
+ *
* <p>
* Emits start of leaf set, during writing leaf set event, only
* {@link #leafSetEntryNode(Object)} calls are valid. Leaf set event is
void startOrderedLeafSet(String localName, int childSizeHint) throws IOException;
/**
- * Emits a leaf set entry node
+ * Emits a leaf set entry node.
*
* @param value
* Value of leaf set entry node.
void leafSetEntryNode(Object value) throws IOException;
/**
- *
- * Emits start of new container.
- *
- * <p>
- * End of container event is emitted by invoking {@link #endNode()}.
+ * Emits start of new container. End of container event is emitted by invoking {@link #endNode()}.
*
* <p>
* Valid sub-events are:
void startContainerNode(Class<? extends DataObject> container, int childSizeHint) throws IOException;
/**
- *
* Emits start of unkeyed list node event.
*
* <p>
* <p>
* Unkeyed list item event is finished by invoking {@link #endNode()}. Valid
* sub-events are:
- * <p>
- * Valid sub-events are:
- *
* <ul>
* <li>{@link #leafNode(String, Object)}</li>
* <li>{@link #startContainerNode(Class, int)}</li>
* <li>{@link #startAugmentationNode(Class)}</li>
* </ul>
*
- *
* @param childSizeHint
* Non-negative count of expected direct child nodes or
* {@link #UNKNOWN_SIZE} if count is unknown. This is only hint
void startUnkeyedListItem(int childSizeHint) throws IOException;
/**
- *
* Emits start of unordered map node event.
*
* <p>
* End of map node event is emitted by invoking {@link #endNode()}. Valid
- * subevents is only {@link #startMapEntryNode(Identifier, int)}. All other methods will
+ * subevent is only {@link #startMapEntryNode(Identifier, int)}. All other methods will
* throw {@link IllegalArgumentException}.
*
* @param mapEntryType
throws IOException;
/**
- *
* Emits start of ordered map node event.
*
* <p>
* End of map node event is emitted by invoking {@link #endNode()}. Valid
- * subevents is only {@link #startMapEntryNode(Identifier, int)}. All other methods will
+ * subevent is only {@link #startMapEntryNode(Identifier, int)}. All other methods will
* throw {@link IllegalArgumentException}.
*
* @param mapEntryType
throws IOException;
/**
- *
* Emits start of map entry.
*
* <p>
* {@link #UNKNOWN_SIZE} if count is unknown. This is only hint
* and should not fail writing of child events, if there are more
* events than count.
- * @throws IllegalArgumentException
* @throws IllegalStateException
* If node was emitted inside <code>map</code>, <code>choice</code>,
* <code>unkeyed list</code> node.
void startChoiceNode(Class<? extends DataContainer> choice, int childSizeHint) throws IOException;
/**
- *
* Starts a case node.
*
* <p>
* </ul>
*
* @param caze Case class
- * @throws IllegalArgumentException
* @throws IOException if an underlying IO error occurs
*/
void startCase(Class<? extends DataObject> caze, int childSizeHint) throws IOException;
/**
* Emits anyxml node event.
*
- * @param name
- * @param value
- * @throws IllegalArgumentException
+ * @param name node name
+ * @param value node value
* @throws IllegalStateException
* If node was emitted inside <code>map</code>,
* <code>choice</code> <code>unkeyed list</code> node.
* @throws IOException if an underlying IO error occurs
*/
void endNode() throws IOException;
+
@Override
void flush() throws IOException;
package org.opendaylight.yangtools.yang.binding;
/**
- * Child of parent container
- *
- * Marker interface uniquelly bounding generated Java interfaces to their
- * parent container.
- *
- * Any nested Java interface generated from YANG must implement this interface,
- * where parameter <code>P</code> points to it's defining data node container
- * (interface generated for List, Container, Case).
- *
- * In case of children added by augmentation (which implements {@link Augmentation})
- * interfaces representing nested container must implements {@link ChildOf} with
- * same argument as Augmentation.
- *
+ * Child of parent container. Marker interface uniquely bounding generated Java interfaces to their parent container.
+ *
+ * <p>
+ * Any nested Java interface generated from YANG must implement this interface, where parameter <code>P</code> points
+ * to it's defining data node container (interface generated for List, Container, Case).
+ *
+ * <p>
+ * In case of children added by augmentation (which implements {@link Augmentation}) interfaces representing nested
+ * container must implements {@link ChildOf} with same argument as Augmentation.
+ *
* @param <P> Parent container
*/
public interface ChildOf<P> extends DataObject {
package org.opendaylight.yangtools.yang.binding;
/**
- * Data Container - object contains structured data
- *
- * Marker interface which must be implmeneted by all interfaces
+ * Data Container - object contains structured data. Marker interface which must be implmeneted by all interfaces
* generated for YANG:
* <ul>
* <li>Rpc Input
- * <li>Output
+ * <li>Output
* <li>Notification
* <li>Container
* <li>List
/**
* Data container is an interface which has structured contents.
- *
- * @author Tony Tkacik
*
+ * @author Tony Tkacik
*/
public interface DataObject extends DataContainer {
*/
public interface DataObjectSerializer {
/**
- * Writes stream events representing object to supplied stream
+ * Writes stream events representing object to supplied stream.
*
* @param obj
* Source of stream events
* SPI-level contract for implementations of {@link DataObjectSerializer}.
* The contract is kept between implementation of {@link DataObjectSerializerRegistry},
* which maintains the lookup context required for recursive serialization.
- *
+ */
+/*
* FIXME: this interface needs to be moved into .spi, but due to classpath funkyness
* of OSGi, that change has to be carefully orchestrated to ensure proper imports
* exist in all generated packages. One avenue how to achieve that is to move
* to all generated classes which will point to the per-model YangModuleInfo
* (currently all users of it have to walk the package hierarchy, so that
* is an improvement in and of itself).
- *
*/
public interface DataObjectSerializerImplementation {
/**
- *
* Writes stream events for supplied data object to provided stream.
*
- * DataObjectSerializerRegistry may be used to lookup serializers
- * for other generated classes in order to support writing
- * their events.
- *
+ * <p>
+ * DataObjectSerializerRegistry may be used to lookup serializers for other generated classes in order to support
+ * writing their events.
*/
- void serialize(DataObjectSerializerRegistry reg,DataObject obj, BindingStreamEventWriter stream) throws IOException;
+ void serialize(DataObjectSerializerRegistry reg, DataObject obj, BindingStreamEventWriter stream)
+ throws IOException;
}
package org.opendaylight.yangtools.yang.binding;
/**
- * SPI-level contract for registry of {@link DataObjectSerializer}.
- * The contract is kept between implementation of {@link DataObjectSerializerImplementation},
- * Registry provides lookup for serializers to support recursive
+ * SPI-level contract for registry of {@link DataObjectSerializer}. The contract is kept between implementation
+ * of {@link DataObjectSerializerImplementation}, Registry provides lookup for serializers to support recursive
* serialization of nested {@link DataObject}s.
- *
+ */
+/*
* FIXME: this interface needs to be moved into .spi, but due to classpath funkyness
* of OSGi, that change has to be carefully orchestrated to ensure proper imports
- * exist in all generated pacakges. One avenue how to achieve that is to move
+ * exist in all generated packages. One avenue how to achieve that is to move
* {@link YangModuleInfo} and modify code generator to add a static field
* to all generated classes which will point to the per-model YangModuleInfo
* (currently all users of it have to walk the package hierarchy, so that
* is an improvement in and of itself).
- *
*/
public interface DataObjectSerializerRegistry {
package org.opendaylight.yangtools.yang.binding;
/**
- * Data Root of YANG module
- *
+ * Data Root of YANG module.
*/
public interface DataRoot {
/**
- * Identifiable object, which could be identified by it's key
- *
- * @author ttkacik
+ * Identifiable object, which could be identified by it's key.
*
* @param <T> Identifier class for this object
+ *
+ * @author ttkacik
*/
public interface Identifiable<T extends Identifier<? extends Identifiable<T>>> {
-
/**
- * Returns an unique key for the object
- *
+ * Returns an unique key for the object.
+ *
* @return Key for the object
*/
T getKey();
package org.opendaylight.yangtools.yang.binding;
/**
- *
- * Object is unique identifier for another object
- *
- *
- *
+ * Object is unique identifier for another object.
+ *
* @param <T>
* Class of object for which this object is identifier
* @author ttkacik
import org.opendaylight.yangtools.util.HashCodeBuilder;
/**
- *
* This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
*
+ * <p>
* For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
*
+ * <p>
* <pre>
* module opendaylight-inventory {
* ....
* }
* </pre>
*
- * You could create an instance identifier as follows to get to a node with id "openflow:1"
- *
+ * <p>
+ * You can create an instance identifier as follows to get to a node with id "openflow:1": {@code
* InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
+ * }
*
+ * <p>
* This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
- *
*/
-public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>, Immutable, Serializable {
+public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>,
+ Immutable, Serializable {
private static final Field PATHARGUMENTS_FIELD;
private static final long serialVersionUID = 2L;
/*
* access is required never to modify the contents. References passed
* to outside entities have to be wrapped in an unmodifiable view.
*/
- protected transient final Iterable<PathArgument> pathArguments;
+ protected final transient Iterable<PathArgument> pathArguments;
private final Class<T> targetType;
private final boolean wildcarded;
private final int hash;
PATHARGUMENTS_FIELD = f;
}
- InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded, final int hash) {
+ InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded,
+ final int hash) {
this.pathArguments = Preconditions.checkNotNull(pathArguments);
this.targetType = Preconditions.checkNotNull(type);
this.wildcarded = wildcarded;
}
/**
- * Check whether an instance identifier contains any wildcards. A wildcard
- * is an path argument which has a null key.
+ * Check whether an instance identifier contains any wildcards. A wildcard is an path argument which has a null key.
*
* @return true if any of the path arguments has a null key.
*/
}
/**
- * Perform class-specific fast checks for non-equality. This allows
- * subclasses to avoid iterating over the pathArguments by performing
- * quick checks on their specific fields.
+ * Perform class-specific fast checks for non-equality. This allows subclasses to avoid iterating over the
+ * pathArguments by performing quick checks on their specific fields.
*
* @param other The other identifier, guaranteed to be the same class
* @return true if the other identifier cannot be equal to this one.
}
/**
- * Return an instance identifier trimmed at the first occurrence of a
- * specific component type.
+ * Return an instance identifier trimmed at the first occurrence of a specific component type.
*
+ * <p>
* For example let's say an instance identifier was built like so,
* <pre>
- * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
+ * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class,
+ * new NodeKey(new NodeId("openflow:1")).build();
* </pre>
*
+ * <p>
* And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
*
+ * <p>
* <pre>
* identifier.firstIdentifierOf(Nodes.class)
* </pre>
* is not present.
*/
public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
- int i = 1;
+ int count = 1;
for (final PathArgument a : pathArguments) {
if (type.equals(a.getType())) {
@SuppressWarnings("unchecked")
final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(
- Iterables.limit(pathArguments, i));
+ Iterables.limit(pathArguments, count));
return ret;
}
- ++i;
+ ++count;
}
return null;
* @deprecated Use {@link #firstKeyOf(Class)} instead.
*/
@Deprecated
- public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem, final Class<K> listKey) {
+ public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem,
+ final Class<K> listKey) {
return firstKeyOf(listItem);
}
* @return key associated with the component, or null if the component type
* is not present.
*/
- public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem) {
+ public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(
+ final Class<N> listItem) {
for (final PathArgument i : pathArguments) {
if (listItem.equals(i.getType())) {
@SuppressWarnings("unchecked")
/**
* Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
- * PathArguments to match exactly, e.g.
- *
+ * PathArguments to match exactly.
*
+ * <p>
* The contains method checks if the other identifier is fully contained within the current identifier. It does this
* by looking at only the types of the path arguments and not by comparing the path arguments themselves.
*
- * To illustrate here is an example which explains the working of this API.
- *
- * Let's say you have two instance identifiers as follows,
- *
+ * <p>
+ * To illustrate here is an example which explains the working of this API. Let's say you have two instance
+ * identifiers as follows:
+ * {@code
* this = /nodes/node/openflow:1
* other = /nodes/node/openflow:2
- *
+ * }
* then this.contains(other) will return false.
*
- * @param other
- * @return
+ * @param other Potentially-container instance identifier
+ * @return True if the specified identifier is contained in this identifier.
*/
@Override
public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
return true;
}
- /**
- * Create a builder rooted at this key.
- *
- * @return A builder instance
- */
- public InstanceIdentifierBuilder<T> builder() {
- return new InstanceIdentifierBuilderImpl<>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
- }
-
private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
- return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
+ return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)),
+ HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
}
@SuppressWarnings("unchecked")
}
@SuppressWarnings("unchecked")
- public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> KeyedInstanceIdentifier<N, K> child(
- final Class<N> listItem, final K listKey) {
+ public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> KeyedInstanceIdentifier<N, K>
+ child(final Class<N> listItem, final K listKey) {
final PathArgument arg = new IdentifiableItem<>(listItem, listKey);
return (KeyedInstanceIdentifier<N, K>) childIdentifier(arg);
}
private List<PathArgument> legacyCache;
/**
+ * Return the path as a list.
+ *
* @deprecated Use {@link #getPathArguments()} instead.
*/
@Deprecated
}
/**
- * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
+ * Create a builder rooted at this key.
*
- * @param base
- * @param <T>
- * @return
+ * @return A builder instance
+ */
+ public InstanceIdentifierBuilder<T> builder() {
+ return new InstanceIdentifierBuilderImpl<>(new Item<>(targetType), pathArguments, hash, isWildcarded());
+ }
+
+ /**
+ * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier.
*
* @deprecated Use {@link #builder()} instead.
*/
}
/**
- * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
+ * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container.
*
- * @param container
- * @param <T>
- * @return
+ * @param container Base container
+ * @param <T> Type of the container
+ * @return New IsntanceIdentifierBuilder
*/
- public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
+ public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(
+ final Class<T> container) {
return new InstanceIdentifierBuilderImpl<T>().addNode(container);
}
/**
- * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
- *
- * @param listItem
- * @param listKey
- * @param <N>
- * @param <K>
- * @return
+ * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an
+ * {@link IdentifiableItem}.
+ *
+ * @param listItem list item class
+ * @param listKey key value
+ * @param <N> List type
+ * @param <K> List key
+ * @return A new {@link InstanceIdentifierBuilder}
*/
- public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>, K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(
- final Class<N> listItem, final K listKey) {
+ public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>,
+ K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(final Class<N> listItem, final K listKey) {
return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
}
/**
- * Create an instance identifier for a very specific object type. This method
- * implements {@link #create(Iterable)} semantics, except it is used by internal
- * callers, which have assured that the argument is an immutable Iterable.
- *
+ * Create an instance identifier for a very specific object type. This method implements {@link #create(Iterable)}
+ * semantics, except it is used by internal callers, which have assured that the argument is an immutable Iterable.
*
* @param pathArguments The path to a specific node in the data tree
* @return InstanceIdentifier instance
- * @throws IllegalArgumentException if pathArguments is empty or
- * contains a null element.
+ * @throws IllegalArgumentException if pathArguments is empty or contains a null element.
*/
private static InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
- final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
+ final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments,
+ "pathArguments may not be null").iterator();
final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
boolean wildcard = false;
- PathArgument a = null;
+ PathArgument arg = null;
while (it.hasNext()) {
- a = it.next();
- Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
+ arg = it.next();
+ Preconditions.checkArgument(arg != null, "pathArguments may not contain null elements");
// TODO: sanity check ChildOf<>;
- hashBuilder.addArgument(a);
+ hashBuilder.addArgument(arg);
- if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
+ if (Identifiable.class.isAssignableFrom(arg.getType()) && !(arg instanceof IdentifiableItem<?, ?>)) {
wildcard = true;
}
}
- Preconditions.checkArgument(a != null, "pathArguments may not be empty");
+ Preconditions.checkArgument(arg != null, "pathArguments may not be empty");
- return trustedCreate(a, pathArguments, hashBuilder.build(), wildcard);
+ return trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard);
}
/**
* Create an instance identifier for a very specific object type.
*
- * Example
+ * <p>
+ * Example:
* <pre>
* List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
* new InstanceIdentifier(path);
/**
* Create an instance identifier for a very specific object type.
*
+ * <p>
* For example
* <pre>
* new InstanceIdentifier(Nodes.class)
*/
@SuppressWarnings("unchecked")
public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
- return (InstanceIdentifier<T>) create(Collections.<PathArgument> singletonList(new Item<>(type)));
+ return (InstanceIdentifier<T>) create(Collections.singletonList(new Item<>(type)));
}
/**
* @throws IllegalArgumentException if the supplied identifier type cannot have a key.
* @throws NullPointerException if id is null.
*/
- public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(final InstanceIdentifier<N> id) {
+ public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(
+ final InstanceIdentifier<N> id) {
Preconditions.checkNotNull(id);
Preconditions.checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
- static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
- if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
+ static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments,
+ final int hash, boolean wildcarded) {
+ if (Identifiable.class.isAssignableFrom(arg.getType()) && !wildcarded) {
Identifier<?> key = null;
if (arg instanceof IdentifiableItem<?, ?>) {
key = ((IdentifiableItem<?, ?>)arg).key;
}
return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
- } else {
- return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
}
+
+ return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
}
/**
- * Path argument of {@link InstanceIdentifier}.
- * <p>
- * Interface which implementations are used as path components of the
+ * Path argument of {@link InstanceIdentifier}. Interface which implementations are used as path components of the
* path in overall data tree.
*/
public interface PathArgument extends Comparable<PathArgument> {
* An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
* a kind. In YANG terms this would probably represent a container.
*
- * @param <T>
+ * @param <T> Item type
*/
public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
private static final long serialVersionUID = 1L;
* @param <I> An object that is identifiable by an identifier
* @param <T> The identifier of the object
*/
- public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
+ public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>>
+ extends AbstractPathArgument<I> {
private static final long serialVersionUID = 1L;
private final T key;
/**
* Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
- * the builder
+ * the builder.
*
- * @param container
- * @param <N>
- * @return
+ * @param container augmentation class
+ * @param <N> augmentation type
+ * @return this builder
*/
<N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
Class<N> container);
/**
* Build the instance identifier.
*
- * @return
+ * @return Resulting instance identifier.
*/
@Override
InstanceIdentifier<T> build();
import java.util.Objects;
import org.opendaylight.yangtools.util.HashCodeBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
-final class InstanceIdentifierBuilderImpl<T extends DataObject> implements InstanceIdentifier.InstanceIdentifierBuilder<T> {
+final class InstanceIdentifierBuilderImpl<T extends DataObject> implements InstanceIdentifierBuilder<T> {
private final ImmutableList.Builder<PathArgument> pathBuilder = ImmutableList.builder();
private final HashCodeBuilder<PathArgument> hashBuilder;
private final Iterable<? extends PathArgument> basePath;
this.basePath = null;
}
- InstanceIdentifierBuilderImpl(final PathArgument item, final Iterable<? extends PathArgument> pathArguments, final int hash, final boolean wildcard) {
+ InstanceIdentifierBuilderImpl(final PathArgument item, final Iterable<? extends PathArgument> pathArguments,
+ final int hash, final boolean wildcard) {
this.hashBuilder = new HashCodeBuilder<>(hash);
this.basePath = pathArguments;
this.wildcard = wildcard;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof InstanceIdentifierBuilderImpl) {
InstanceIdentifierBuilderImpl<T> otherBuilder = (InstanceIdentifierBuilderImpl<T>) obj;
- return wildcard == otherBuilder.wildcard &&
- Objects.equals(basePath, otherBuilder.basePath) &&
- Objects.equals(arg, otherBuilder.arg) &&
- Objects.equals(hashBuilder.build(), otherBuilder.hashBuilder.build());
+ return wildcard == otherBuilder.wildcard && Objects.equals(basePath, otherBuilder.basePath)
+ && Objects.equals(arg, otherBuilder.arg)
+ && Objects.equals(hashBuilder.build(), otherBuilder.hashBuilder.build());
}
return false;
}
@SuppressWarnings("unchecked")
<N extends DataObject> InstanceIdentifierBuilderImpl<N> addNode(final Class<N> container) {
- arg = new Item<N>(container);
+ arg = new Item<>(container);
hashBuilder.addArgument(arg);
pathBuilder.add(arg);
}
@SuppressWarnings("unchecked")
- <N extends DataObject & Identifiable<K>, K extends Identifier<N>> InstanceIdentifierBuilderImpl<N> addNode(final Class<N> listItem, final K listKey) {
- arg = new IdentifiableItem<N, K>(listItem, listKey);
+ <N extends DataObject & Identifiable<K>, K extends Identifier<N>> InstanceIdentifierBuilderImpl<N> addNode(
+ final Class<N> listItem, final K listKey) {
+ arg = new IdentifiableItem<>(listItem, listKey);
hashBuilder.addArgument(arg);
pathBuilder.add(arg);
return (InstanceIdentifierBuilderImpl<N>) this;
}
@Override
- public <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilderImpl<N> child(final Class<N> listItem, final K listKey) {
+ public <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilderImpl<N>
+ child(final Class<N> listItem, final K listKey) {
return addNode(listItem, listKey);
}
/**
* Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
- * the builder
+ * the builder.
*
- * @param container
- * @param <N>
- * @return
+ * @param container Augmentation to be added
+ * @param <N> Augmentation type
+ * @return This builder
*/
@Override
- public <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilderImpl<N> augmentation(final Class<N> container) {
+ public <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilderImpl<N> augmentation(
+ final Class<N> container) {
return addNode(container);
}
}
@SuppressWarnings("unchecked")
- final InstanceIdentifier<T> ret = (InstanceIdentifier<T>) InstanceIdentifier.trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard);
+ final InstanceIdentifier<T> ret = (InstanceIdentifier<T>) InstanceIdentifier.trustedCreate(arg, pathArguments,
+ hashBuilder.build(), wildcard);
return ret;
}
- /*
+ /**
+ * Build the resulting InstanceIdentifier.
+ *
* @deprecated Use #build() instead.
*/
@Override
package org.opendaylight.yangtools.yang.binding;
/**
- * An {@link InstanceIdentifier}, which has a list key attached at its last path
- * element.
+ * An {@link InstanceIdentifier}, which has a list key attached at its last path element.
*
* @param <T> Target data type
* @param <K> Target key type
*/
-public class KeyedInstanceIdentifier<T extends Identifiable<K> & DataObject, K extends Identifier<T>> extends InstanceIdentifier<T> {
+public class KeyedInstanceIdentifier<T extends Identifiable<K> & DataObject, K extends Identifier<T>>
+ extends InstanceIdentifier<T> {
private static final long serialVersionUID = 1L;
private final K key;
- KeyedInstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded, final int hash, final K key) {
+ KeyedInstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded,
+ final int hash, final K key) {
super(type, pathArguments, wildcarded, hash);
this.key = key;
}
/**
- * Return the key attached to this identifier. This method is equivalent to
- * calling {@link InstanceIdentifier#keyOf(InstanceIdentifier)}.
+ * Return the key attached to this identifier. This method is equivalent to calling
+ * {@link InstanceIdentifier#keyOf(InstanceIdentifier)}.
*
* @return Key associated with this instance identifier.
*/
@Override
public final InstanceIdentifierBuilder<T> builder() {
- return new InstanceIdentifierBuilderImpl<>(new InstanceIdentifier.IdentifiableItem<T, K>(getTargetType(), key), pathArguments, hashCode(), isWildcarded());
+ return new InstanceIdentifierBuilderImpl<>(new InstanceIdentifier.IdentifiableItem<>(getTargetType(), key),
+ pathArguments, hashCode(), isWildcarded());
}
@Override
* equals() in superclass falls back to a full compare, which will
* end up running that equals anyway, so do not bother here.
*/
- return (key == null) != (kii.key == null);
+ return key == null != (kii.key == null);
}
}
package org.opendaylight.yangtools.yang.binding;
/**
- * Marker interface for YANG-defined notifications
- *
- *
+ * Marker interface for YANG-defined notifications.
*/
public interface Notification extends DataContainer {
package org.opendaylight.yangtools.yang.binding;
/**
- * Marker interface for tagging generated YANG Modules
- *
+ * Marker interface for tagging generated YANG Modules.
*/
public interface RpcService {
import java.util.ServiceLoader;
/**
- *
- * Provider of YangModuleInfo for specified package / model.
- *
- * Implementation of this interface should be discoverable
- * via {@link ServiceLoader}
- *
- *
- *
+ * Provider of YangModuleInfo for specified package / model. Implementations of this interface should be discoverable
+ * via {@link ServiceLoader}.
*/
public interface YangModelBindingProvider {
-
/**
- * YangModuleInfo associated to package
+ * Returns YangModuleInfo associated with a package.
*
- * @return
+ * @return YangModuleInfo associated with a package.
*/
YangModuleInfo getModuleInfo();
-
}
*/
package org.opendaylight.yangtools.yang.binding;
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.util.Set;
public interface YangModuleInfo {
/**
- * Returns yang module name
+ * Returns YANG module name.
*
- * @return
+ * @return YANG module name.
*/
String getName();
/**
+ * Returns revision of YANG module.
*
- * Returns revision of yang module.
- *
- * @return
+ * @return YANG module revision.
*/
String getRevision();
/**
- * Returns XML namespace associated to the YANG module
+ * Returns XML namespace associated to the YANG module.
*
* @return XML namespace associated to the YANG module.
*/
*/
package org.opendaylight.yangtools.yang.binding.annotations;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
this.map = b.build();
}
- protected abstract T qnameToKey(final QName qname);
+ protected abstract T qnameToKey(QName qname);
@Override
- public final Future<RpcResult<?>> invokeRpc(@Nonnull final RpcService impl, @Nonnull final QName rpcName, @Nullable final DataObject input) {
+ public final Future<RpcResult<?>> invokeRpc(@Nonnull final RpcService impl, @Nonnull final QName rpcName,
+ @Nullable final DataObject input) {
Preconditions.checkNotNull(impl, "Implementation must be supplied");
RpcMethodInvoker invoker = map.get(qnameToKey(rpcName));
};
private static final AugmentationFieldGetter AUGMENTATION_HOLDER_GETTER = new AugmentationFieldGetter() {
-
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
protected Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object input) {
}
};
- private static final LoadingCache<Class<?>, AugmentationFieldGetter> AUGMENTATION_GETTERS = CacheBuilder.newBuilder().weakKeys().build(
- new AugmentationGetterLoader());
+ private static final LoadingCache<Class<?>, AugmentationFieldGetter> AUGMENTATION_GETTERS =
+ CacheBuilder.newBuilder().weakKeys().build(new AugmentationGetterLoader());
/**
- *
- * Retrieves augmentations from supplied object
+ * Retrieves augmentations from supplied object.
*
* @param input Input Data object, from which augmentations should be extracted
* @return Map of Augmentation class to augmentation
*/
- protected abstract Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object input);
+ protected abstract Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(Object input);
public static AugmentationFieldGetter getGetter(final Class<? extends Object> clz) {
- if(AugmentationHolder.class.isAssignableFrom(clz)) {
+ if (AugmentationHolder.class.isAssignableFrom(clz)) {
return AUGMENTATION_HOLDER_GETTER;
}
return AUGMENTATION_GETTERS.getUnchecked(clz);
}
@Override
+ @SuppressWarnings("checkstyle:illegalCatch")
protected Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object input) {
try {
return (Map<Class<? extends Augmentation<?>>, Augmentation<?>>) fieldGetter.invokeExact(input);
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
+
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import javax.annotation.RegEx;
import org.opendaylight.yangtools.util.ClassLoaderUtils;
import org.opendaylight.yangtools.yang.binding.Augmentable;
import org.opendaylight.yangtools.yang.binding.Augmentation;
public class BindingReflections {
private static final long EXPIRATION_TIME = 60;
- private static final String ROOT_PACKAGE_PATTERN_STRING = "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])";
+
+ @RegEx
+ private static final String ROOT_PACKAGE_PATTERN_STRING =
+ "(org.opendaylight.yang.gen.v1.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])";
private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING);
private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class);
}
/**
- * Find augmentation target class from concrete Augmentation class
- *
- * This method uses first generic argument of implemented
- * {@link Augmentation} interface.
+ * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
+ * implemented {@link Augmentation} interface.
*
* @param augmentation
* {@link Augmentation} subclass for which we want to determine
* augmentation target.
- * @return Augmentation target - class which augmentation provides
- * additional extensions.
+ * @return Augmentation target - class which augmentation provides additional extensions.
*/
public static Class<? extends Augmentable<?>> findAugmentationTarget(
final Class<? extends Augmentation<?>> augmentation) {
}
/**
- * Find data hierarchy parent from concrete Data class
- *
- * This method uses first generic argument of implemented {@link ChildOf}
- * interface.
+ * Find data hierarchy parent from concrete Data class. This method uses first generic argument of implemented
+ * {@link ChildOf} interface.
*
* @param childClass
* child class for which we want to find the parent class.
}
/**
- * Find data hierarchy parent from concrete Data class
- *
- * This method is shorthand which gets DataObject class by invoking
- * {@link DataObject#getImplementedInterface()} and uses
- * {@link #findHierarchicalParent(Class)}.
+ * Find data hierarchy parent from concrete Data class. This method is shorthand which gets DataObject class by
+ * invoking {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
*
* @param child
* Child object for which the parent needs to be located.
}
/**
- * Returns a QName associated to supplied type
- *
- * @param dataType
- * @return QName associated to supplied dataType. If dataType is
- * Augmentation method does not return canonical QName, but QName
- * with correct namespace revision, but virtual local name, since
- * augmentations do not have name.
+ * Returns a QName associated to supplied type.
*
- * May return null if QName is not present.
+ * @param dataType Data type class
+ * @return QName associated to supplied dataType. If dataType is Augmentation method does not return canonical
+ * QName, but QName with correct namespace revision, but virtual local name, since augmentations do not
+ * have name. May return null if QName is not present.
*/
public static final QName findQName(final Class<?> dataType) {
return CLASS_TO_QNAME.getUnchecked(dataType).orNull();
}
/**
- * Checks if method is RPC invocation
+ * Checks if method is RPC invocation.
*
* @param possibleMethod
* Method to check
}
/**
- *
- * Extracts Output class for RPC method
+ * Extracts Output class for RPC method.
*
* @param targetMethod
* method to scan
- * @return Optional.absent() if result type could not be get, or return type
- * is Void.
+ * @return Optional.absent() if result type could not be get, or return type is Void.
*/
@SuppressWarnings("rawtypes")
public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
}
/**
- *
- * Extracts input class for RPC method
+ * Extracts input class for RPC method.
*
* @param targetMethod
* method to scan
- * @return Optional.absent() if rpc has no input, Rpc input type otherwise.
+ * @return Optional.absent() if RPC has no input, RPC input type otherwise.
*/
@SuppressWarnings("rawtypes")
public static Optional<Class<? extends DataContainer>> resolveRpcInputClass(final Method targetMethod) {
}
/**
- *
* Checks if class is child of augmentation.
- *
- *
- * @param clazz
- * @return
*/
public static boolean isAugmentationChild(final Class<?> clazz) {
- // FIXME: Current resolver could be still confused when
- // child node was added by grouping
+ // FIXME: Current resolver could be still confused when child node was added by grouping
checkArgument(clazz != null);
@SuppressWarnings({ "rawtypes", "unchecked" })
return match.group(0);
}
+ @SuppressWarnings("checkstyle:illegalCatch")
public static final QNameModule getQNameModule(final Class<?> clz) {
- if(DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
+ if (DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
return findQName(clz).getModule();
}
try {
}
/**
+ * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
*
- * Returns instance of {@link YangModuleInfo} of declaring model for
- * specific class.
- *
- * @param cls
+ * @param cls data object class
* @return Instance of {@link YangModuleInfo} associated with model, from
* which this class was derived.
- * @throws Exception
*/
public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
checkArgument(cls != null);
return ClassLoaderUtils.withClassLoader(cls.getClassLoader(), (Callable<YangModuleInfo>) () -> {
Class<?> moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName);
return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null);
- });
+ });
}
public static String getModuleInfoClassName(final String packageName) {
}
/**
- *
* Check if supplied class is derived from YANG model.
*
* @param cls
}
/**
- *
* Checks if supplied method is callback for notifications.
*
- * @param method
+ * @param method method to check
* @return true if method is notification callback.
*/
public static boolean isNotificationCallback(final Method method) {
}
/**
+ * Checks is supplied class is a {@link Notification}.
*
- * Checks is supplied class is Notification.
- *
- * @param potentialNotification
- * @return
+ * @param potentialNotification class to examine
+ * @return True if the class represents a Notification.
*/
public static boolean isNotification(final Class<?> potentialNotification) {
checkArgument(potentialNotification != null, "potentialNotification must not be null.");
}
/**
- *
- * Loads {@link YangModuleInfo} infos available on current classloader.
- *
- * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with
- * {@link Thread#getContextClassLoader()} for current thread.
+ * Loads {@link YangModuleInfo} infos available on current classloader. This method is shorthand for
+ * {@link #loadModuleInfos(ClassLoader)} with {@link Thread#getContextClassLoader()} for current thread.
*
* @return Set of {@link YangModuleInfo} available for current classloader.
*/
}
/**
- *
* Loads {@link YangModuleInfo} infos available on supplied classloader.
*
- * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
- * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
- * simple classes which holds only pointers to actual instance
+ * <p>
+ * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for {@link YangModelBindingProvider}.
+ * {@link YangModelBindingProvider} are simple classes which holds only pointers to actual instance
* {@link YangModuleInfo}.
*
- * When {@link YangModuleInfo} is available, all dependencies are
- * recursivelly collected into returning set by collecting results of
- * {@link YangModuleInfo#getImportedModules()}.
- *
+ * <p>
+ * When {@link YangModuleInfo} is available, all dependencies are recursively collected into returning set by
+ * collecting results of {@link YangModuleInfo#getImportedModules()}.
*
* @param loader
* Classloader for which {@link YangModuleInfo} should be
}
/**
- *
* Checks if supplied class represents RPC Input / RPC Output.
*
* @param targetType
}
/**
- *
- * Scans supplied class and returns an iterable of all data children
- * classes.
+ * Scans supplied class and returns an iterable of all data children classes.
*
* @param type
* YANG Modeled Entity derived from DataContainer
}
/**
- *
- * Scans supplied class and returns an iterable of all data children
- * classes.
+ * Scans supplied class and returns an iterable of all data children classes.
*
* @param type
* YANG Modeled Entity derived from DataContainer
return ret;
}
- @SuppressWarnings({ "unchecked", "rawtypes" })
+ @SuppressWarnings({ "unchecked", "rawtypes", "checkstyle:illegalCatch" })
private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
if ("getClass".equals(method.getName()) || !method.getName().startsWith("get")
|| method.getParameterTypes().length > 0) {
return Optional.absent();
}
- @SuppressWarnings("rawtypes")
Class returnType = method.getReturnType();
if (DataContainer.class.isAssignableFrom(returnType)) {
return Optional.of(returnType);
} else if (List.class.isAssignableFrom(returnType)) {
try {
return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
- (Callable<Optional<Class<? extends DataContainer>>>) () -> {
- Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
- if (listResult instanceof Class
- && DataContainer.class.isAssignableFrom((Class) listResult)) {
- return Optional.of((Class) listResult);
- }
- return Optional.absent();
- });
+ (Callable<Optional<Class<? extends DataContainer>>>) () -> {
+ Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
+ if (listResult instanceof Class
+ && DataContainer.class.isAssignableFrom((Class) listResult)) {
+ return Optional.of((Class) listResult);
+ }
+ return Optional.absent();
+ });
} catch (Exception e) {
/*
- *
* It is safe to log this this exception on debug, since this
* method should not fail. Only failures are possible if the
* runtime / backing.
}
/**
- *
- * Tries to resolve QName for supplied class.
- *
- * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns
- * value if present.
- *
- * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
- *
- * @param key
- * @return
+ * Tries to resolve QName for supplied class. Looks up for static field with name from constant
+ * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if present. If field is not present uses
+ * {@link #computeQName(Class)} to compute QName for missing types.
*/
private static Optional<QName> resolveQNameNoCache(final Class<?> key) {
try {
}
/**
- * Computes QName for supplied class
+ * Computes QName for supplied class. Namespace and revision are same as {@link YangModuleInfo} associated with
+ * supplied class.
*
- * Namespace and revision are same as {@link YangModuleInfo} associated with supplied class.
* <p>
* If class is
* <ul>
* <li>augmentation: local name is "module name".
* </ul>
*
+ * <p>
* There is also fallback, if it is not possible to compute QName using following algorithm returns module
* QName.
*
- * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
- *
* @throws IllegalStateException If YangModuleInfo could not be resolved
* @throws IllegalArgumentException If supplied class was not derived from YANG model.
- *
*/
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ // FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
+ @SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:illegalCatch" })
private static QName computeQName(final Class key) {
- if (isBindingClass(key)) {
- YangModuleInfo moduleInfo;
- try {
- moduleInfo = getModuleInfo(key);
- } catch (Exception e) {
- throw new IllegalStateException("Unable to get QName for " + key
- + ". YangModuleInfo was not found.", e);
- }
- final QName module = getModuleQName(moduleInfo).intern();
- if (Augmentation.class.isAssignableFrom(key)) {
- return module;
- } else if (isRpcType(key)) {
- final String className = key.getSimpleName();
- if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
- return QName.create(module, "output").intern();
- } else {
- return QName.create(module, "input").intern();
- }
- }
- /*
- * Fallback for Binding types which do not have QNAME field
- */
+ checkArgument(isBindingClass(key), "Supplied class %s is not derived from YANG.", key);
+
+ YangModuleInfo moduleInfo;
+ try {
+ moduleInfo = getModuleInfo(key);
+ } catch (Exception e) {
+ throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",
+ e);
+ }
+ final QName module = getModuleQName(moduleInfo).intern();
+ if (Augmentation.class.isAssignableFrom(key)) {
return module;
- } else {
- throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
+ } else if (isRpcType(key)) {
+ final String className = key.getSimpleName();
+ if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
+ return QName.create(module, "output").intern();
+ } else {
+ return QName.create(module, "input").intern();
+ }
}
+
+ /*
+ * Fallback for Binding types which do not have QNAME field
+ */
+ return module;
}
}
/**
- * Given a {@link YangModuleInfo}, create a QName representing it. The QName
- * is formed by reusing the module's namespace and revision using the
- * module's name as the QName's local name.
+ * Given a {@link YangModuleInfo}, create a QName representing it. The QName is formed by reusing the module's
+ * namespace and revision using the module's name as the QName's local name.
*
* @param moduleInfo
* module information
}
/**
- * Extracts augmentation from Binding DTO field using reflection
+ * Extracts augmentation from Binding DTO field using reflection.
*
* @param input
* Instance of DataObject which is augmentable and may contain
}
/**
- *
* Determines if two augmentation classes or case classes represents same
* data.
+ *
* <p>
* Two augmentations or cases could be substituted only if and if:
* <ul>
* <li>If cases: Both are from same choice. Choice class was generated for
* data node in grouping.</li>
* </ul>
+ *
* <p>
* <b>Explanation:</b> Binding Specification reuses classes generated for
* groupings as part of normal data tree, this classes from grouping could
import org.opendaylight.yangtools.yang.common.QName;
final class ClassBasedRpcServiceInvoker extends AbstractMappedRpcInvoker<String> {
- private static final LoadingCache<Class<? extends RpcService>, RpcServiceInvoker> INVOKERS = CacheBuilder.newBuilder()
- .weakKeys()
+ private static final LoadingCache<Class<? extends RpcService>, RpcServiceInvoker> INVOKERS =
+ CacheBuilder.newBuilder().weakKeys()
.build(new CacheLoader<Class<? extends RpcService>, RpcServiceInvoker>() {
@Override
public RpcServiceInvoker load(final Class<? extends RpcService> key) {
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
public class DataObjectReadingUtil {
- private static final DataObjectReadingStrategy REAUSABLE_AUGMENTATION_READING_STRATEGY = new AugmentationReadingStrategy();
+ private static final DataObjectReadingStrategy REAUSABLE_AUGMENTATION_READING_STRATEGY =
+ new AugmentationReadingStrategy();
private DataObjectReadingUtil() {
throw new UnsupportedOperationException("Utility class. Instantion is not allowed.");
}
/**
+ * Read data from parent at specified path.
*
* @param parent
* Parent object on which read operation will be performed
* @param parentPath
* Path, to parent object.
* @param childPath
- * Path, which is nested to parent, and should be readed.
+ * Path, which is nested to parent, and should be read.
* @return Value of object.
*/
- public static final <T extends DataObject, P extends DataObject> Map<InstanceIdentifier<T>, T> readData(final P parent,
- final InstanceIdentifier<P> parentPath, final InstanceIdentifier<T> childPath) {
+ public static final <T extends DataObject, P extends DataObject> Map<InstanceIdentifier<T>, T> readData(
+ final P parent, final InstanceIdentifier<P> parentPath, final InstanceIdentifier<T> childPath) {
checkArgument(parent != null, "Parent must not be null.");
checkArgument(parentPath != null, "Parent path must not be null");
checkArgument(childPath != null, "Child path must not be null");
List<PathArgument> pathArgs = subList(parentPath.getPathArguments(), childPath.getPathArguments());
@SuppressWarnings("rawtypes")
- Map<InstanceIdentifier, DataContainer> lastFound = Collections
- .<InstanceIdentifier, DataContainer> singletonMap(parentPath, parent);
+ Map<InstanceIdentifier, DataContainer> lastFound = Collections.singletonMap(parentPath, parent);
for (PathArgument pathArgument : pathArgs) {
@SuppressWarnings("rawtypes")
final ImmutableMap.Builder<InstanceIdentifier, DataContainer> potentialBuilder = ImmutableMap.builder();
- for (@SuppressWarnings("rawtypes")
- Entry<InstanceIdentifier, DataContainer> entry : lastFound.entrySet()) {
+ for (@SuppressWarnings("rawtypes") Entry<InstanceIdentifier, DataContainer> entry : lastFound.entrySet()) {
potentialBuilder.putAll(readData(entry, pathArgument));
}
lastFound = potentialBuilder.build();
}
@SuppressWarnings("rawtypes")
- private static final Map<InstanceIdentifier, DataContainer> readData(final DataContainer parent,
+ private static Map<InstanceIdentifier, DataContainer> readData(final DataContainer parent,
final InstanceIdentifier parentPath, final PathArgument child) {
checkArgument(parent != null, "Object should not be null.");
checkArgument(child != null, "Child argument should not be null");
private final Method getterMethod;
@SuppressWarnings("unchecked")
- public DataObjectReadingStrategy(final Class parentType, final Class childType) {
+ DataObjectReadingStrategy(final Class parentType, final Class childType) {
checkArgument(DataContainer.class.isAssignableFrom(parentType));
checkArgument(DataContainer.class.isAssignableFrom(childType));
this.parentType = parentType;
}
@SuppressWarnings("unchecked")
- public DataObjectReadingStrategy(final Class parentType, final Class childType, final Method getter) {
+ DataObjectReadingStrategy(final Class parentType, final Class childType, final Method getter) {
this.parentType = parentType;
this.childType = childType;
this.getterMethod = getter;
@SuppressWarnings("rawtypes")
private static class ContainerReadingStrategy extends DataObjectReadingStrategy {
-
- public ContainerReadingStrategy(final Class<? extends DataContainer> parent, final Class<? extends DataContainer> child) {
+ ContainerReadingStrategy(final Class<? extends DataContainer> parent,
+ final Class<? extends DataContainer> child) {
super(parent, child);
checkArgument(child.isAssignableFrom(getGetterMethod().getReturnType()));
}
@SuppressWarnings("rawtypes")
private static class ListItemReadingStrategy extends DataObjectReadingStrategy {
-
- public ListItemReadingStrategy(final Class<? extends DataContainer> parent, final Class child) {
+ ListItemReadingStrategy(final Class<? extends DataContainer> parent, final Class child) {
super(parent, child);
checkArgument(Iterable.class.isAssignableFrom(getGetterMethod().getReturnType()));
}
private Map<InstanceIdentifier, DataContainer> readAll(final Iterable<Identifiable> dataList,
final InstanceIdentifier parentPath) {
- Builder<InstanceIdentifier, DataContainer> result = ImmutableMap
- .<InstanceIdentifier, DataContainer> builder();
+ Builder<InstanceIdentifier, DataContainer> result = ImmutableMap.builder();
for (Identifiable item : dataList) {
@SuppressWarnings("unchecked")
InstanceIdentifier childPath = parentPath.child(getChildType(), item.getKey());
}
@SuppressWarnings("unchecked")
- private static Map<InstanceIdentifier, DataContainer> readUsingIdentifiableItem(final Iterable<Identifiable> dataList,
- final IdentifiableItem childArgument, final InstanceIdentifier parentPath) {
+ private static Map<InstanceIdentifier, DataContainer> readUsingIdentifiableItem(
+ final Iterable<Identifiable> dataList, final IdentifiableItem childArgument,
+ final InstanceIdentifier parentPath) {
final Identifier<?> key = childArgument.getKey();
for (Identifiable item : dataList) {
if (key.equals(item.getKey()) && item instanceof DataContainer) {
}
private static final class AugmentationReadingStrategy extends DataObjectReadingStrategy {
-
- public AugmentationReadingStrategy() {
+ AugmentationReadingStrategy() {
super(Augmentable.class, Augmentation.class, null);
}
final PathArgument childArgument, final InstanceIdentifier builder) {
checkArgument(childArgument instanceof Item<?>, "Path Argument must be Item without keys");
DataContainer aug = read(parent, childArgument.getType());
- if (aug != null) {
- @SuppressWarnings("unchecked")
- final InstanceIdentifier childPath = builder.child(childArgument.getType());
- return Collections.singletonMap(childPath, aug);
- } else {
+ if (aug == null) {
return Collections.emptyMap();
}
+
+ @SuppressWarnings("unchecked")
+ final InstanceIdentifier childPath = builder.child(childArgument.getType());
+ return Collections.singletonMap(childPath, aug);
}
@Override
}
/**
- * Create sublist view of child from element on [size-of-parent] position to
- * last element.
+ * Create sublist view of child from element on [size-of-parent] position to last element.
*
- * @param parent
- * @param child
* @return sublist view of child argument
* @throws IllegalArgumentException
* if parent argument is bigger than child
*/
private static <P, C> List<C> subList(final Iterable<P> parent, final Iterable<C> child) {
- Iterator<P> iParent = parent.iterator();
+ Iterator<P> parentIt = parent.iterator();
List<C> result = new ArrayList<>();
for (C arg : child) {
- if (iParent.hasNext()) {
- iParent.next();
+ if (parentIt.hasNext()) {
+ parentIt.next();
} else {
result.add(arg);
}
}
- if (iParent.hasNext()) {
+ if (parentIt.hasNext()) {
throw new IllegalArgumentException("Parent argument is bigger than child.");
}
return result;
}
-
}
/**
* Provides single method invocation of notificatoin callbacks on supplied instance.
*
+ * <p>
* Notification Listener invoker provides common invocation interface for any subtype of {@link NotificationListener}.
* via {@link #invokeNotification(NotificationListener, QName, DataContainer)} method.
- *
*/
public final class NotificationListenerInvoker {
private static final Lookup LOOKUP = MethodHandles.publicLookup();
- private static final LoadingCache<Class<? extends NotificationListener>, NotificationListenerInvoker> INVOKERS = CacheBuilder
- .newBuilder().weakKeys()
+ private static final LoadingCache<Class<? extends NotificationListener>, NotificationListenerInvoker> INVOKERS =
+ CacheBuilder .newBuilder().weakKeys()
.build(new CacheLoader<Class<? extends NotificationListener>, NotificationListenerInvoker>() {
private NotificationListenerInvoker createInvoker(
}
private Map<QName, MethodHandle> createInvokerMap(final Class<? extends NotificationListener> key) {
- final Builder<QName, MethodHandle> ret = ImmutableMap.<QName, MethodHandle> builder();
+ final Builder<QName, MethodHandle> ret = ImmutableMap.builder();
for (final Method method : key.getMethods()) {
if (BindingReflections.isNotificationCallback(method)) {
MethodHandle handle;
try {
handle = LOOKUP.unreflect(method).asType(MethodType.methodType(void.class,
- NotificationListener.class, DataContainer.class));
+ NotificationListener.class, DataContainer.class));
ret.put(name, handle);
} catch (final IllegalAccessException e) {
throw new IllegalStateException("Can not access public method.", e);
}
@Override
- public NotificationListenerInvoker load(final Class<? extends NotificationListener> key) throws Exception {
+ public NotificationListenerInvoker load(final Class<? extends NotificationListener> key) {
return createInvoker(key);
}
}
/**
- *
- * Creates RPCServiceInvoker for specified RpcService type
+ * Creates RPCServiceInvoker for specified RpcService type.
*
* @param type
* RpcService interface, which was generated from model.
* @return Cached instance of {@link NotificationListenerInvoker} for
* supplied RPC type.
- *
*/
public static NotificationListenerInvoker from(final Class<? extends NotificationListener> type) {
Preconditions.checkArgument(type.isInterface());
* Name of RPC to be invoked.
* @param input
* Input data for RPC.
- *
*/
+ @SuppressWarnings("checkstyle:illegalCatch")
public void invokeNotification(@Nonnull final NotificationListener impl, @Nonnull final QName rpcName,
@Nullable final DataContainer input) {
Preconditions.checkNotNull(impl, "implemetation must be supplied");
try {
invoker.invokeExact(impl, input);
} catch (final Throwable e) {
- throw Throwables.propagate(e);
+ Throwables.throwIfUnchecked(e);
+ throw new RuntimeException(e);
}
}
-
}
import org.opendaylight.yangtools.yang.common.RpcResult;
class RpcMethodInvokerWithInput extends RpcMethodInvoker {
+ private static final MethodType INVOCATION_SIGNATURE = MethodType.methodType(Future.class, RpcService.class,
+ DataObject.class);
- private static final MethodType INVOCATION_SIGNATURE =
- MethodType.methodType(Future.class, RpcService.class, DataObject.class);
private final MethodHandle handle;
- RpcMethodInvokerWithInput(MethodHandle methodHandle) {
+ RpcMethodInvokerWithInput(final MethodHandle methodHandle) {
this.handle = methodHandle.asType(INVOCATION_SIGNATURE);
}
@Override
- public Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input) {
+ @SuppressWarnings("checkstyle:illegalCatch")
+ public Future<RpcResult<?>> invokeOn(final RpcService impl, final DataObject input) {
try {
return (Future<RpcResult<?>>) handle.invokeExact(impl,input);
} catch (Throwable e) {
- throw Throwables.propagate(e);
+ Throwables.throwIfUnchecked(e);
+ throw new RuntimeException(e);
}
}
-
}
\ No newline at end of file
private static final MethodType INVOCATION_SIGNATURE = MethodType.methodType(Future.class, RpcService.class);
private final MethodHandle handle;
- RpcMethodInvokerWithoutInput(MethodHandle methodHandle) {
+ RpcMethodInvokerWithoutInput(final MethodHandle methodHandle) {
this.handle = methodHandle.asType(INVOCATION_SIGNATURE);
}
@Override
- public Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input) {
+ @SuppressWarnings("checkstyle:illegalCatch")
+ public Future<RpcResult<?>> invokeOn(final RpcService impl, final DataObject input) {
try {
return (Future<RpcResult<?>>) handle.invokeExact(impl);
} catch (Throwable e) {
- throw Throwables.propagate(e);
+ Throwables.throwIfUnchecked(e);
+ throw new RuntimeException(e);
}
}
-
}
\ No newline at end of file
/**
* Provides single method invocation of RPCs on supplied instance.
*
- * Rpc Service invoker provides common invocation interface for any subtype of {@link RpcService}.
+ * <p>
+ * RPC Service invoker provides common invocation interface for any subtype of {@link RpcService}.
* via {@link #invokeRpc(RpcService, QName, DataObject)} method.
*/
public abstract class RpcServiceInvoker {
private static final Logger LOG = LoggerFactory.getLogger(RpcServiceInvoker.class);
/**
- * Creates RPCServiceInvoker for specified RpcService type
+ * Creates RPCServiceInvoker for specified RpcService type.
*
* @param type RpcService interface, which was generated from model.
* @return Cached instance of {@link RpcServiceInvoker} for supplied RPC type.
- *
*/
public static RpcServiceInvoker from(final Class<? extends RpcService> type) {
return ClassBasedRpcServiceInvoker.instanceFor(type);
for (QName qname : qnameToMethod.keySet()) {
if (module != null) {
if (!module.equals(qname.getModule())) {
- LOG.debug("QNames from different modules {} and {}, falling back to QName map", module, qname.getModule());
+ LOG.debug("QNames from different modules {} and {}, falling back to QName map", module,
+ qname.getModule());
return QNameRpcServiceInvoker.instanceFor(qnameToMethod);
}
} else {
* @param input Input data for RPC.
* @return Future which will complete once rpc procesing is finished.
*/
- public abstract Future<RpcResult<?>> invokeRpc(@Nonnull final RpcService impl, @Nonnull final QName rpcName, @Nullable final DataObject input);
+ public abstract Future<RpcResult<?>> invokeRpc(@Nonnull RpcService impl, @Nonnull QName rpcName,
+ @Nullable DataObject input);
}
* Utility class for instantiating value-type generated objects with String being the base type. Unlike the normal
* constructor, instances of this class bypass string validation.
*
+ * <p>
* THE USE OF THIS CLASS IS DANGEROUS AND SHOULD ONLY BE USED TO IMPLEMENT WELL-AUDITED AND CORRECT UTILITY METHODS
* SHIPPED WITH MODELS TO PROVIDE INSTANTIATION FROM TYPES DIFFERENT THAN STRING.
*
+ * <p>
* APPLICATION CODE <em>MUST NOT</em> USE THIS CLASS DIRECTLY. VIOLATING THIS CONSTRAINT HAS SECURITY AND CORRECTNESS
* IMPLICATIONS ON EVERY USER INTERACTING WITH THE RESULTING OBJECTS.
*
return false;
}
+ @SuppressWarnings("checkstyle:illegalCatch")
public T newInstance(final String string) {
Preconditions.checkNotNull(string, "Argument may not be null");
LOG.trace("Instantiated new object {} value {}", ret.getClass(), string);
return ret;
} catch (Throwable e) {
- throw Throwables.propagate(e);
+ Throwables.throwIfUnchecked(e);
+ throw new RuntimeException(e);
}
}
import static org.junit.Assert.fail;
import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.Date;
import org.junit.Test;
}
@Test(expected = UnsupportedOperationException.class)
+ @SuppressWarnings("checkstyle:illegalThrows")
public void privateConstructTest() throws Throwable {
- final Constructor<BindingMapping> bindingMappingConstructor =
- BindingMapping.class.getDeclaredConstructor();
+ final Constructor<BindingMapping> bindingMappingConstructor = BindingMapping.class.getDeclaredConstructor();
assertFalse(bindingMappingConstructor.isAccessible());
bindingMappingConstructor.setAccessible(true);
try {
bindingMappingConstructor.newInstance();
fail("Expected exception for calling private constructor");
- } catch (Exception e) {
+ } catch (InvocationTargetException e) {
throw e.getCause();
}
}
import org.opendaylight.yangtools.yang.binding.Identifier;
-public class NodeChildKey implements //
- Identifier<NodeChild> {
- private static final long serialVersionUID = 1L;
- private final int id;
+public class NodeChildKey implements Identifier<NodeChild> {
+ private static final long serialVersionUID = 1L;
- public NodeChildKey(int id) {
+ private final int id;
+
+ public NodeChildKey(final int id) {
this.id = id;
}
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + id;
- return result;
+ return Integer.hashCode(id);
}
@Override
- public boolean equals(Object obj) {
- if (this == obj)
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
NodeChildKey other = (NodeChildKey) obj;
- if (id != other.id)
+ if (id != other.id) {
return false;
+ }
return true;
}
}
import org.opendaylight.yangtools.yang.binding.Identifier;
-public class NodeKey implements //
- Identifier<Node> {
- private static final long serialVersionUID = 1L;
- private final int id;
+public class NodeKey implements Identifier<Node> {
+ private static final long serialVersionUID = 1L;
- public NodeKey(int id) {
+ private final int id;
+
+ public NodeKey(final int id) {
this.id = id;
}
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + id;
- return result;
+ return Integer.hashCode(id);
}
@Override
- public boolean equals(Object obj) {
- if (this == obj)
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
NodeKey other = (NodeKey) obj;
- if (id != other.id)
+ if (id != other.id) {
return false;
+ }
return true;
}
}
assertTrue(getGetter(TestAugmentationWrongTypeClass.class).getAugmentations(null).isEmpty());
final AugmentationFieldGetter augmentationFieldGetter = getGetter(TestAugmentationClass.class);
- final Augmentation augmentation = mock(Augmentation.class);
+ final Augmentation<?> augmentation = mock(Augmentation.class);
final TestAugmentationClass testAugmentationClass = new TestAugmentationClass();
testAugmentationClass.addAugmentation(augmentation, augmentation);
}
private final class TestAugmentationClass {
- private Map augmentation = new HashMap();
+ private final Map<Augmentation<?>, Augmentation<?>> augmentation = new HashMap<>();
- void addAugmentation(Augmentation key, Augmentation value){
+ void addAugmentation(final Augmentation<?> key, final Augmentation<?> value) {
augmentation.put(key, value);
}
}
import static org.opendaylight.yangtools.yang.binding.util.BindingReflections.findHierarchicalParent;
import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
assertNull(findHierarchicalParent(mock(DataObject.class)));
assertEquals(GroupingFoo.class, BindingReflections.findHierarchicalParent(FooChild.class));
- final ChildOf childOf = mock(FooChild.class);
+ final ChildOf<?> childOf = mock(FooChild.class);
doReturn(FooChild.class).when(childOf).getImplementedInterface();
assertEquals(GroupingFoo.class, BindingReflections.findHierarchicalParent(childOf));
assertTrue(BindingReflections.isRpcMethod(TestImplementation.class.getDeclaredMethod("rpcMethodTest")));
}
@Test(expected = UnsupportedOperationException.class)
+ @SuppressWarnings("checkstyle:illegalThrows")
public void testPrivateConstructor() throws Throwable {
assertFalse(BindingReflections.class.getDeclaredConstructor().isAccessible());
- final Constructor constructor = BindingReflections.class.getDeclaredConstructor();
+ final Constructor<?> constructor = BindingReflections.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
- } catch (Exception e) {
+ } catch (InvocationTargetException e) {
throw e.getCause();
}
}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.UnmodifiableIterator;
import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Before;
final ImmutableSet<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> entries = map.entrySet();
final UnmodifiableIterator<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> it = entries.iterator();
- while(it.hasNext()) {
+ while (it.hasNext()) {
entry = it.next();
}
}
}
@Test(expected = UnsupportedOperationException.class)
+ @SuppressWarnings("checkstyle:illegalThrows")
public void testPrivateConstructor() throws Throwable {
assertFalse(DataObjectReadingUtil.class.getDeclaredConstructor().isAccessible());
- final Constructor constructor = DataObjectReadingUtil.class.getDeclaredConstructor();
+ final Constructor<?> constructor = DataObjectReadingUtil.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
- } catch (Exception e) {
+ } catch (InvocationTargetException e) {
throw e.getCause();
}
}
import static org.mockito.Mockito.mock;
import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.UncheckedExecutionException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.WrongMethodTypeException;
import org.junit.Test;
}
@Test(expected = IllegalStateException.class)
+ @SuppressWarnings("checkstyle:illegalThrows")
public void fromWithExceptionTest() throws Throwable {
try {
NotificationListenerInvoker.from(TestPrivateInterface.class);
fail("Expected IllegalAccessException");
- } catch (Exception e) {
+ } catch (UncheckedExecutionException e) {
throw e.getCause();
}
}
public void invokeOnTest() throws Exception {
final MethodHandle methodHandle = MethodHandles.lookup().unreflect(
TestImplClassWithoutInput.class.getDeclaredMethod("testMethod", RpcService.class));
- final RpcMethodInvokerWithoutInput rpcMethodInvokerWithoutInput = new RpcMethodInvokerWithoutInput(methodHandle);
- assertNotNull(rpcMethodInvokerWithoutInput.invokeOn(TEST_IMPL_CLASS, null));
+ final RpcMethodInvokerWithoutInput invokerWithoutInput = new RpcMethodInvokerWithoutInput(methodHandle);
+ assertNotNull(invokerWithoutInput.invokeOn(TEST_IMPL_CLASS, null));
}
@Test(expected = InternalError.class)
public void invokeOnWithException() throws Exception {
final MethodHandle methodHandle = MethodHandles.lookup().unreflect(
TestImplClassWithoutInput.class.getDeclaredMethod("testMethodWithException", RpcService.class));
- final RpcMethodInvokerWithoutInput rpcMethodInvokerWithoutInput = new RpcMethodInvokerWithoutInput(methodHandle);
- rpcMethodInvokerWithoutInput.invokeOn(TEST_IMPL_CLASS, null);
+ final RpcMethodInvokerWithoutInput invokerWithoutInput = new RpcMethodInvokerWithoutInput(methodHandle);
+ invokerWithoutInput.invokeOn(TEST_IMPL_CLASS, null);
}
private static final class TestImplClassWithoutInput implements RpcService {
- static Future testMethod(RpcService testArgument) {
+ @SuppressWarnings("unused")
+ static Future<?> testMethod(final RpcService testArgument) {
return Futures.immediateFuture(null);
}
- static Future testMethodWithException(RpcService testArgument) throws Exception {
+ @SuppressWarnings("unused")
+ static Future<?> testMethodWithException(final RpcService testArgument) throws Exception {
throw new InternalError();
}
}
@Test
public void createTest() throws Exception {
- final StringValueObjectFactory stringValueObjectFactory =
+ final StringValueObjectFactory<?> stringValueObjectFactory =
StringValueObjectFactory.create(TestClass.class, "testTemplate");
assertNotNull(stringValueObjectFactory);
assertEquals("testTemplate", stringValueObjectFactory.getTemplate().toString());
@Test
public void newInstanceTest() throws Exception {
- final StringValueObjectFactory instance = StringValueObjectFactory.create(TestClass.class, "testTemplate");
+ final StringValueObjectFactory<?> instance = StringValueObjectFactory.create(TestClass.class, "testTemplate");
assertEquals("instanceTest", instance.newInstance("instanceTest").toString());
}
StringValueObjectFactory.create(String.class, "");
}
- private static final class TestClass {
+ public static final class TestClass {
+ @SuppressWarnings("checkstyle:memberName")
private final String _value;
- public TestClass(TestClass parrent) {
- this._value = parrent._value;
+ public TestClass(final TestClass parent) {
+ this._value = parent._value;
}
- public TestClass(String value) {
+ public TestClass(final String value) {
this._value = value;
}
return this._value;
}
}
-}
\ No newline at end of file
+}