concepts/util should have their checkstyle enforced.
Change-Id: I752ce3c75e69446a1284b511b5221553d7187bb5
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
- <failsOnError>true</failsOnError>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
</configuration>
</plugin>
</plugins>
</build>
- <!--
- Maven Site Configuration
+ <!--
+ Maven Site Configuration
- 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>
+ 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>
+ <distributionManagement>
+ <site>
+ <id>opendaylight-site</id>
+ <url>${nexus.site.url}/${project.artifactId}/</url>
+ </site>
+ </distributionManagement>
</project>
public interface Identifiable<T> {
/**
- * Return this objects Identifier
+ * Return this objects Identifier.
*
* @return Object's identifier, must not be null.
*/
if (patchIdx == -1) {
minorStr = str.substring(minorIdx + 1);
return create(Integer.parseInt(str.substring(0, minorIdx), 10), Integer.parseInt(minorStr, 10));
- } else {
- minorStr = str.substring(minorIdx + 1, patchIdx);
}
+ minorStr = str.substring(minorIdx + 1, patchIdx);
return create(Integer.parseInt(str.substring(0, minorIdx), 10), Integer.parseInt(minorStr, 10),
Integer.parseInt(str.substring(patchIdx + 1), 10));
}
* @throws NullPointerException if output is null
*/
public static void writeLong(final DataOutput out, final long value, final int flags) throws IOException {
- Preconditions.checkArgument((flags & 0xFFFFFF0F) == 0, "Invalid flags {}", flags);
+ Preconditions.checkArgument((flags & 0xFFFFFF0F) == 0, "Invalid flags %s", flags);
final int bytes = valueBytes(value);
out.writeByte(bytes | flags);
writeValue(out, value, bytes);
*/
public static long readLongBody(final @Nonnull DataInput in, final byte header) throws IOException {
int bytes = header & 0xF;
- if (bytes < 8) {
- if (bytes > 0) {
- long value = 0;
- if (bytes >= 4) {
- bytes -= 4;
- value = (in.readInt() & 0xFFFFFFFFL) << (bytes * Byte.SIZE);
- }
- if (bytes >= 2) {
- bytes -= 2;
- value |= in.readUnsignedShort() << (bytes * Byte.SIZE);
- }
- if (bytes > 0) {
- value |= in.readUnsignedByte();
- }
- return value;
- } else {
- return 0;
- }
- } else {
+ if (bytes >= 8) {
return in.readLong();
}
+
+ if (bytes <= 0) {
+ return 0;
+ }
+
+ long value = 0;
+ if (bytes >= 4) {
+ bytes -= 4;
+ value = (in.readInt() & 0xFFFFFFFFL) << bytes * Byte.SIZE;
+ }
+ if (bytes >= 2) {
+ bytes -= 2;
+ value |= in.readUnsignedShort() << bytes * Byte.SIZE;
+ }
+ if (bytes > 0) {
+ value |= in.readUnsignedByte();
+ }
+ return value;
}
/**
int left = bytes;
if (left >= 4) {
left -= 4;
- out.writeInt((int)(value >>> (left * Byte.SIZE)));
+ out.writeInt((int)(value >>> left * Byte.SIZE));
}
if (left >= 2) {
left -= 2;
- out.writeShort((int)(value >>> (left * Byte.SIZE)));
+ out.writeShort((int)(value >>> left * Byte.SIZE));
}
if (left > 0) {
out.writeByte((int)(value & 0xFF));
if ((value & 0xFFFFFFFF00000000L) != 0) {
if ((value & 0xFFFF000000000000L) != 0) {
return (value & 0xFF00000000000000L) != 0 ? 8 : 7;
- } else {
- return (value & 0x0000FF0000000000L) != 0 ? 6 : 5;
}
+ return (value & 0x0000FF0000000000L) != 0 ? 6 : 5;
} else if ((value & 0x00000000FFFFFFFFL) != 0) {
if ((value & 0x00000000FFFF0000L) != 0) {
return (value & 0x00000000FF000000L) != 0 ? 4 : 3;
- } else {
- return (value & 0x000000000000FF00L) != 0 ? 2 : 1;
}
+ return (value & 0x000000000000FF00L) != 0 ? 2 : 1;
} else {
return 0;
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
+ <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>1.9.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
+ <parent>
+ <groupId>org.opendaylight.odlparent</groupId>
+ <artifactId>bundle-parent</artifactId>
+ <version>1.9.0-SNAPSHOT</version>
+ <relativePath/>
+ </parent>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>testutils</artifactId>
- <version>1.2.0-SNAPSHOT</version>
- <!-- Currently not needed, maybe later: <packaging>bundle</packaging> -->
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>testutils</artifactId>
+ <version>1.2.0-SNAPSHOT</version>
+ <!-- Currently not needed, maybe later: <packaging>bundle</packaging> -->
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yangtools-artifacts</artifactId>
- <version>${project.version}</version>
- <scope>import</scope>
- <type>pom</type>
- </dependency>
- </dependencies>
- </dependencyManagement>
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yangtools-artifacts</artifactId>
+ <version>${project.version}</version>
+ <scope>import</scope>
+ <type>pom</type>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
- <dependencies>
- <!-- NOTE: The use of <scope> here is a little particular, compared to other standard projects...
+ <dependencies>
+ <!-- NOTE: The use of <scope> here is a little particular, compared to other standard projects...
- As this test helper project is intended to itself be used as a <scope>test
- <dependency> so that the utility code in src/main/java of this project can
- be used to write src/test/java code in projects using it, all <dependencies>
- here are <scope>compile here (the default, don't mention it), and NOT <scope>test.
- (Only a <dependency> which only this project would want to use in its own src/test/java code
- but not expose to projects depending on it would be <scope>test. However that kind of against
- the whole point of this project, and currently there no such dependencies here.
- -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>com.google.truth</groupId>
- <artifactId>truth</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
+ As this test helper project is intended to itself be used as a <scope>test
+ <dependency> so that the utility code in src/main/java of this project can
+ be used to write src/test/java code in projects using it, all <dependencies>
+ here are <scope>compile here (the default, don't mention it), and NOT <scope>test.
+ (Only a <dependency> which only this project would want to use in its own src/test/java code
+ but not expose to projects depending on it would be <scope>test. However that kind of against
+ the whole point of this project, and currently there no such dependencies here.
+ -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.truth</groupId>
+ <artifactId>truth</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
- </dependencies>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
</project>
</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>
}
@Override
- public final boolean equals(final Object o) {
- if (this == o) {
+ public final boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (o == null) {
+ if (obj == null) {
return false;
}
- return getClass().equals(o.getClass()) && value.equals(((AbstractIdentifier<?>)o).value);
+ return getClass().equals(obj.getClass()) && value.equals(((AbstractIdentifier<?>)obj).value);
}
@Override
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final int compareTo(@Nonnull final T o) {
return getValue().compareTo(o.getValue());
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final int compareTo(@Nonnull final T o) {
return getValue().compareTo(o.getValue());
}
/**
* Runs {@link Supplier} with provided {@link ClassLoader}.
*
- * <p>Invokes supplies function and makes sure that original {@link ClassLoader}
+ * <p>
+ * Invokes supplies function and makes sure that original {@link ClassLoader}
* is context {@link ClassLoader} after execution.
*
* @param cls {@link ClassLoader} to be used.
/**
* Runs {@link Callable} with provided {@link ClassLoader}.
*
+ * <p>
* Invokes supplies function and makes sure that original {@link ClassLoader}
* is context {@link ClassLoader} after execution.
*
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
for (Object wlk : array) {
if (o.equals(wlk)) {
@Override
public Iterator<E> iterator() {
return new UnmodifiableIterator<E>() {
- private int i = 0;
+ private int offset = 0;
@Override
public boolean hasNext() {
- return i < array.length;
+ return offset < array.length;
}
@Override
public E next() {
- if (i >= array.length) {
+ if (offset >= array.length) {
throw new NoSuchElementException();
}
- return array[i++];
+ return array[offset++];
}
};
}
}
@Nonnull
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "unchecked", "checkstyle:parameterName" })
@Override
public <T> T[] toArray(@Nonnull final T[] a) {
if (a.length < array.length) {
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean add(final E e) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean containsAll(@Nonnull final Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean addAll(@Nonnull final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean removeAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean retainAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
}
final StringBuilder sb = new StringBuilder("[");
- int i = 0;
- while (i < array.length - 1) {
- sb.append(String.valueOf(array[i++])).append(", ");
+ int offset = 0;
+ while (offset < array.length - 1) {
+ sb.append(String.valueOf(array[offset++])).append(", ");
}
- return sb.append(String.valueOf(array[i])).append(']').toString();
+ return sb.append(String.valueOf(array[offset])).append(']').toString();
}
}
}
@Override
- public boolean offer(final E entry) {
+ @SuppressWarnings("checkstyle:parameterName")
+ public boolean offer(final E e) {
return false;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean offerFirst(final E e) {
return false;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean offerLast(final E e) {
return false;
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public <T> T[] toArray(final T[] a) {
return Preconditions.checkNotNull(a);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public void addFirst(final E e) {
add(e);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public void addLast(final E e) {
add(e);
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean removeFirstOccurrence(final Object o) {
return false;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean removeLastOccurrence(final Object o) {
return false;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public void push(final E e) {
addFirst(e);
}
public final class EvenMoreObjects {
@SuppressWarnings("unchecked")
- public static <T> boolean equalsHelper(T self, Object other, BooleanEqualsFunction<T> equals) {
+ public static <T> boolean equalsHelper(final T self, final Object other, final BooleanEqualsFunction<T> equals) {
if (other == self) {
return true;
}
if (self.getClass() != other.getClass()) {
return false;
}
- return equals.apply(self, (T) other);
+ return equals.apply(self, (T) other).booleanValue();
}
@FunctionalInterface
public final class ExecutorServiceUtil {
private static final class WaitInQueueExecutionHandler implements RejectedExecutionHandler {
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
- if (executor.isShutdown() ) {
- throw new RejectedExecutionException( "Executor has been shutdown." );
+ if (executor.isShutdown()) {
+ throw new RejectedExecutionException("Executor has been shutdown.");
}
try {
public static <E> BlockingQueue<E> offerFailingBlockingQueue(final BlockingQueue<E> delegate) {
return new ForwardingBlockingQueue<E>() {
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean offer(@Nonnull final E o) {
return false;
}
* timeout period. If the timeout elapses before termination, the executor is forcefully
* shutdown.
*/
- public static void tryGracefulShutdown(final ExecutorService executor, long timeout,
- TimeUnit unit ) {
+ public static void tryGracefulShutdown(final ExecutorService executor, final long timeout, final TimeUnit unit) {
executor.shutdown();
* All other maps are converted to an {@link ImmutableOffsetMap} with the
* same iteration order as input.
*
- * @param m
+ * @param map
* Input map, may not be null.
* @return An isolated, immutable copy of the input map
*/
- @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> m) {
+ @Nonnull public static <K, V> Map<K, V> orderedCopyOf(@Nonnull final Map<K, V> map) {
// Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
- if (m instanceof ImmutableOffsetMap || m instanceof SharedSingletonMap) {
- return m;
+ if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
+ return map;
}
// Familiar and efficient to copy
- if (m instanceof MutableOffsetMap) {
- return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
+ if (map instanceof MutableOffsetMap) {
+ return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
}
- final int size = m.size();
+ final int size = map.size();
if (size == 0) {
// Shares a single object
return ImmutableMap.of();
}
if (size == 1) {
// Efficient single-entry implementation
- final Entry<K, V> e = m.entrySet().iterator().next();
+ final Entry<K, V> e = map.entrySet().iterator().next();
return SharedSingletonMap.orderedOf(e.getKey(), e.getValue());
}
- final Map<K, Integer> offsets = OffsetMapCache.orderedOffsets(m.keySet());
+ final Map<K, Integer> offsets = OffsetMapCache.orderedOffsets(map.keySet());
@SuppressWarnings("unchecked")
final V[] array = (V[]) new Object[offsets.size()];
- for (Entry<K, V> e : m.entrySet()) {
+ for (Entry<K, V> e : map.entrySet()) {
array[offsets.get(e.getKey())] = e.getValue();
}
* All other maps are converted to an {@link ImmutableOffsetMap}. Iterator
* order is not guaranteed to be retained.
*
- * @param m
+ * @param map
* Input map, may not be null.
* @return An isolated, immutable copy of the input map
*/
- @Nonnull public static <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> m) {
+ @Nonnull public static <K, V> Map<K, V> unorderedCopyOf(@Nonnull final Map<K, V> map) {
// Prevent a copy. Note that ImmutableMap is not listed here because of its potentially larger keySet overhead.
- if (m instanceof ImmutableOffsetMap || m instanceof SharedSingletonMap) {
- return m;
+ if (map instanceof ImmutableOffsetMap || map instanceof SharedSingletonMap) {
+ return map;
}
// Familiar and efficient to copy
- if (m instanceof MutableOffsetMap) {
- return ((MutableOffsetMap<K, V>) m).toUnmodifiableMap();
+ if (map instanceof MutableOffsetMap) {
+ return ((MutableOffsetMap<K, V>) map).toUnmodifiableMap();
}
- final int size = m.size();
+ final int size = map.size();
if (size == 0) {
// Shares a single object
return ImmutableMap.of();
}
if (size == 1) {
// Efficient single-entry implementation
- final Entry<K, V> e = m.entrySet().iterator().next();
+ final Entry<K, V> e = map.entrySet().iterator().next();
return SharedSingletonMap.unorderedOf(e.getKey(), e.getValue());
}
- final Map<K, Integer> offsets = OffsetMapCache.unorderedOffsets(m.keySet());
+ final Map<K, Integer> offsets = OffsetMapCache.unorderedOffsets(map.keySet());
@SuppressWarnings("unchecked")
final V[] array = (V[]) new Object[offsets.size()];
- for (Entry<K, V> e : m.entrySet()) {
+ for (Entry<K, V> e : map.entrySet()) {
array[offsets.get(e.getKey())] = e.getValue();
}
}
@Override
- public final boolean equals(final Object o) {
- if (o == this) {
+ public final boolean equals(final Object obj) {
+ if (obj == this) {
return true;
}
- if (!(o instanceof Map)) {
+ if (!(obj instanceof Map)) {
return false;
}
- if (o instanceof ImmutableOffsetMap) {
- final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
+ if (obj instanceof ImmutableOffsetMap) {
+ final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
// If the offset match, the arrays have to match, too
if (offsets.equals(om.offsets)) {
return Arrays.deepEquals(objects, om.objects);
}
- } else if (o instanceof MutableOffsetMap) {
+ } else if (obj instanceof MutableOffsetMap) {
// Let MutableOffsetMap do the actual work.
- return o.equals(this);
+ return obj.equals(this);
}
- final Map<?, ?> other = (Map<?, ?>)o;
+ final Map<?, ?> other = (Map<?, ?>)obj;
// Size and key sets have to match
if (size() != other.size() || !keySet().equals(other.keySet())) {
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
public final String toString() {
final StringBuilder sb = new StringBuilder("{");
final Iterator<K> it = offsets.keySet().iterator();
- int i = 0;
+ int offset = 0;
while (it.hasNext()) {
sb.append(it.next());
sb.append('=');
- sb.append(objects[i++]);
+ sb.append(objects[offset++]);
if (it.hasNext()) {
sb.append(", ");
* <p>Note: This method may return false to immutable objects which
* immutability is not known, was defined not using concepts term.
*
- * @param o
+ * @param obj
* Reference to check
* @return true if object is known to be immutable false otherwise.
*/
- public static boolean isImmutable(final Object o) {
- Preconditions.checkArgument(o != null,"Object should not be null");
- if (o instanceof Mutable) {
+ public static boolean isImmutable(final Object obj) {
+ Preconditions.checkArgument(obj != null,"Object should not be null");
+ if (obj instanceof Mutable) {
return false;
- } else if (o instanceof Immutable) {
+ } else if (obj instanceof Immutable) {
return true;
- } else if (o instanceof String) {
+ } else if (obj instanceof String) {
return true;
- } else if (KNOWN_IMMUTABLES.contains(o.getClass())) {
+ } else if (KNOWN_IMMUTABLES.contains(obj.getClass())) {
return true;
}
return false;
private class ListenerRegistrationImpl<P extends EventListener> extends AbstractObjectRegistration<P> implements
ListenerRegistration<P> {
- public ListenerRegistrationImpl(final P instance) {
+ ListenerRegistrationImpl(final P instance) {
super(instance);
}
}
private static int getProperty(final String name, final int defaultValue) {
- try {
- final String p = System.getProperty(name);
- if (p != null) {
- try {
- int pi = Integer.valueOf(p);
- if (pi <= 0) {
- LOG.warn("Ignoring illegal value of {}: has to be a positive number", name);
- } else {
- return pi;
- }
- } catch (NumberFormatException e) {
- LOG.warn("Ignoring non-numerical value of {}", name, e);
- }
- }
- } catch (Exception e) {
- LOG.debug("Failed to get {}", name, e);
+ final int val = Integer.getInteger(name, defaultValue).intValue();
+ if (val > 0) {
+ return val;
}
+
+ LOG.warn("Ignoring illegal value of {}: has to be a positive number", name);
return defaultValue;
}
this.needClone = false;
}
- public static <K, V> MutableOffsetMap<K, V> orderedCopyOf(final Map<K, V> m) {
- if (m instanceof Ordered) {
- return ((Ordered<K, V>) m).clone();
+ public static <K, V> MutableOffsetMap<K, V> orderedCopyOf(final Map<K, V> map) {
+ if (map instanceof Ordered) {
+ return ((Ordered<K, V>) map).clone();
}
- if (m instanceof ImmutableOffsetMap) {
- final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) m;
+ if (map instanceof ImmutableOffsetMap) {
+ final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) map;
return new Ordered<>(om.offsets(), om.objects());
}
- return new Ordered<>(m);
+ return new Ordered<>(map);
}
- public static <K, V> MutableOffsetMap<K, V> unorderedCopyOf(final Map<K, V> m) {
- if (m instanceof Unordered) {
- return ((Unordered<K, V>) m).clone();
+ public static <K, V> MutableOffsetMap<K, V> unorderedCopyOf(final Map<K, V> map) {
+ if (map instanceof Unordered) {
+ return ((Unordered<K, V>) map).clone();
}
- if (m instanceof ImmutableOffsetMap) {
- final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) m;
+ if (map instanceof ImmutableOffsetMap) {
+ final ImmutableOffsetMap<K, V> om = (ImmutableOffsetMap<K, V>) map;
return new Unordered<>(om.offsets(), om.objects());
}
- return new Unordered<>(m);
+ return new Unordered<>(map);
}
public static <K, V> MutableOffsetMap<K, V> ordered() {
// Construct the values
@SuppressWarnings("unchecked")
final V[] values = (V[])new Object[keyset.size()];
- int i = 0;
+ int offset = 0;
if (removed != 0) {
if (removed != offsets.size()) {
for (Entry<K, Integer> e : offsets.entrySet()) {
if (o != null && !REMOVED.equals(o)) {
@SuppressWarnings("unchecked")
final V v = (V) o;
- values[i++] = v;
+ values[offset++] = v;
}
}
}
} else {
System.arraycopy(objects, 0, values, 0, offsets.size());
- i = offsets.size();
+ offset = offsets.size();
}
for (V v : newKeys.values()) {
- values[i++] = v;
+ values[offset++] = v;
}
return modifiedMap(keyset, values);
}
@Override
- public final boolean equals(final Object o) {
- if (o == this) {
+ public final boolean equals(final Object obj) {
+ if (obj == this) {
return true;
}
- if (!(o instanceof Map)) {
+ if (!(obj instanceof Map)) {
return false;
}
- if (o instanceof ImmutableOffsetMap) {
- final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) o;
+ if (obj instanceof ImmutableOffsetMap) {
+ final ImmutableOffsetMap<?, ?> om = (ImmutableOffsetMap<?, ?>) obj;
if (newKeys.isEmpty() && offsets.equals(om.offsets())) {
return Arrays.deepEquals(objects, om.objects());
}
- } else if (o instanceof MutableOffsetMap) {
- final MutableOffsetMap<?, ?> om = (MutableOffsetMap<?, ?>) o;
+ } else if (obj instanceof MutableOffsetMap) {
+ final MutableOffsetMap<?, ?> om = (MutableOffsetMap<?, ?>) obj;
if (offsets.equals(om.offsets)) {
return Arrays.deepEquals(objects, om.objects) && newKeys.equals(om.newKeys);
}
// Fall back to brute map compare
- final Map<?, ?> other = (Map<?, ?>)o;
+ final Map<?, ?> other = (Map<?, ?>)obj;
// Size and key sets have to match
if (size() != other.size() || !keySet().equals(other.keySet())) {
// Ensure all objects are present
for (Entry<K, Integer> e : offsets.entrySet()) {
- final Object obj = objects[e.getValue()];
- if (obj != null && !REMOVED.equals(obj) && !obj.equals(other.get(e.getKey()))) {
+ final Object val = objects[e.getValue()];
+ if (val != null && !REMOVED.equals(val) && !val.equals(other.get(e.getKey()))) {
return false;
}
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
if (!(o instanceof Entry)) {
return false;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean add(final Entry<K, V> e) {
Preconditions.checkNotNull(e.getValue());
final V p = MutableOffsetMap.this.put(e.getKey(), e.getValue());
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean remove(final Object o) {
if (!(o instanceof Entry)) {
return false;
return unorderedOffsets(args instanceof Set ? (Set<T>)args : ImmutableSet.copyOf(args));
}
+ @SuppressWarnings("unchecked")
+ private static <T> Map<T, Integer> unorderedOffsets(final Set<T> args) {
+ final Map<T, Integer> existing = (Map<T, Integer>) UNORDERED_CACHE.getIfPresent(args);
+ if (existing != null) {
+ return existing;
+ }
+
+ final Map<T, Integer> newMap = createMap(args);
+ final Map<?, Integer> raced = UNORDERED_CACHE.asMap().putIfAbsent(newMap.keySet(), newMap);
+ return raced == null ? newMap : (Map<T, Integer>)raced;
+ }
+
static <K, V> V[] adjustedArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
Verify.verify(offsets.size() == keys.size(), "Offsets %s do not match keys %s", offsets, keys);
private static <T> Map<T, Integer> createMap(final Collection<T> keys) {
final Builder<T, Integer> b = ImmutableMap.builder();
- int i = 0;
+ int counter = 0;
for (T arg : keys) {
- b.put(arg, i++);
+ b.put(arg, counter++);
}
return b.build();
}
- @SuppressWarnings("unchecked")
- private static <T> Map<T, Integer> unorderedOffsets(final Set<T> args) {
- final Map<T, Integer> existing = (Map<T, Integer>) UNORDERED_CACHE.getIfPresent(args);
- if (existing != null) {
- return existing;
- }
-
- final Map<T, Integer> newMap = createMap(args);
- final Map<?, Integer> raced = UNORDERED_CACHE.asMap().putIfAbsent(newMap.keySet(), newMap);
- return raced == null ? newMap : (Map<T, Integer>)raced;
- }
-
private static <K, V> V[] adjustArray(final Map<K, Integer> offsets, final List<K> keys, final V[] array) {
@SuppressWarnings("unchecked")
final V[] ret = (V[]) Array.newInstance(array.getClass().getComponentType(), array.length);
- int i = 0;
+ int offset = 0;
for (final K k : keys) {
final Integer o = Verify.verifyNotNull(offsets.get(k), "Key %s not present in offsets %s", k, offsets);
- ret[o] = array[i++];
+ ret[o] = array[offset++];
}
return ret;
* @param defaultValue the default value
* @return the System property as an int or the <code>defaultValue</code> if not found.
*/
- public static int getIntSystemProperty( String propName, int defaultValue ) {
+ public static int getIntSystemProperty(String propName, int defaultValue) {
int propValue = defaultValue;
String strValue = System.getProperty(propName);
- if (!Strings.isNullOrEmpty(strValue) && !strValue.trim().isEmpty() ) {
+ if (!Strings.isNullOrEmpty(strValue) && !strValue.trim().isEmpty()) {
try {
propValue = Integer.parseInt(strValue);
} catch (NumberFormatException e) {
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
@Override
- public boolean equals(final Object o) {
- return delegate.equals(o);
+ public boolean equals(final Object obj) {
+ return delegate.equals(obj);
}
@Override
return new Unordered<>(key, value);
}
- public static <K, V> SharedSingletonMap<K, V> orderedCopyOf(final Map<K, V> m) {
- Preconditions.checkArgument(m.size() == 1);
+ public static <K, V> SharedSingletonMap<K, V> orderedCopyOf(final Map<K, V> map) {
+ Preconditions.checkArgument(map.size() == 1);
- final Entry<K, V> e = m.entrySet().iterator().next();
+ final Entry<K, V> e = map.entrySet().iterator().next();
return new Ordered<>(e.getKey(), e.getValue());
}
- public static <K, V> SharedSingletonMap<K, V> unorderedCopyOf(final Map<K, V> m) {
- Preconditions.checkArgument(m.size() == 1);
+ public static <K, V> SharedSingletonMap<K, V> unorderedCopyOf(final Map<K, V> map) {
+ Preconditions.checkArgument(map.size() == 1);
- final Entry<K, V> e = m.entrySet().iterator().next();
+ final Entry<K, V> e = map.entrySet().iterator().next();
return new Unordered<>(e.getKey(), e.getValue());
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final void putAll(@Nonnull final Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 1L;
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
return o == null;
}
}
@Nonnull
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "unchecked", "checkstyle:parameterName" })
@Override
public final <T> T[] toArray(@Nonnull final T[] a) {
if (a.length > 0) {
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean add(final E e) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean containsAll(@Nonnull final Collection<?> c) {
if (c.isEmpty()) {
return true;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean addAll(@Nonnull final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean retainAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean removeAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
return element.equals(o);
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
return delegate.contains(o);
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public <T> T[] toArray(@Nonnull final T[] a) {
return delegate.toArray(a);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean containsAll(@Nonnull final Collection<?> c) {
return delegate.containsAll(c);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean add(final E e) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean addAll(@Nonnull final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean removeAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean retainAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
* @param listenableFutureExecutor the executor used to run listener callbacks asynchronously.
* If null, no executor is used.
*/
- public AsyncNotifyingListeningExecutorService( final ExecutorService delegate,
- @Nullable final Executor listenableFutureExecutor ) {
- this.delegate = Preconditions.checkNotNull( delegate );
+ public AsyncNotifyingListeningExecutorService(final ExecutorService delegate,
+ @Nullable final Executor listenableFutureExecutor) {
+ this.delegate = Preconditions.checkNotNull(delegate);
this.listenableFutureExecutor = listenableFutureExecutor;
}
*
* @param task the Callable to execute
*/
- private <T> AsyncNotifyingListenableFutureTask<T> newFutureTask( final Callable<T> task ) {
- return AsyncNotifyingListenableFutureTask.create( task, listenableFutureExecutor );
+ private <T> AsyncNotifyingListenableFutureTask<T> newFutureTask(final Callable<T> task) {
+ return AsyncNotifyingListenableFutureTask.create(task, listenableFutureExecutor);
}
/**
*
* @param task the Runnable to execute
*/
- private <T> AsyncNotifyingListenableFutureTask<T> newFutureTask( final Runnable task, final T result ) {
- return AsyncNotifyingListenableFutureTask.create( task, result, listenableFutureExecutor );
+ private <T> AsyncNotifyingListenableFutureTask<T> newFutureTask(final Runnable task, final T result) {
+ return AsyncNotifyingListenableFutureTask.create(task, result, listenableFutureExecutor);
}
/**
}
@Override
- public boolean awaitTermination( final long timeout, @Nonnull final TimeUnit unit ) throws InterruptedException {
- return delegate.awaitTermination( timeout, unit );
+ public boolean awaitTermination(final long timeout, @Nonnull final TimeUnit unit) throws InterruptedException {
+ return delegate.awaitTermination(timeout, unit);
}
@Override
}
@Override
- public void execute( @Nonnull final Runnable command ) {
- delegate.execute( command );
+ public void execute(@Nonnull final Runnable command) {
+ delegate.execute(command);
}
@Nonnull
@Override
- public <T> ListenableFuture<T> submit( final Callable<T> task ) {
- AsyncNotifyingListenableFutureTask<T> futureTask = newFutureTask( task );
- delegate.execute( futureTask );
+ public <T> ListenableFuture<T> submit(final Callable<T> task) {
+ AsyncNotifyingListenableFutureTask<T> futureTask = newFutureTask(task);
+ delegate.execute(futureTask);
return futureTask;
}
@Nonnull
@Override
- public ListenableFuture<?> submit( final Runnable task ) {
- AsyncNotifyingListenableFutureTask<Void> futureTask = newFutureTask( task, null );
- delegate.execute( futureTask );
+ public ListenableFuture<?> submit(final Runnable task) {
+ AsyncNotifyingListenableFutureTask<Void> futureTask = newFutureTask(task, null);
+ delegate.execute(futureTask);
return futureTask;
}
@Nonnull
@Override
- public <T> ListenableFuture<T> submit( final Runnable task, final T result ) {
- AsyncNotifyingListenableFutureTask<T> futureTask = newFutureTask( task, result );
- delegate.execute( futureTask );
+ public <T> ListenableFuture<T> submit(final Runnable task, final T result) {
+ AsyncNotifyingListenableFutureTask<T> futureTask = newFutureTask(task, result);
+ delegate.execute(futureTask);
return futureTask;
}
- protected ToStringHelper addToStringAttributes( final ToStringHelper toStringHelper ) {
+ protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper;
}
@Override
public final String toString() {
- return addToStringAttributes( MoreObjects.toStringHelper( this )
- .add( "delegate", delegate ) ).toString();
+ return addToStringAttributes(MoreObjects.toStringHelper(this)
+ .add("delegate", delegate)).toString();
}
}
// been reached, the task will be rejected. We specify a RejectedTaskHandler that tries
// to offer to the backing queue. If that succeeds, the task will execute as soon as a
// thread becomes available. If the offer fails to the backing queue, the task is rejected.
- super( 0, maximumPoolSize, IDLE_TIMEOUT_IN_SEC, TimeUnit.SECONDS,
- new ExecutorQueue( maximumQueueSize ) );
+ super(0, maximumPoolSize, IDLE_TIMEOUT_IN_SEC, TimeUnit.SECONDS,
+ new ExecutorQueue(maximumQueueSize));
- this.threadPrefix = Preconditions.checkNotNull( threadPrefix );
+ this.threadPrefix = Preconditions.checkNotNull(threadPrefix);
this.maximumQueueSize = maximumQueueSize;
- setThreadFactory( new ThreadFactoryBuilder().setDaemon( true )
- .setNameFormat( this.threadPrefix + "-%d" ).build() );
+ setThreadFactory(new ThreadFactoryBuilder().setDaemon(true)
+ .setNameFormat(this.threadPrefix + "-%d").build());
executorQueue = (ExecutorQueue)super.getQueue();
rejectedTaskHandler = new RejectedTaskHandler(
- executorQueue.getBackingQueue(), CountingRejectedExecutionHandler.newAbortPolicy() );
- super.setRejectedExecutionHandler( rejectedTaskHandler );
+ executorQueue.getBackingQueue(), CountingRejectedExecutionHandler.newAbortPolicy());
+ super.setRejectedExecutionHandler(rejectedTaskHandler);
}
@Override
- public void setRejectedExecutionHandler( final RejectedExecutionHandler handler ) {
- Preconditions.checkNotNull( handler );
- rejectedTaskHandler.setDelegateRejectedExecutionHandler( handler );
+ public void setRejectedExecutionHandler(final RejectedExecutionHandler handler) {
+ Preconditions.checkNotNull(handler);
+ rejectedTaskHandler.setDelegateRejectedExecutionHandler(handler);
}
@Override
return ((TrackingLinkedBlockingQueue<?>)executorQueue.getBackingQueue()).getLargestQueueSize();
}
- protected ToStringHelper addToStringAttributes( final ToStringHelper toStringHelper ) {
+ protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper;
}
@Override
public final String toString() {
- return addToStringAttributes( MoreObjects.toStringHelper( this )
- .add( "Thread Prefix", threadPrefix )
- .add( "Current Thread Pool Size", getPoolSize() )
- .add( "Largest Thread Pool Size", getLargestPoolSize() )
- .add( "Max Thread Pool Size", getMaximumPoolSize() )
- .add( "Current Queue Size", executorQueue.getBackingQueue().size() )
- .add( "Largest Queue Size", getLargestQueueSize() )
- .add( "Max Queue Size", maximumQueueSize )
- .add( "Active Thread Count", getActiveCount() )
- .add( "Completed Task Count", getCompletedTaskCount() )
- .add( "Total Task Count", getTaskCount() ) ).toString();
+ return addToStringAttributes(MoreObjects.toStringHelper(this)
+ .add("Thread Prefix", threadPrefix)
+ .add("Current Thread Pool Size", getPoolSize())
+ .add("Largest Thread Pool Size", getLargestPoolSize())
+ .add("Max Thread Pool Size", getMaximumPoolSize())
+ .add("Current Queue Size", executorQueue.getBackingQueue().size())
+ .add("Largest Queue Size", getLargestQueueSize())
+ .add("Max Queue Size", maximumQueueSize)
+ .add("Active Thread Count", getActiveCount())
+ .add("Completed Task Count", getCompletedTaskCount())
+ .add("Total Task Count", getTaskCount())).toString();
}
/**
private final LinkedBlockingQueue<Runnable> backingQueue;
- ExecutorQueue( final int maxBackingQueueSize ) {
- backingQueue = new TrackingLinkedBlockingQueue<>( maxBackingQueueSize );
+ ExecutorQueue(final int maxBackingQueueSize) {
+ backingQueue = new TrackingLinkedBlockingQueue<>(maxBackingQueueSize);
}
LinkedBlockingQueue<Runnable> getBackingQueue() {
}
@Override
- public Runnable poll( final long timeout, final TimeUnit unit ) throws InterruptedException {
- long totalWaitTime = unit.toMillis( timeout );
- long waitTime = Math.min( totalWaitTime, POLL_WAIT_TIME_IN_MS );
+ public Runnable poll(final long timeout, final TimeUnit unit) throws InterruptedException {
+ long totalWaitTime = unit.toMillis(timeout);
+ long waitTime = Math.min(totalWaitTime, POLL_WAIT_TIME_IN_MS);
Runnable task = null;
// We loop here, each time polling the backingQueue first then our queue, instead of
task = backingQueue.poll();
if (task == null) {
// No task in backing - call the base class to wait for one to be offered.
- task = super.poll( waitTime, TimeUnit.MILLISECONDS );
+ task = super.poll(waitTime, TimeUnit.MILLISECONDS);
totalWaitTime -= POLL_WAIT_TIME_IN_MS;
- if (totalWaitTime <= 0 ) {
+ if (totalWaitTime <= 0) {
break;
}
- waitTime = Math.min( totalWaitTime, POLL_WAIT_TIME_IN_MS );
+ waitTime = Math.min(totalWaitTime, POLL_WAIT_TIME_IN_MS);
}
}
private final LinkedBlockingQueue<Runnable> backingQueue;
private volatile RejectedExecutionHandler delegateRejectedExecutionHandler;
- RejectedTaskHandler( final LinkedBlockingQueue<Runnable> backingQueue,
- final RejectedExecutionHandler delegateRejectedExecutionHandler ) {
+ RejectedTaskHandler(final LinkedBlockingQueue<Runnable> backingQueue,
+ final RejectedExecutionHandler delegateRejectedExecutionHandler) {
this.backingQueue = backingQueue;
this.delegateRejectedExecutionHandler = delegateRejectedExecutionHandler;
}
void setDelegateRejectedExecutionHandler(
- final RejectedExecutionHandler delegateRejectedExecutionHandler ) {
+ final RejectedExecutionHandler delegateRejectedExecutionHandler) {
this.delegateRejectedExecutionHandler = delegateRejectedExecutionHandler;
}
}
@Override
- public void rejectedExecution( final Runnable task, final ThreadPoolExecutor executor ) {
+ public void rejectedExecution(final Runnable task, final ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
- throw new RejectedExecutionException( "Executor has been shutdown." );
+ throw new RejectedExecutionException("Executor has been shutdown.");
}
if (!backingQueue.offer(task)) {
- delegateRejectedExecutionHandler.rejectedExecution( task, executor );
+ delegateRejectedExecutionHandler.rejectedExecution(task, executor);
}
}
}
*
* @param delegate the backing RejectedExecutionHandler.
*/
- public CountingRejectedExecutionHandler( final RejectedExecutionHandler delegate ) {
- this.delegate = Preconditions.checkNotNull( delegate );
+ public CountingRejectedExecutionHandler(final RejectedExecutionHandler delegate) {
+ this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
- public void rejectedExecution( final Runnable task, final ThreadPoolExecutor executor ) {
+ public void rejectedExecution(final Runnable task, final ThreadPoolExecutor executor) {
rejectedTaskCounter.increment();
delegate.rejectedExecution(task, executor);
}
*/
public DeadlockDetectingListeningExecutorService(final ExecutorService delegate,
@Nonnull final Supplier<Exception> deadlockExceptionSupplier,
- @Nullable final Executor listenableFutureExecutor ) {
+ @Nullable final Executor listenableFutureExecutor) {
super(delegate, listenableFutureExecutor);
this.deadlockExceptionFunction = Preconditions.checkNotNull(deadlockExceptionSupplier);
}
*
* <p>
* This mapper is intended to be used with
- * {@link com.google.common.util.concurrent.Futures#makeChecked(com.google.common.util.concurrent.ListenableFuture, Function)}
+ * {@link com.google.common.util.concurrent.Futures#makeChecked(
+ * com.google.common.util.concurrent.ListenableFuture, Function)}
* <ul>
* <li>if exception is the specified type or one of its subclasses, it returns
* original exception.
@SuppressWarnings("unchecked")
@Override
- public X apply(final Exception e) {
+ public X apply(final Exception input) {
// If exception is of the specified type,return it.
- if (exceptionType.isAssignableFrom( e.getClass())) {
- return (X) e;
+ if (exceptionType.isAssignableFrom(input.getClass())) {
+ return (X) input;
}
// If exception is ExecutionException whose cause is of the specified
// type, return the cause.
- if (e instanceof ExecutionException && e.getCause() != null) {
- if (exceptionType.isAssignableFrom(e.getCause().getClass())) {
- return (X) e.getCause();
+ if (input instanceof ExecutionException && input.getCause() != null) {
+ if (exceptionType.isAssignableFrom(input.getCause().getClass())) {
+ return (X) input.getCause();
}
- return newWithCause(opName + " execution failed", e.getCause());
+ return newWithCause(opName + " execution failed", input.getCause());
}
// Otherwise return an instance of the specified type with the original
// cause.
- if (e instanceof InterruptedException) {
- return newWithCause(opName + " was interupted.", e);
+ if (input instanceof InterruptedException) {
+ return newWithCause(opName + " was interupted.", input);
}
- if (e instanceof CancellationException ) {
- return newWithCause(opName + " was cancelled.", e);
+ if (input instanceof CancellationException) {
+ return newWithCause(opName + " was cancelled.", input);
}
// We really shouldn't get here but need to cover it anyway for completeness.
- return newWithCause(opName + " encountered an unexpected failure", e);
+ return newWithCause(opName + " encountered an unexpected failure", input);
}
}
* @param threadPrefix
* the name prefix for threads created by this executor.
*/
- public FastThreadPoolExecutor( final int maximumPoolSize, final int maximumQueueSize, final String threadPrefix ) {
- this( maximumPoolSize, maximumQueueSize, DEFAULT_IDLE_TIMEOUT_IN_SEC, TimeUnit.SECONDS,
- threadPrefix );
+ public FastThreadPoolExecutor(final int maximumPoolSize, final int maximumQueueSize, final String threadPrefix) {
+ this(maximumPoolSize, maximumQueueSize, DEFAULT_IDLE_TIMEOUT_IN_SEC, TimeUnit.SECONDS,
+ threadPrefix);
}
/**
* @param threadPrefix
* the name prefix for threads created by this executor.
*/
- public FastThreadPoolExecutor( final int maximumPoolSize, final int maximumQueueSize, final long keepAliveTime,
- final TimeUnit unit, final String threadPrefix ) {
+ public FastThreadPoolExecutor(final int maximumPoolSize, final int maximumQueueSize, final long keepAliveTime,
+ final TimeUnit unit, final String threadPrefix) {
// We use all core threads (the first 2 parameters below equal) so, when a task is submitted,
// if the thread limit hasn't been reached, a new thread will be spawned to execute
// the task even if there is an existing idle thread in the pool. This is faster than
// handing the task to an existing idle thread via the queue. Once the thread limit is
// reached, subsequent tasks will be queued. If the queue is full, tasks will be rejected.
- super( maximumPoolSize, maximumPoolSize, keepAliveTime, unit,
- new TrackingLinkedBlockingQueue<>(maximumQueueSize) );
+ super(maximumPoolSize, maximumPoolSize, keepAliveTime, unit,
+ new TrackingLinkedBlockingQueue<>(maximumQueueSize));
this.threadPrefix = threadPrefix;
this.maximumQueueSize = maximumQueueSize;
- setThreadFactory( new ThreadFactoryBuilder().setDaemon( true )
- .setNameFormat( threadPrefix + "-%d" ).build() );
+ setThreadFactory(new ThreadFactoryBuilder().setDaemon(true)
+ .setNameFormat(threadPrefix + "-%d").build());
if (keepAliveTime > 0) {
// Need to specifically configure core threads to timeout.
- allowCoreThreadTimeOut( true );
+ allowCoreThreadTimeOut(true);
}
- setRejectedExecutionHandler( CountingRejectedExecutionHandler.newAbortPolicy() );
+ setRejectedExecutionHandler(CountingRejectedExecutionHandler.newAbortPolicy());
}
public long getLargestQueueSize() {
return ((TrackingLinkedBlockingQueue<?>)getQueue()).getLargestQueueSize();
}
- protected ToStringHelper addToStringAttributes( final ToStringHelper toStringHelper ) {
+ protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper;
}
@Override
public final String toString() {
- return addToStringAttributes( MoreObjects.toStringHelper( this )
- .add( "Thread Prefix", threadPrefix )
- .add( "Current Thread Pool Size", getPoolSize() )
- .add( "Largest Thread Pool Size", getLargestPoolSize() )
- .add( "Max Thread Pool Size", getMaximumPoolSize() )
- .add( "Current Queue Size", getQueue().size() )
- .add( "Largest Queue Size", getLargestQueueSize() )
- .add( "Max Queue Size", maximumQueueSize )
- .add( "Active Thread Count", getActiveCount() )
- .add( "Completed Task Count", getCompletedTaskCount() )
- .add( "Total Task Count", getTaskCount() ) ).toString();
+ return addToStringAttributes(MoreObjects.toStringHelper(this)
+ .add("Thread Prefix", threadPrefix)
+ .add("Current Thread Pool Size", getPoolSize())
+ .add("Largest Thread Pool Size", getLargestPoolSize())
+ .add("Max Thread Pool Size", getMaximumPoolSize())
+ .add("Current Queue Size", getQueue().size())
+ .add("Largest Queue Size", getLargestQueueSize())
+ .add("Max Queue Size", maximumQueueSize)
+ .add("Active Thread Count", getActiveCount())
+ .add("Completed Task Count", getCompletedTaskCount())
+ .add("Total Task Count", getTaskCount())).toString();
}
}
private final int currentQueueSize;
@ConstructorProperties({ "listenerClassName","currentQueueSize" })
- public ListenerNotificationQueueStats( final String listenerClassName, final int currentQueueSize ) {
+ public ListenerNotificationQueueStats(final String listenerClassName, final int currentQueueSize) {
this.listenerClassName = listenerClassName;
this.currentQueueSize = currentQueueSize;
}
private final Function<Exception, X> mapper;
- private MappingCheckedFuture( final ListenableFuture<V> delegate, final Function<Exception, X> mapper ) {
- super( delegate );
- this.mapper = Preconditions.checkNotNull( mapper );
+ private MappingCheckedFuture(final ListenableFuture<V> delegate, final Function<Exception, X> mapper) {
+ super(delegate);
+ this.mapper = Preconditions.checkNotNull(mapper);
}
/**
* @return a new <code>MappingCheckedFuture</code>
*/
public static <V, X extends Exception> MappingCheckedFuture<V, X> create(
- final ListenableFuture<V> delegate, final Function<Exception, X> mapper ) {
+ final ListenableFuture<V> delegate, final Function<Exception, X> mapper) {
return new MappingCheckedFuture<>(delegate, mapper);
}
@Override
- protected X mapException( @Nonnull final Exception e ) {
- return mapper.apply( e );
+ @SuppressWarnings("checkstyle:parameterName")
+ protected X mapException(@Nonnull final Exception e) {
+ return mapper.apply(e);
}
- private ExecutionException wrapInExecutionException( final String message, final Exception e ) {
- return new ExecutionException( message, mapException( e ) );
+ private ExecutionException wrapInExecutionException(final String message, final Exception ex) {
+ return new ExecutionException(message, mapException(ex));
}
@Override
return super.get();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
- throw wrapInExecutionException( "Operation was interrupted", e );
+ throw wrapInExecutionException("Operation was interrupted", e);
} catch (final CancellationException e) {
- throw wrapInExecutionException( "Operation was cancelled", e );
+ throw wrapInExecutionException("Operation was cancelled", e);
} catch (final ExecutionException e) {
- throw wrapInExecutionException( e.getMessage(), e );
+ throw wrapInExecutionException(e.getMessage(), e);
}
}
@Override
- public V get( final long timeout, @Nonnull final TimeUnit unit )
+ public V get(final long timeout, @Nonnull final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
try {
- return super.get( timeout, unit );
+ return super.get(timeout, unit);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
- throw wrapInExecutionException( "Operation was interrupted", e );
+ throw wrapInExecutionException("Operation was interrupted", e);
} catch (final CancellationException e) {
- throw wrapInExecutionException( "Operation was cancelled", e );
+ throw wrapInExecutionException("Operation was cancelled", e);
} catch (final ExecutionException e) {
- throw wrapInExecutionException( e.getMessage(), e );
+ throw wrapInExecutionException(e.getMessage(), e);
}
}
}
* @deprecated Use {@link #create(Executor, BatchedInvoker, int, String)} instead.
*/
@Deprecated
+ @SuppressWarnings("checkstyle:illegalCatch")
public QueuedNotificationManager(final Executor executor, final Invoker<L, N> listenerInvoker,
final int maxQueueCapacity, final String name) {
- this(executor, (BatchedInvoker<L, N>)(l, c) -> c.forEach(n -> {
+ this(executor, (BatchedInvoker<L, N>)(listener, notifications) -> notifications.forEach(n -> {
try {
- listenerInvoker.invokeListener(l, n);
+ listenerInvoker.invokeListener(listener, n);
} catch (Exception e) {
- LOG.error("{}: Error notifying listener {} with {}", name, l, n, e);
+ LOG.error("{}: Error notifying listener {} with {}", name, listener, n, e);
}
}), maxQueueCapacity, name);
if (obj == this) {
return true;
}
- return (obj instanceof ListenerKey<?>) && listener == ((ListenerKey<?>) obj).listener;
+ return obj instanceof ListenerKey<?> && listener == ((ListenerKey<?>) obj).listener;
}
@Override
}
}
+ @SuppressWarnings("checkstyle:illegalCatch")
private void invokeListener(final Collection<N> notifications) {
LOG.debug("{}: Invoking listener {} with notification: {}", name, listenerKey, notifications);
try {
protected X newWithCause(final String message, final Throwable cause) {
try {
return ctor.newInstance(message, cause);
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
+ | InvocationTargetException e) {
throw new IllegalStateException("Failed to instantiate exception " + ctor.getDeclaringClass(), e);
}
}
* the name prefix for threads created by this executor.
* @return a new ExecutorService with the specified configuration.
*/
- public static ExecutorService newBoundedFastThreadPool( int maximumPoolSize,
- int maximumQueueSize, String threadPrefix ) {
- return new FastThreadPoolExecutor( maximumPoolSize, maximumQueueSize, threadPrefix );
+ public static ExecutorService newBoundedFastThreadPool(int maximumPoolSize,
+ int maximumQueueSize, String threadPrefix) {
+ return new FastThreadPoolExecutor(maximumPoolSize, maximumQueueSize, threadPrefix);
}
/**
* the name prefix for threads created by this executor.
* @return a new ExecutorService with the specified configuration.
*/
- public static ExecutorService newBlockingBoundedFastThreadPool( int maximumPoolSize,
- int maximumQueueSize, String threadPrefix ) {
+ public static ExecutorService newBlockingBoundedFastThreadPool(int maximumPoolSize,
+ int maximumQueueSize, String threadPrefix) {
FastThreadPoolExecutor executor =
- new FastThreadPoolExecutor( maximumPoolSize, maximumQueueSize, threadPrefix );
- executor.setRejectedExecutionHandler( CountingRejectedExecutionHandler.newCallerRunsPolicy() );
+ new FastThreadPoolExecutor(maximumPoolSize, maximumQueueSize, threadPrefix);
+ executor.setRejectedExecutionHandler(CountingRejectedExecutionHandler.newCallerRunsPolicy());
return executor;
}
* the name prefix for threads created by this executor.
* @return a new ExecutorService with the specified configuration.
*/
- public static ExecutorService newBoundedCachedThreadPool( int maximumPoolSize,
- int maximumQueueSize, String threadPrefix ) {
- return new CachedThreadPoolExecutor( maximumPoolSize, maximumQueueSize, threadPrefix );
+ public static ExecutorService newBoundedCachedThreadPool(int maximumPoolSize,
+ int maximumQueueSize, String threadPrefix) {
+ return new CachedThreadPoolExecutor(maximumPoolSize, maximumQueueSize, threadPrefix);
}
/**
* the name prefix for threads created by this executor.
* @return a new ExecutorService with the specified configuration.
*/
- public static ExecutorService newBlockingBoundedCachedThreadPool( int maximumPoolSize,
- int maximumQueueSize, String threadPrefix ) {
+ public static ExecutorService newBlockingBoundedCachedThreadPool(int maximumPoolSize,
+ int maximumQueueSize, String threadPrefix) {
CachedThreadPoolExecutor executor =
- new CachedThreadPoolExecutor( maximumPoolSize, maximumQueueSize, threadPrefix );
- executor.setRejectedExecutionHandler( CountingRejectedExecutionHandler.newCallerRunsPolicy() );
+ new CachedThreadPoolExecutor(maximumPoolSize, maximumQueueSize, threadPrefix);
+ executor.setRejectedExecutionHandler(CountingRejectedExecutionHandler.newCallerRunsPolicy());
return executor;
}
* the name prefix for the thread created by this executor.
* @return a new ExecutorService with the specified configuration.
*/
- public static ExecutorService newBoundedSingleThreadExecutor( int maximumQueueSize,
- String threadPrefix ) {
- return new FastThreadPoolExecutor( 1, maximumQueueSize, Long.MAX_VALUE, TimeUnit.SECONDS,
- threadPrefix );
+ public static ExecutorService newBoundedSingleThreadExecutor(int maximumQueueSize,
+ String threadPrefix) {
+ return new FastThreadPoolExecutor(1, maximumQueueSize, Long.MAX_VALUE, TimeUnit.SECONDS,
+ threadPrefix);
}
}
private volatile int largestQueueSize = 0;
/**
- * @see LinkedBlockingQueue#LinkedBlockingQueue
+ * See {@link LinkedBlockingQueue#LinkedBlockingQueue()}.
*/
public TrackingLinkedBlockingQueue() {
super();
}
/**
- * @see LinkedBlockingQueue#LinkedBlockingQueue(Collection)
+ * See {@link LinkedBlockingQueue#LinkedBlockingQueue(Collection)}.
*/
- public TrackingLinkedBlockingQueue( final Collection<? extends E> c ) {
+ @SuppressWarnings("checkstyle:parameterName")
+ public TrackingLinkedBlockingQueue(final Collection<? extends E> c) {
super(c);
}
/**
- * @see LinkedBlockingQueue#LinkedBlockingQueue(int)
+ * See {@link LinkedBlockingQueue#LinkedBlockingQueue(int)}.
*/
- public TrackingLinkedBlockingQueue( final int capacity ) {
+ public TrackingLinkedBlockingQueue(final int capacity) {
super(capacity);
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
- if (super.offer( e, timeout, unit ) ) {
+ if (super.offer(e, timeout, unit)) {
updateLargestQueueSize();
return true;
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean offer(@Nonnull final E e) {
- if (super.offer( e ) ) {
+ if (super.offer(e)) {
updateLargestQueueSize();
return true;
}
}
@Override
- public void put( final E e ) throws InterruptedException {
- super.put( e );
+ @SuppressWarnings("checkstyle:parameterName")
+ public void put(final E e) throws InterruptedException {
+ super.put(e);
updateLargestQueueSize();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean add(final E e) {
- boolean result = super.add( e );
+ boolean result = super.add(e);
updateLargestQueueSize();
return result;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean addAll(final Collection<? extends E> c) {
try {
- return super.addAll( c );
+ return super.addAll(c);
} finally {
updateLargestQueueSize();
}
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
/**
* Set of utility methods for instantiating parser that deal with untrusted XML sources.
@Beta
public final class UntrustedXML {
private static final DocumentBuilderFactory DBF;
+
static {
final DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setCoalescing(true);
}
private static final SAXParserFactory SPF;
+
static {
final SAXParserFactory f = SAXParserFactory.newInstance();
f.setNamespaceAware(true);
f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
f.setFeature("http://xml.org/sax/features/external-general-entities", false);
f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- } catch (final Exception e) {
+ } catch (final SAXNotRecognizedException | SAXNotSupportedException | ParserConfigurationException e) {
throw new ExceptionInInitializerError(e);
}
}
private static final XMLInputFactory XIF;
+
static {
final XMLInputFactory f = XMLInputFactory.newInstance();
assertFalse(c.contains(""));
assertFalse(c.contains(1));
- assertTrue(c.containsAll(Collections.<String>emptyList()));
+ assertTrue(c.containsAll(Collections.emptyList()));
assertFalse(c.containsAll(Collections.singleton("")));
assertFalse(c.containsAll(Collections.singleton(1)));
}
package org.opendaylight.yangtools.util;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import org.junit.Test;
}
private static void verifyDisplayableString(final String name, final String actual, final String expPrefix) {
- assertEquals(name + " starts with " + expPrefix + ". Actual: " + actual,
- true, actual.startsWith(expPrefix));
+ assertTrue(name + " starts with " + expPrefix + ". Actual: " + actual,
+ actual.startsWith(expPrefix));
}
}
@Test
public void nullEqualsNull() {
- assertTrue(EvenMoreObjects.equalsHelper(null, null, (one, another) -> true));
+ assertTrue(EvenMoreObjects.equalsHelper(null, null, (one, another) -> Boolean.TRUE));
}
private static class Thing {
-
String name;
Integer age;
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
return EvenMoreObjects.equalsHelper(this, obj,
(one, another) -> Objects.equals(one.name, another.name) && Objects.equals(one.age, another.age));
}
return MoreObjects.toStringHelper(this).add("name", name).add("age", age).toString();
}
- Thing(String name, Integer age) {
+ Thing(final String name, final Integer age) {
super();
this.name = name;
this.age = age;
}
-
}
-
}
@Test
public void testAllMethodsOfHashCodeBuilder() {
- final HashCodeBuilder<String> hashCodeBuilder = new HashCodeBuilder<>();
- assertEquals("Default hash code should be '1'.", 1, hashCodeBuilder.build().intValue());
+ final HashCodeBuilder<String> builder = new HashCodeBuilder<>();
+ assertEquals("Default hash code should be '1'.", 1, builder.build().intValue());
int nextHashCode = HashCodeBuilder.nextHashCode(1, "test");
assertEquals("Next hash code should be '3556529'.", 3556529, nextHashCode);
- hashCodeBuilder.addArgument("another test");
- assertEquals("Updated internal hash code should be '700442706'.", -700442706, hashCodeBuilder.build().intValue());
+ builder.addArgument("another test");
+ assertEquals("Updated internal hash code should be '700442706'.", -700442706, builder.build().intValue());
}
}
private TestEventListener testEventListener;
private ExtendedTestEventListener extendedTestEventListener;
- private ListenerRegistry<TestEventListener> listenerRegistry;
+ private ListenerRegistry<TestEventListener> registry;
@Rule
public ExpectedException expException = ExpectedException.none();
public void init() {
testEventListener = new TestEventListener() {};
extendedTestEventListener = new ExtendedTestEventListener() {};
- listenerRegistry = new ListenerRegistry<>();
+ registry = new ListenerRegistry<>();
}
@Test
public void testCreateNewInstance() {
- assertNotNull("Intance of listener registry shouldn't be null.", listenerRegistry);
+ assertNotNull("Intance of listener registry shouldn't be null.", registry);
}
@Test
public void tetGetListenersMethod() {
- assertTrue("Listener regisdtry should have any listeners.", Iterables.isEmpty(listenerRegistry.getListeners()));
+ assertTrue("Listener registry should have any listeners.", Iterables.isEmpty(registry.getListeners()));
}
@Test
public void testRegisterMethod() {
- final ListenerRegistration<TestEventListener> listenerRegistration = listenerRegistry.register(testEventListener);
+ final ListenerRegistration<TestEventListener> listenerRegistration = registry.register(testEventListener);
assertEquals("Listeners should be the same.", testEventListener, listenerRegistration.getInstance());
expException.expect(IllegalArgumentException.class);
expException.expectMessage("Listener should not be null.");
- listenerRegistry.register(null);
+ registry.register(null);
}
@Test
public void testRegisterWithType() {
- final ListenerRegistration<ExtendedTestEventListener> listenerRegistration = listenerRegistry.registerWithType(extendedTestEventListener);
+ final ListenerRegistration<ExtendedTestEventListener> listenerRegistration = registry.registerWithType(
+ extendedTestEventListener);
assertEquals("Listeners should be the same.", extendedTestEventListener, listenerRegistration.getInstance());
}
@Test
public void testIteratorMethod() {
- final Iterator<ListenerRegistration<TestEventListener>> listenerIterator = listenerRegistry.iterator();
+ final Iterator<ListenerRegistration<TestEventListener>> listenerIterator = registry.iterator();
assertNotNull("Listener iterator shouldn't be null.", listenerIterator);
}
@Test
public void testCreateMethod() {
- final ListenerRegistry<EventListener> emptyListenerRegistry = ListenerRegistry.create();
- assertTrue("List of listeners in listener registry should be empty.", Iterables.isEmpty(emptyListenerRegistry.getListeners()));
+ final ListenerRegistry<EventListener> emptyRegistry = ListenerRegistry.create();
+ assertTrue("List of listeners in listener registry should be empty.",
+ Iterables.isEmpty(emptyRegistry.getListeners()));
}
interface TestEventListener extends EventListener {
final Collection<String> trieMapValues = readWriteTrieMap.values();
assertEquals("Size of values should be '3'.", 3, trieMapValues.size());
- assertTrue("Entry set of readWriteTrieMap and trieMap should by equals.", convertSetEntryToMap(readWriteTrieMap.entrySet()).equals(trieMap));
+ assertTrue("Entry set of readWriteTrieMap and trieMap should by equals.",
+ convertSetEntryToMap(readWriteTrieMap.entrySet()).equals(trieMap));
trieMap.put("2", "two");
final ReadWriteTrieMap<String, String> readWriteTrieMap2 = new ReadWriteTrieMap<>(trieMap, 4);
- assertFalse("Objects readWriteTrieMap and readOnlyTrieMap2 should be different.", readWriteTrieMap.equals(readWriteTrieMap2));
- assertFalse("Hash codes of object readWriteTrieMap and readOnelyTrieMap2 should be different.", readWriteTrieMap.hashCode() == readWriteTrieMap2.hashCode());
+ assertFalse("Objects readWriteTrieMap and readOnlyTrieMap2 should be different.",
+ readWriteTrieMap.equals(readWriteTrieMap2));
+ assertFalse("Hash codes of object readWriteTrieMap and readOnelyTrieMap2 should be different.",
+ readWriteTrieMap.hashCode() == readWriteTrieMap2.hashCode());
final Map<String, String> readOnlyTrieMap = readWriteTrieMap.toReadOnly();
readWriteTrieMap.clear();
assertEquals("Size of readOnlyTrieMap should be '6'.", 6, readOnlyTrieMap.size());
}
- public Map<String, String> convertSetEntryToMap(Set<Entry<String, String>> input) {
+ public Map<String, String> convertSetEntryToMap(final Set<Entry<String, String>> input) {
Map<String, String> resultMap = new HashMap<>();
for (Entry<String, String> entry : input) {
resultMap.put(entry.getKey(), entry.getValue());
assertTrue(m.equals(t));
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testEmptyOrderedCopyOf() {
SharedSingletonMap.orderedCopyOf(ImmutableMap.of());
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testEmptyUnorderedCopyOf() {
SharedSingletonMap.unorderedCopyOf(ImmutableMap.of());
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testClear() {
create().clear();
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testPut() {
create().put(null, null);
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testPutAll() {
create().putAll(Collections.singletonMap("", ""));
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRemove() {
create().remove(null);
}
assertFalse(it.hasNext());
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRejectedAdd() {
final SingletonSet<?> s = nullSet();
s.add(null);
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRejectedAddAll() {
final SingletonSet<?> s = nullSet();
s.addAll(null);
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRejectedClear() {
final SingletonSet<?> s = nullSet();
s.clear();
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRejectedRemove() {
final SingletonSet<?> s = nullSet();
s.remove(null);
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRejectedRemoveAll() {
final SingletonSet<?> s = nullSet();
s.removeAll(null);
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testRejectedRetainAll() {
final SingletonSet<?> s = nullSet();
s.retainAll(null);
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.opendaylight.yangtools.util.concurrent.CommonTestUtils.SUBMIT_RUNNABLE;
import static org.opendaylight.yangtools.util.concurrent.CommonTestUtils.SUBMIT_RUNNABLE_WITH_RESULT;
-import com.google.common.collect.Lists;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@After
public void tearDown() {
- if (listenerExecutor != null ) {
+ if (listenerExecutor != null) {
listenerExecutor.shutdownNow();
}
- if (testExecutor != null ) {
+ if (testExecutor != null) {
testExecutor.shutdownNow();
}
}
public void testListenerCallbackWithExecutor() throws InterruptedException {
String listenerThreadPrefix = "ListenerThread";
- listenerExecutor = Executors.newFixedThreadPool( 3,
- new ThreadFactoryBuilder().setNameFormat( listenerThreadPrefix + "-%d" ).build() );
+ listenerExecutor = Executors.newFixedThreadPool(3,
+ new ThreadFactoryBuilder().setNameFormat(listenerThreadPrefix + "-%d").build());
testExecutor = new AsyncNotifyingListeningExecutorService(
Executors.newSingleThreadExecutor(
- new ThreadFactoryBuilder().setNameFormat( "SingleThread" ).build() ),
- listenerExecutor );
+ new ThreadFactoryBuilder().setNameFormat("SingleThread").build()),
+ listenerExecutor);
- testListenerCallback( testExecutor, SUBMIT_CALLABLE, listenerThreadPrefix );
- testListenerCallback( testExecutor, SUBMIT_RUNNABLE, listenerThreadPrefix );
- testListenerCallback( testExecutor, SUBMIT_RUNNABLE_WITH_RESULT, listenerThreadPrefix );
+ testListenerCallback(testExecutor, SUBMIT_CALLABLE, listenerThreadPrefix);
+ testListenerCallback(testExecutor, SUBMIT_RUNNABLE, listenerThreadPrefix);
+ testListenerCallback(testExecutor, SUBMIT_RUNNABLE_WITH_RESULT, listenerThreadPrefix);
}
@Test
String listenerThreadPrefix = "SingleThread";
testExecutor = new AsyncNotifyingListeningExecutorService(
Executors.newSingleThreadExecutor(
- new ThreadFactoryBuilder().setNameFormat( listenerThreadPrefix ).build() ),
- null );
+ new ThreadFactoryBuilder().setNameFormat(listenerThreadPrefix).build()),
+ null);
- testListenerCallback( testExecutor, SUBMIT_CALLABLE, listenerThreadPrefix );
- testListenerCallback( testExecutor, SUBMIT_RUNNABLE, listenerThreadPrefix );
- testListenerCallback( testExecutor, SUBMIT_RUNNABLE_WITH_RESULT, listenerThreadPrefix );
+ testListenerCallback(testExecutor, SUBMIT_CALLABLE, listenerThreadPrefix);
+ testListenerCallback(testExecutor, SUBMIT_RUNNABLE, listenerThreadPrefix);
+ testListenerCallback(testExecutor, SUBMIT_RUNNABLE_WITH_RESULT, listenerThreadPrefix);
}
- static void testListenerCallback( AsyncNotifyingListeningExecutorService executor,
- Invoker invoker, final String expListenerThreadPrefix ) throws InterruptedException {
+ static void testListenerCallback(final AsyncNotifyingListeningExecutorService executor,
+ final Invoker invoker, final String expListenerThreadPrefix) throws InterruptedException {
AtomicReference<AssertionError> assertError = new AtomicReference<>();
- CountDownLatch futureNotifiedLatch = new CountDownLatch( 1 );
- CountDownLatch blockTaskLatch = new CountDownLatch( 1 );
+ CountDownLatch futureNotifiedLatch = new CountDownLatch(1);
+ CountDownLatch blockTaskLatch = new CountDownLatch(1);
// The blockTaskLatch is used to block the task from completing until we've added
// our listener to the Future. Otherwise, if the task completes quickly and the Future is
// will immediately notify synchronously on this thread as Futures#addCallback defaults to
// a same thread executor. This would erroneously fail the test.
- ListenableFuture<?> future = invoker.invokeExecutor( executor, blockTaskLatch );
- addCallback( future, futureNotifiedLatch, expListenerThreadPrefix, assertError );
+ ListenableFuture<?> future = invoker.invokeExecutor(executor, blockTaskLatch);
+ addCallback(future, futureNotifiedLatch, expListenerThreadPrefix, assertError);
// Now that we've added our listener, signal the latch to let the task complete.
blockTaskLatch.countDown();
- assertTrue( "ListenableFuture callback was not notified of onSuccess",
- futureNotifiedLatch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("ListenableFuture callback was not notified of onSuccess",
+ futureNotifiedLatch.await(5, TimeUnit.SECONDS));
- if (assertError.get() != null ) {
+ if (assertError.get() != null) {
throw assertError.get();
}
// Add another listener - since the Future is already complete, we expect the listener to be
// notified inline on this thread when it's added.
- futureNotifiedLatch = new CountDownLatch( 1 );
- addCallback( future, futureNotifiedLatch, Thread.currentThread().getName(), assertError );
+ futureNotifiedLatch = new CountDownLatch(1);
+ addCallback(future, futureNotifiedLatch, Thread.currentThread().getName(), assertError);
- assertTrue( "ListenableFuture callback was not notified of onSuccess",
- futureNotifiedLatch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("ListenableFuture callback was not notified of onSuccess",
+ futureNotifiedLatch.await(5, TimeUnit.SECONDS));
- if (assertError.get() != null ) {
+ if (assertError.get() != null) {
throw assertError.get();
}
}
- static void addCallback( ListenableFuture<?> future,
- final CountDownLatch futureNotifiedLatch,
- final String expListenerThreadPrefix,
- final AtomicReference<AssertionError> assertError ) {
+ static void addCallback(final ListenableFuture<?> future, final CountDownLatch futureNotifiedLatch,
+ final String expListenerThreadPrefix, final AtomicReference<AssertionError> assertError) {
- Futures.addCallback( future, new FutureCallback<Object>() {
+ Futures.addCallback(future, new FutureCallback<Object>() {
@Override
- public void onSuccess( Object result ) {
-
+ public void onSuccess(final Object result) {
try {
String theadName = Thread.currentThread().getName();
- assertTrue( "ListenableFuture callback was not notified on the listener executor."
- + " Expected thread name prefix \"" + expListenerThreadPrefix +
- "\". Actual thread name \"" + theadName + "\"",
- theadName.startsWith( expListenerThreadPrefix ) );
- } catch( AssertionError e ) {
- assertError.set( e );
+ assertTrue("ListenableFuture callback was not notified on the listener executor."
+ + " Expected thread name prefix \"" + expListenerThreadPrefix
+ + "\". Actual thread name \"" + theadName + "\"",
+ theadName.startsWith(expListenerThreadPrefix));
+ } catch (AssertionError e) {
+ assertError.set(e);
} finally {
futureNotifiedLatch.countDown();
}
}
@Override
- public void onFailure( @Nonnull Throwable t ) {
+ @SuppressWarnings("checkstyle:parameterName")
+ public void onFailure(@Nonnull final Throwable t) {
// Shouldn't happen
- t.printStackTrace();
+ fail("Unexpected failure " + t);
}
- } );
+ });
}
@Test
public void testDelegatedMethods() throws InterruptedException {
- Runnable task = () -> {
- };
+ Runnable task = () -> { };
- List<Runnable> taskList = Lists.newArrayList();
+ List<Runnable> taskList = new ArrayList<>();
- ExecutorService mockDelegate = mock( ExecutorService.class );
- doNothing().when( mockDelegate ).execute( task );
- doNothing().when( mockDelegate ).shutdown();
- doReturn( taskList ).when( mockDelegate ).shutdownNow();
- doReturn( true ).when( mockDelegate ).awaitTermination( 3, TimeUnit.SECONDS );
- doReturn( true ).when( mockDelegate ).isShutdown();
- doReturn( true ).when( mockDelegate ).isTerminated();
+ ExecutorService mockDelegate = mock(ExecutorService.class);
+ doNothing().when(mockDelegate).execute(task);
+ doNothing().when(mockDelegate).shutdown();
+ doReturn(taskList).when(mockDelegate).shutdownNow();
+ doReturn(Boolean.TRUE).when(mockDelegate).awaitTermination(3, TimeUnit.SECONDS);
+ doReturn(Boolean.TRUE).when(mockDelegate).isShutdown();
+ doReturn(Boolean.TRUE).when(mockDelegate).isTerminated();
AsyncNotifyingListeningExecutorService executor = new AsyncNotifyingListeningExecutorService(
- mockDelegate, null );
+ mockDelegate, null);
- executor.execute( task );
+ executor.execute(task);
executor.shutdown();
- assertEquals( "awaitTermination", true, executor.awaitTermination( 3, TimeUnit.SECONDS ) );
- assertSame( "shutdownNow", taskList, executor.shutdownNow() );
- assertEquals( "isShutdown", true, executor.isShutdown() );
- assertEquals( "isTerminated", true, executor.isTerminated() );
-
- verify( mockDelegate ).execute( task );
- verify( mockDelegate ).shutdown();
- verify( mockDelegate ).awaitTermination( 3, TimeUnit.SECONDS );
- verify( mockDelegate ).shutdownNow();
- verify( mockDelegate ).isShutdown();
- verify( mockDelegate ).isTerminated();
+ assertTrue("awaitTermination", executor.awaitTermination(3, TimeUnit.SECONDS));
+ assertSame("shutdownNow", taskList, executor.shutdownNow());
+ assertTrue("isShutdown", executor.isShutdown());
+ assertTrue("isTerminated", executor.isTerminated());
+
+ verify(mockDelegate).execute(task);
+ verify(mockDelegate).shutdown();
+ verify(mockDelegate).awaitTermination(3, TimeUnit.SECONDS);
+ verify(mockDelegate).shutdownNow();
+ verify(mockDelegate).isShutdown();
+ verify(mockDelegate).isTerminated();
}
}
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.Uninterruptibles;
-import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
/**
* @author Thomas Pantelis
*/
public class CommonTestUtils {
-
+ @FunctionalInterface
public interface Invoker {
- ListenableFuture<?> invokeExecutor( ListeningExecutorService executor,
- CountDownLatch blockingLatch );
+ ListenableFuture<?> invokeExecutor(ListeningExecutorService executor, CountDownLatch blockingLatch);
}
- public static final Invoker SUBMIT_CALLABLE = (executor, blockingLatch) -> executor.submit(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- if (blockingLatch != null ) {
- Uninterruptibles.awaitUninterruptibly( blockingLatch );
- }
- return null;
+ public static final Invoker SUBMIT_CALLABLE = (executor, blockingLatch) -> executor.submit(() -> {
+ if (blockingLatch != null) {
+ Uninterruptibles.awaitUninterruptibly(blockingLatch);
}
- } );
+ return null;
+ });
public static final Invoker SUBMIT_RUNNABLE = (executor, blockingLatch) -> executor.submit(() -> {
- if (blockingLatch != null ) {
- Uninterruptibles.awaitUninterruptibly( blockingLatch );
+ if (blockingLatch != null) {
+ Uninterruptibles.awaitUninterruptibly(blockingLatch);
}
});
public static final Invoker SUBMIT_RUNNABLE_WITH_RESULT = (executor, blockingLatch) -> executor.submit(() -> {
- if (blockingLatch != null ) {
- Uninterruptibles.awaitUninterruptibly( blockingLatch );
+ if (blockingLatch != null) {
+ Uninterruptibles.awaitUninterruptibly(blockingLatch);
}
- }, "foo" );
+ }, "foo");
}
package org.opendaylight.yangtools.util.concurrent;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.CountDownLatch;
@Test
public void testCallerRunsPolicyHandler() throws InterruptedException {
- int nTasks = 5;
- CountDownLatch tasksRunLatch = new CountDownLatch( 1 );
- CountDownLatch blockLatch = new CountDownLatch( 1 );
+ CountDownLatch tasksRunLatch = new CountDownLatch(1);
+ CountDownLatch blockLatch = new CountDownLatch(1);
- executor = new ThreadPoolExecutor( 1, 1, 0, TimeUnit.SECONDS,
- ExecutorServiceUtil.offerFailingBlockingQueue(new LinkedBlockingQueue<>() ) );
+ executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
+ ExecutorServiceUtil.offerFailingBlockingQueue(new LinkedBlockingQueue<>()));
- CountingRejectedExecutionHandler countingHandler =
- CountingRejectedExecutionHandler.newCallerRunsPolicy();
- executor.setRejectedExecutionHandler( countingHandler );
+ CountingRejectedExecutionHandler countingHandler = CountingRejectedExecutionHandler.newCallerRunsPolicy();
+ executor.setRejectedExecutionHandler(countingHandler);
- executor.execute( new Task( tasksRunLatch, blockLatch ) );
+ executor.execute(new Task(tasksRunLatch, blockLatch));
- for (int i = 0; i < nTasks - 1; i++) {
- executor.execute( new Task( null, null, null, null, 0 ) );
+ int tasks = 5;
+ for (int i = 0; i < tasks - 1; i++) {
+ executor.execute(new Task(null, null, null, null, 0));
}
- assertEquals( "getRejectedTaskCount", nTasks - 1, countingHandler.getRejectedTaskCount() );
+ assertEquals("getRejectedTaskCount", tasks - 1, countingHandler.getRejectedTaskCount());
blockLatch.countDown();
- assertEquals( "Tasks complete", true, tasksRunLatch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("Tasks complete", tasksRunLatch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortPolicyHandler() throws InterruptedException {
- int nTasks = 5;
- CountDownLatch tasksRunLatch = new CountDownLatch( 1 );
- CountDownLatch blockLatch = new CountDownLatch( 1 );
+ CountDownLatch tasksRunLatch = new CountDownLatch(1);
+ CountDownLatch blockLatch = new CountDownLatch(1);
- executor = new ThreadPoolExecutor( 1, 1, 0, TimeUnit.SECONDS,
- ExecutorServiceUtil.offerFailingBlockingQueue(new LinkedBlockingQueue<>() ) );
+ executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
+ ExecutorServiceUtil.offerFailingBlockingQueue(new LinkedBlockingQueue<>()));
- CountingRejectedExecutionHandler countingHandler =
- CountingRejectedExecutionHandler.newAbortPolicy();
- executor.setRejectedExecutionHandler( countingHandler );
+ CountingRejectedExecutionHandler countingHandler = CountingRejectedExecutionHandler.newAbortPolicy();
+ executor.setRejectedExecutionHandler(countingHandler);
- executor.execute( new Task( tasksRunLatch, blockLatch ) );
+ executor.execute(new Task(tasksRunLatch, blockLatch));
- for (int i = 0; i < nTasks - 1; i++) {
+ int tasks = 5;
+ for (int i = 0; i < tasks - 1; i++) {
try {
- executor.execute( new Task( null, null, null, null, 0 ) );
- fail( "Expected RejectedExecutionException" );
- } catch( RejectedExecutionException e ) {
+ executor.execute(new Task(null, null, null, null, 0));
+ fail("Expected RejectedExecutionException");
+ } catch (RejectedExecutionException e) {
// Expected
}
}
- assertEquals( "getRejectedTaskCount", nTasks - 1, countingHandler.getRejectedTaskCount() );
+ assertEquals("getRejectedTaskCount", tasks - 1, countingHandler.getRejectedTaskCount());
blockLatch.countDown();
- assertEquals( "Tasks complete", true, tasksRunLatch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("Tasks complete", tasksRunLatch.await(5, TimeUnit.SECONDS));
}
}
ListenableFuture<String> future = executor.submit(() -> "foo");
- assertEquals( "Future result", "foo", future.get( 5, TimeUnit.SECONDS));
+ assertEquals("Future result", "foo", future.get(5, TimeUnit.SECONDS));
// Test submit with Runnable.
- executor.submit(() -> {
- }).get();
+ executor.submit(() -> { }).get();
// Test submit with Runnable and value.
}
@Test
+ @SuppressWarnings("checkstyle:illegalThrows")
public void testNonBlockingSubmitOnExecutorThread() throws Throwable {
executor = newExecutor();
testNonBlockingSubmitOnExecutorThread(EXECUTE, SUBMIT_CALLABLE);
}
+ @SuppressWarnings("checkstyle:illegalThrows")
void testNonBlockingSubmitOnExecutorThread(final InitialInvoker initialInvoker, final Invoker invoker)
throws Throwable {
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public void onFailure(@Nonnull final Throwable t) {
caughtEx.set(t);
futureCompletedLatch.countDown();
}
@Test
- public void testBlockingSubmitOnExecutorThread() throws Exception {
+ public void testBlockingSubmitOnExecutorThread() throws InterruptedException {
executor = newExecutor();
testBlockingSubmitOnExecutorThread(EXECUTE, SUBMIT_CALLABLE);
}
+ @SuppressWarnings("checkstyle:illegalCatch")
void testBlockingSubmitOnExecutorThread(final InitialInvoker initialInvoker, final Invoker invoker)
- throws Exception {
+ throws InterruptedException {
final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
try {
invoker.invokeExecutor(executor, null).get();
- } catch(ExecutionException e) {
+ } catch (ExecutionException e) {
caughtEx.set(e.getCause());
- } catch(Throwable e) {
+ } catch (Throwable e) {
caughtEx.set(e);
} finally {
latch.countDown();
initialInvoker.invokeExecutor(executor, task);
- assertTrue("Task did not complete - executor likely deadlocked", latch.await( 5, TimeUnit.SECONDS));
+ assertTrue("Task did not complete - executor likely deadlocked", latch.await(5, TimeUnit.SECONDS));
assertNotNull("Expected exception thrown", caughtEx.get());
assertEquals("Caught exception type", TestDeadlockException.class, caughtEx.get().getClass());
}
package org.opendaylight.yangtools.util.concurrent;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.util.concurrent.CheckedFuture;
public class MappingCheckedFutureTest {
interface FutureInvoker {
- void invokeGet( CheckedFuture<?,?> future ) throws Exception;
- Throwable extractWrappedTestEx( Exception from );
+ void invokeGet(CheckedFuture<?,?> future) throws Exception;
+
+ Throwable extractWrappedTestEx(Exception from);
}
- @SuppressWarnings("serial")
static class TestException extends Exception {
- TestException( final String message, final Throwable cause ) {
- super( message, cause );
+ private static final long serialVersionUID = 1L;
+
+ TestException(final String message, final Throwable cause) {
+ super(message, cause);
}
}
- static final ExceptionMapper<TestException> MAPPER = new ExceptionMapper<TestException>(
- "Test", TestException.class ) {
+ static final ExceptionMapper<TestException> MAPPER = new ExceptionMapper<TestException>(
+ "Test", TestException.class) {
@Override
- protected TestException newWithCause( final String message, final Throwable cause ) {
- return new TestException( message, cause );
+ protected TestException newWithCause(final String message, final Throwable cause) {
+ return new TestException(message, cause);
}
};
static final FutureInvoker GET = new FutureInvoker() {
@Override
- public void invokeGet( final CheckedFuture<?,?> future ) throws Exception {
+ public void invokeGet(final CheckedFuture<?, ?> future) throws Exception {
future.get();
}
@Override
- public Throwable extractWrappedTestEx( final Exception from ) {
- if (from instanceof ExecutionException ) {
+ public Throwable extractWrappedTestEx(final Exception from) {
+ if (from instanceof ExecutionException) {
return from.getCause();
}
static final FutureInvoker TIMED_GET = new FutureInvoker() {
@Override
- public void invokeGet( final CheckedFuture<?,?> future ) throws Exception {
- future.get( 1, TimeUnit.HOURS );
+ public void invokeGet(final CheckedFuture<?, ?> future) throws Exception {
+ future.get(1, TimeUnit.HOURS);
}
@Override
- public Throwable extractWrappedTestEx( final Exception from ) {
- if (from instanceof ExecutionException ) {
+ public Throwable extractWrappedTestEx(final Exception from) {
+ if (from instanceof ExecutionException) {
return from.getCause();
}
static final FutureInvoker CHECKED_GET = new FutureInvoker() {
@Override
- public void invokeGet( final CheckedFuture<?,?> future ) throws Exception {
+ public void invokeGet(final CheckedFuture<?,?> future) throws Exception {
future.checkedGet();
}
@Override
- public Throwable extractWrappedTestEx( final Exception from ) {
+ public Throwable extractWrappedTestEx(final Exception from) {
return from;
}
};
static final FutureInvoker TIMED_CHECKED_GET = new FutureInvoker() {
@Override
- public void invokeGet( final CheckedFuture<?,?> future ) throws Exception {
- future.checkedGet( 50, TimeUnit.MILLISECONDS );
+ public void invokeGet(final CheckedFuture<?,?> future) throws Exception {
+ future.checkedGet(50, TimeUnit.MILLISECONDS);
}
@Override
- public Throwable extractWrappedTestEx( final Exception from ) {
+ public Throwable extractWrappedTestEx(final Exception from) {
return from;
}
};
@Test
public void testGet() throws Exception {
-
SettableFuture<String> delegate = SettableFuture.create();
- MappingCheckedFuture<String,TestException> future = MappingCheckedFuture.create( delegate, MAPPER );
- delegate.set( "test" );
- assertEquals( "get", "test", future.get() );
+ MappingCheckedFuture<String,TestException> future = MappingCheckedFuture.create(delegate, MAPPER);
+ delegate.set("test");
+ assertEquals("get", "test", future.get());
}
@Test
public void testGetWithExceptions() throws Exception {
-
- testExecutionException( GET, new RuntimeException() );
- testExecutionException( GET, new TestException( "mock", null ) );
- testCancellationException( GET );
- testInterruptedException( GET );
+ testExecutionException(GET, new RuntimeException());
+ testExecutionException(GET, new TestException("mock", null));
+ testCancellationException(GET);
+ testInterruptedException(GET);
}
@Test
public void testTimedGet() throws Exception {
-
SettableFuture<String> delegate = SettableFuture.create();
- MappingCheckedFuture<String,TestException> future = MappingCheckedFuture.create( delegate, MAPPER );
- delegate.set( "test" );
- assertEquals( "get", "test", future.get( 50, TimeUnit.MILLISECONDS ) );
+ MappingCheckedFuture<String,TestException> future = MappingCheckedFuture.create(delegate, MAPPER);
+ delegate.set("test");
+ assertEquals("get", "test", future.get(50, TimeUnit.MILLISECONDS));
}
@Test
public void testTimedGetWithExceptions() throws Exception {
-
- testExecutionException( TIMED_GET, new RuntimeException() );
- testCancellationException( TIMED_GET );
- testInterruptedException( TIMED_GET );
+ testExecutionException(TIMED_GET, new RuntimeException());
+ testCancellationException(TIMED_GET);
+ testInterruptedException(TIMED_GET);
}
@Test
public void testCheckedGetWithExceptions() throws Exception {
-
- testExecutionException( CHECKED_GET, new RuntimeException() );
- testCancellationException( CHECKED_GET );
- testInterruptedException( CHECKED_GET );
+ testExecutionException(CHECKED_GET, new RuntimeException());
+ testCancellationException(CHECKED_GET);
+ testInterruptedException(CHECKED_GET);
}
@Test
public void testTimedCheckedWithExceptions() throws Exception {
-
- testExecutionException( TIMED_CHECKED_GET, new RuntimeException() );
- testCancellationException( TIMED_CHECKED_GET );
- testInterruptedException( TIMED_CHECKED_GET );
+ testExecutionException(TIMED_CHECKED_GET, new RuntimeException());
+ testCancellationException(TIMED_CHECKED_GET);
+ testInterruptedException(TIMED_CHECKED_GET);
}
- private static void testExecutionException( final FutureInvoker invoker, final Throwable cause ) {
-
+ @SuppressWarnings("checkstyle:illegalCatch")
+ private static void testExecutionException(final FutureInvoker invoker, final Throwable cause) {
SettableFuture<String> delegate = SettableFuture.create();
- MappingCheckedFuture<String,TestException> mappingFuture =
- MappingCheckedFuture.create( delegate, MAPPER );
+ MappingCheckedFuture<String, TestException> mappingFuture = MappingCheckedFuture.create(delegate, MAPPER);
- delegate.setException( cause );
+ delegate.setException(cause);
try {
- invoker.invokeGet( mappingFuture );
- fail( "Expected exception thrown" );
- } catch( Exception e ) {
- Throwable expectedTestEx = invoker.extractWrappedTestEx( e );
- assertNotNull( "Expected returned exception is null", expectedTestEx );
- assertEquals( "Exception type", TestException.class, expectedTestEx.getClass() );
-
- if (cause instanceof TestException ) {
- assertNull( "Expected null cause", expectedTestEx.getCause() );
+ invoker.invokeGet(mappingFuture);
+ fail("Expected exception thrown");
+ } catch (Exception e) {
+ Throwable expectedTestEx = invoker.extractWrappedTestEx(e);
+ assertNotNull("Expected returned exception is null", expectedTestEx);
+ assertEquals("Exception type", TestException.class, expectedTestEx.getClass());
+
+ if (cause instanceof TestException) {
+ assertNull("Expected null cause", expectedTestEx.getCause());
} else {
- assertSame( "TestException cause", cause, expectedTestEx.getCause() );
+ assertSame("TestException cause", cause, expectedTestEx.getCause());
}
}
}
- private static void testCancellationException( final FutureInvoker invoker ) {
-
+ @SuppressWarnings("checkstyle:illegalCatch")
+ private static void testCancellationException(final FutureInvoker invoker) {
SettableFuture<String> delegate = SettableFuture.create();
- MappingCheckedFuture<String,TestException> mappingFuture =
- MappingCheckedFuture.create( delegate, MAPPER );
+ MappingCheckedFuture<String, TestException> mappingFuture = MappingCheckedFuture.create(delegate, MAPPER);
- mappingFuture.cancel( false );
+ mappingFuture.cancel(false);
try {
- invoker.invokeGet( mappingFuture );
- fail( "Expected exception thrown" );
- } catch( Exception e ) {
- Throwable expectedTestEx = invoker.extractWrappedTestEx( e );
- assertNotNull( "Expected returned exception is null", expectedTestEx );
- assertEquals( "Exception type", TestException.class, expectedTestEx.getClass() );
- assertEquals( "TestException cause type", CancellationException.class,
- expectedTestEx.getCause().getClass() );
+ invoker.invokeGet(mappingFuture);
+ fail("Expected exception thrown");
+ } catch (Exception e) {
+ Throwable expectedTestEx = invoker.extractWrappedTestEx(e);
+ assertNotNull("Expected returned exception is null", expectedTestEx);
+ assertEquals("Exception type", TestException.class, expectedTestEx.getClass());
+ assertEquals("TestException cause type", CancellationException.class, expectedTestEx.getCause().getClass());
}
}
- private static void testInterruptedException( final FutureInvoker invoker ) throws Exception {
-
+ @SuppressWarnings("checkstyle:illegalCatch")
+ private static void testInterruptedException(final FutureInvoker invoker) throws Exception {
SettableFuture<String> delegate = SettableFuture.create();
- final MappingCheckedFuture<String,TestException> mappingFuture =
- MappingCheckedFuture.create( delegate, MAPPER );
+ final MappingCheckedFuture<String, TestException> mappingFuture = MappingCheckedFuture.create(delegate, MAPPER);
final AtomicReference<AssertionError> assertError = new AtomicReference<>();
- final CountDownLatch doneLatch = new CountDownLatch( 1 );
+ final CountDownLatch doneLatch = new CountDownLatch(1);
Thread thread = new Thread() {
-
@Override
public void run() {
try {
doInvoke();
- } catch( AssertionError e ) {
- assertError.set( e );
+ } catch (AssertionError e) {
+ assertError.set(e);
} finally {
doneLatch.countDown();
}
void doInvoke() {
try {
- invoker.invokeGet( mappingFuture );
- fail( "Expected exception thrown" );
- } catch( Exception e ) {
- Throwable expectedTestEx = invoker.extractWrappedTestEx( e );
- assertNotNull( "Expected returned exception is null", expectedTestEx );
- assertEquals( "Exception type", TestException.class, expectedTestEx.getClass() );
- assertEquals( "TestException cause type", InterruptedException.class,
- expectedTestEx.getCause().getClass() );
+ invoker.invokeGet(mappingFuture);
+ fail("Expected exception thrown");
+ } catch (Exception e) {
+ Throwable expectedTestEx = invoker.extractWrappedTestEx(e);
+ assertNotNull("Expected returned exception is null", expectedTestEx);
+ assertEquals("Exception type", TestException.class, expectedTestEx.getClass());
+ assertEquals("TestException cause type", InterruptedException.class,
+ expectedTestEx.getCause().getClass());
}
}
};
thread.start();
thread.interrupt();
- assertEquals( "get call completed", true, doneLatch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("get call completed", doneLatch.await(5, TimeUnit.SECONDS));
- if (assertError.get() != null ) {
+ if (assertError.get() != null) {
throw assertError.get();
}
}
package org.opendaylight.yangtools.util.concurrent;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.Uninterruptibles;
-import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
+import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager.BatchedInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
actual.clear();
}
- void onNotification(final N data) {
+ void onNotification(final Collection<? extends N> data) {
try {
if (sleepTime > 0) {
- Uninterruptibles.sleepUninterruptibly( sleepTime, TimeUnit.MILLISECONDS);
+ Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.MILLISECONDS);
}
if (cacheNotifications) {
- actual.add(data);
+ actual.addAll(data);
}
RuntimeException localRuntimeEx = runtimeEx;
}
} finally {
- latch.countDown();
+ data.forEach(action -> latch.countDown());
}
}
void verifyNotifications() {
- boolean done = Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.SECONDS);
+ boolean done = Uninterruptibles.awaitUninterruptibly(latch, 5, TimeUnit.SECONDS);
if (!done) {
long actualCount = latch.getCount();
fail(name + ": Received " + (expCount - actualCount) + " notifications. Expected " + expCount);
}
}
- static class TestNotifier<N> implements QueuedNotificationManager.Invoker<TestListener<N>, N> {
+ static class TestNotifier<N> implements BatchedInvoker<TestListener<N>, N> {
@Override
- public void invokeListener(final TestListener<N> listener, final N notification) {
- listener.onNotification(notification);
+ public void invokeListener(final TestListener<N> listener, final Collection<? extends N> notifications) {
+ listener.onNotification(notifications);
}
}
}
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testNotificationsWithSingleListener() {
- queueExecutor = Executors.newFixedThreadPool( 2 );
- NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>(queueExecutor,
- new TestNotifier<>(), 10, "TestMgr" );
+ queueExecutor = Executors.newFixedThreadPool(2);
+ NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(queueExecutor,
+ new TestNotifier<>(), 10, "TestMgr");
- int initialCount = 6;
- int nNotifications = 100;
+ int count = 100;
- TestListener<Integer> listener = new TestListener<>(nNotifications, 1);
+ TestListener<Integer> listener = new TestListener<>(count, 1);
listener.sleepTime = 20;
manager.submitNotifications(listener, Arrays.asList(1, 2));
listener.sleepTime = 0;
- List<Integer> expNotifications = new ArrayList<>(nNotifications);
+ List<Integer> expNotifications = new ArrayList<>(count);
expNotifications.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
- for (int i = 1; i <= nNotifications - initialCount; i++) {
- Integer v = Integer.valueOf(initialCount + i);
- expNotifications.add(v);
- manager.submitNotification(listener, v);
+ int initialCount = 6;
+ for (int i = 1; i <= count - initialCount; i++) {
+ Integer val = Integer.valueOf(initialCount + i);
+ expNotifications.add(val);
+ manager.submitNotification(listener, val);
}
- listener.verifyNotifications( expNotifications );
+ listener.verifyNotifications(expNotifications);
}
@Test
public void testNotificationsWithMultipleListeners() throws InterruptedException {
- int nListeners = 10;
- queueExecutor = Executors.newFixedThreadPool(nListeners);
- final ExecutorService stagingExecutor = Executors.newFixedThreadPool(nListeners);
- final NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>(
- queueExecutor, new TestNotifier<>(), 5000, "TestMgr" );
+ int count = 10;
+ queueExecutor = Executors.newFixedThreadPool(count);
+ final ExecutorService stagingExecutor = Executors.newFixedThreadPool(count);
+ final NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(
+ queueExecutor, new TestNotifier<>(), 5000, "TestMgr");
final int nNotifications = 100000;
- LOG.info("Testing {} listeners with {} notifications each...", nListeners, nNotifications);
+ LOG.info("Testing {} listeners with {} notifications each...", count, nNotifications);
final Integer[] notifications = new Integer[nNotifications];
for (int i = 1; i <= nNotifications; i++) {
List<TestListener<Integer>> listeners = new ArrayList<>();
List<Thread> threads = new ArrayList<>();
- for (int i = 1; i <= nListeners; i++) {
+ for (int i = 1; i <= count; i++) {
final TestListener<Integer> listener =
i == 2 ? new TestListener2<>(nNotifications, i) :
i == 3 ? new TestListener3<>(nNotifications, i) :
}
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testNotificationsWithListenerRuntimeEx() {
queueExecutor = Executors.newFixedThreadPool(1);
- NotificationManager<TestListener<Integer>, Integer> manager =
- new QueuedNotificationManager<>( queueExecutor, new TestNotifier<>(),
- 10, "TestMgr" );
-
+ NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(queueExecutor,
+ new TestNotifier<>(), 10, "TestMgr");
TestListener<Integer> listener = new TestListener<>(2, 1);
- final RuntimeException mockedRuntimeException = mock(RuntimeException.class);
- doNothing().when(mockedRuntimeException).printStackTrace(any(PrintStream.class));
+ final RuntimeException mockedRuntimeException = new RuntimeException("mock");
listener.runtimeEx = mockedRuntimeException;
manager.submitNotification(listener, 1);
manager.submitNotification(listener, 2);
listener.verifyNotifications();
+ List<Runnable> tasks = queueExecutor.shutdownNow();
+ assertTrue(tasks.isEmpty());
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testNotificationsWithListenerJVMError() {
final CountDownLatch errorCaughtLatch = new CountDownLatch(1);
queueExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>()) {
- @Override
- public void execute(final Runnable command) {
- super.execute(() -> {
- try {
- command.run();
- } catch (Error e) {
- errorCaughtLatch.countDown();
- }
- });
- }
+ @Override
+ @SuppressWarnings("checkstyle:illegalCatch")
+ public void execute(final Runnable command) {
+ super.execute(() -> {
+ try {
+ command.run();
+ } catch (Error e) {
+ errorCaughtLatch.countDown();
+ }
+ });
+ }
};
- NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>(queueExecutor,
+ NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(queueExecutor,
new TestNotifier<>(), 10, "TestMgr");
TestListener<Integer> listener = new TestListener<>(2, 1);
manager.submitNotification(listener, 1);
- assertEquals("JVM Error caught", true, Uninterruptibles.awaitUninterruptibly(
- errorCaughtLatch, 5, TimeUnit.SECONDS));
+ assertTrue("JVM Error caught", Uninterruptibles.awaitUninterruptibly(errorCaughtLatch, 5, TimeUnit.SECONDS));
manager.submitNotification(listener, 2);
listener.verifyNotifications();
+ List<Runnable> tasks = queueExecutor.shutdownNow();
+ assertTrue(tasks.isEmpty());
}
}
import java.util.concurrent.ExecutionException;
import org.junit.Test;
-public final class ReflectiveExceptionMapperTest {
+public class ReflectiveExceptionMapperTest {
static final class NoArgumentCtorException extends Exception {
private static final long serialVersionUID = 1L;
- public NoArgumentCtorException() {
+ NoArgumentCtorException() {
super();
}
}
static final class FailingCtorException extends Exception {
private static final long serialVersionUID = 1L;
- public FailingCtorException(final String message, final Throwable cause) {
+ FailingCtorException(final String message, final Throwable cause) {
throw new IllegalArgumentException("just for test");
}
}
- static final class GoodException extends Exception {
+ public static final class GoodException extends Exception {
private static final long serialVersionUID = 1L;
public GoodException(final String message, final Throwable cause) {
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testNoArgumentsContructor() {
ReflectiveExceptionMapper.create("no arguments", NoArgumentCtorException.class);
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testPrivateContructor() {
ReflectiveExceptionMapper.create("private constructor", PrivateCtorException.class);
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testFailingContructor() {
ReflectiveExceptionMapper.create("failing constructor", FailingCtorException.class);
}
@Test
public void testInstantiation() {
- ReflectiveExceptionMapper<GoodException> mapper = ReflectiveExceptionMapper.create("instantiation", GoodException.class);
+ ReflectiveExceptionMapper<GoodException> mapper = ReflectiveExceptionMapper.create("instantiation",
+ GoodException.class);
final Throwable cause = new Throwable("some test message");
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Stopwatch;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Tests various ThreadPoolExecutor implementations.
* @author Thomas Pantelis
*/
public class ThreadPoolExecutorTest {
+ private static final Logger LOG = LoggerFactory.getLogger(ThreadPoolExecutorTest.class);
private ExecutorService executor;
}
@Test
- public void testFastThreadPoolExecution() throws Exception {
-
- testThreadPoolExecution(
- SpecialExecutors.newBoundedFastThreadPool( 50, 100000, "TestPool" ),
- 100000, "TestPool", 0 );
+ public void testFastThreadPoolExecution() throws InterruptedException {
+ testThreadPoolExecution(SpecialExecutors.newBoundedFastThreadPool(50, 100000, "TestPool"), 100000, "TestPool",
+ 0);
}
@Test(expected = RejectedExecutionException.class)
- public void testFastThreadPoolRejectingTask() throws Exception {
-
- executor = SpecialExecutors.newBoundedFastThreadPool( 1, 1, "TestPool" );
+ public void testFastThreadPoolRejectingTask() throws InterruptedException {
+ executor = SpecialExecutors.newBoundedFastThreadPool(1, 1, "TestPool");
for (int i = 0; i < 5; i++) {
- executor.execute( new Task( null, null, null, null,
- TimeUnit.MICROSECONDS.convert( 5, TimeUnit.SECONDS ) ) );
+ executor.execute(new Task(null, null, null, null, TimeUnit.MICROSECONDS.convert(5, TimeUnit.SECONDS)));
}
}
@Test
- public void testBlockingFastThreadPoolExecution() throws Exception {
-
+ public void testBlockingFastThreadPoolExecution() throws InterruptedException {
// With a queue capacity of 1, it should block at some point.
- testThreadPoolExecution(
- SpecialExecutors.newBlockingBoundedFastThreadPool( 2, 1, "TestPool" ),
- 1000, null, 10 );
+ testThreadPoolExecution(SpecialExecutors.newBlockingBoundedFastThreadPool(2, 1, "TestPool"), 1000, null, 10);
}
@Test
- public void testCachedThreadPoolExecution() throws Exception {
-
- testThreadPoolExecution(
- SpecialExecutors.newBoundedCachedThreadPool( 10, 100000, "TestPool" ),
- 100000, "TestPool", 0 );
+ public void testCachedThreadPoolExecution() throws InterruptedException {
+ testThreadPoolExecution(SpecialExecutors.newBoundedCachedThreadPool(10, 100000, "TestPool"),
+ 100000, "TestPool", 0);
}
@Test(expected = RejectedExecutionException.class)
- public void testCachedThreadRejectingTask() throws Exception {
-
- ExecutorService executor = SpecialExecutors.newBoundedCachedThreadPool( 1, 1, "TestPool" );
+ public void testCachedThreadRejectingTask() throws InterruptedException {
+ ExecutorService executor = SpecialExecutors.newBoundedCachedThreadPool(1, 1, "TestPool");
for (int i = 0; i < 5; i++) {
- executor.execute( new Task( null, null, null, null,
- TimeUnit.MICROSECONDS.convert( 5, TimeUnit.SECONDS ) ) );
+ executor.execute(new Task(null, null, null, null, TimeUnit.MICROSECONDS.convert(5, TimeUnit.SECONDS)));
}
}
@Test
- public void testBlockingCachedThreadPoolExecution() throws Exception {
-
- testThreadPoolExecution(
- SpecialExecutors.newBlockingBoundedCachedThreadPool( 2, 1, "TestPool" ),
- 1000, null, 10 );
+ public void testBlockingCachedThreadPoolExecution() throws InterruptedException {
+ testThreadPoolExecution(SpecialExecutors.newBlockingBoundedCachedThreadPool(2, 1, "TestPool"), 1000, null, 10);
}
- void testThreadPoolExecution( final ExecutorService executor,
- final int numTasksToRun, final String expThreadPrefix, final long taskDelay ) throws Exception {
+ void testThreadPoolExecution(final ExecutorService executor, final int numTasksToRun, final String expThreadPrefix,
+ final long taskDelay) throws InterruptedException {
this.executor = executor;
- System.out.println("\nTesting " + executor.getClass().getSimpleName() + " with " + numTasksToRun + " tasks.");
+ LOG.debug("Testing {} with {} tasks.", executor.getClass().getSimpleName(), numTasksToRun);
- final CountDownLatch tasksRunLatch = new CountDownLatch( numTasksToRun );
+ final CountDownLatch tasksRunLatch = new CountDownLatch(numTasksToRun);
final ConcurrentMap<Thread, AtomicLong> taskCountPerThread = new ConcurrentHashMap<>();
final AtomicReference<AssertionError> threadError = new AtomicReference<>();
public void run() {
for (int i = 0; i < numTasksToRun; i++) {
// if (i%100 == 0) {
-// Uninterruptibles.sleepUninterruptibly( 20, TimeUnit.MICROSECONDS );
+// Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MICROSECONDS);
// }
- executor.execute( new Task( tasksRunLatch, taskCountPerThread,
- threadError, expThreadPrefix, taskDelay ) );
+ executor.execute(new Task(tasksRunLatch, taskCountPerThread, threadError, expThreadPrefix,
+ taskDelay));
}
}
}.start();
- boolean done = tasksRunLatch.await( 15, TimeUnit.SECONDS );
+ boolean done = tasksRunLatch.await(15, TimeUnit.SECONDS);
stopWatch.stop();
if (!done) {
- fail((numTasksToRun - tasksRunLatch.getCount()) + " tasks out of " + numTasksToRun + " executed");
+ fail(numTasksToRun - tasksRunLatch.getCount() + " tasks out of " + numTasksToRun + " executed");
}
if (threadError.get() != null) {
throw threadError.get();
}
- System.out.println( taskCountPerThread.size() + " threads used:" );
+ LOG.debug("{} threads used:", taskCountPerThread.size());
for (Map.Entry<Thread, AtomicLong> e : taskCountPerThread.entrySet()) {
- System.out.println( " " + e.getKey().getName() + " - " + e.getValue() + " tasks" );
+ LOG.debug(" {} - {} tasks", e.getKey().getName(), e.getValue());
}
- System.out.println( "\n" + executor );
- System.out.println( "\nElapsed time: " + stopWatch );
- System.out.println();
+ LOG.debug("{}", executor);
+ LOG.debug("Elapsed time: {}", stopWatch);
}
static class Task implements Runnable {
final String expThreadPrefix;
final long delay;
- Task( CountDownLatch tasksRunLatch, ConcurrentMap<Thread, AtomicLong> taskCountPerThread,
- AtomicReference<AssertionError> threadError, String expThreadPrefix, long delay ) {
+ Task(final CountDownLatch tasksRunLatch, final ConcurrentMap<Thread, AtomicLong> taskCountPerThread,
+ final AtomicReference<AssertionError> threadError, final String expThreadPrefix, final long delay) {
this.tasksRunLatch = tasksRunLatch;
this.taskCountPerThread = taskCountPerThread;
this.threadError = threadError;
blockLatch = null;
}
- Task( CountDownLatch tasksRunLatch, CountDownLatch blockLatch ) {
+ Task(final CountDownLatch tasksRunLatch, final CountDownLatch blockLatch) {
this.tasksRunLatch = tasksRunLatch;
this.blockLatch = blockLatch;
this.taskCountPerThread = null;
try {
try {
if (delay > 0) {
- TimeUnit.MICROSECONDS.sleep( delay );
+ TimeUnit.MICROSECONDS.sleep(delay);
} else if (blockLatch != null) {
blockLatch.await();
}
} catch (InterruptedException e) {
+ // Ignored
}
if (expThreadPrefix != null) {
- assertEquals( "Thread name starts with " + expThreadPrefix, true,
- Thread.currentThread().getName().startsWith( expThreadPrefix ) );
+ assertTrue("Thread name starts with " + expThreadPrefix,
+ Thread.currentThread().getName().startsWith(expThreadPrefix));
}
if (taskCountPerThread != null) {
- AtomicLong count = taskCountPerThread.get( Thread.currentThread() );
+ AtomicLong count = taskCountPerThread.get(Thread.currentThread());
if (count == null) {
- count = new AtomicLong( 0 );
- AtomicLong prev = taskCountPerThread.putIfAbsent( Thread.currentThread(), count );
+ count = new AtomicLong(0);
+ AtomicLong prev = taskCountPerThread.putIfAbsent(Thread.currentThread(), count);
if (prev != null) {
count = prev;
}
} catch (AssertionError e) {
if (threadError != null) {
- threadError.set( e );
+ threadError.set(e);
}
} finally {
if (tasksRunLatch != null) {
package org.opendaylight.yangtools.util.concurrent;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
@Test
public void testOffer() throws InterruptedException {
+ TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>(2);
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>( 2 );
+ assertTrue("offer", queue.offer("1"));
+ assertEquals("getLargestQueueSize", 1, queue.getLargestQueueSize());
+ assertEquals("size", 1, queue.size());
- assertEquals( "offer", true, queue.offer( "1" ) );
- assertEquals( "getLargestQueueSize", 1, queue.getLargestQueueSize() );
- assertEquals( "size", 1, queue.size() );
+ assertTrue("offer", queue.offer("2", 1, TimeUnit.MILLISECONDS));
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
- assertEquals( "offer", true, queue.offer( "2", 1, TimeUnit.MILLISECONDS ) );
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
+ assertFalse("offer", queue.offer("3"));
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
- assertEquals( "offer", false, queue.offer( "3" ) );
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
-
- assertEquals( "offer", false, queue.offer( "4", 1, TimeUnit.MILLISECONDS ) );
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
+ assertFalse("offer", queue.offer("4", 1, TimeUnit.MILLISECONDS));
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
}
@Test
public void testPut() throws InterruptedException {
-
TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>();
- queue.put( "1" );
- assertEquals( "getLargestQueueSize", 1, queue.getLargestQueueSize() );
- assertEquals( "size", 1, queue.size() );
+ queue.put("1");
+ assertEquals("getLargestQueueSize", 1, queue.getLargestQueueSize());
+ assertEquals("size", 1, queue.size());
- queue.put( "2" );
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
+ queue.put("2");
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
}
@Test
public void testAdd() {
+ TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>(2);
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>( 2 );
+ assertTrue("add", queue.add("1"));
+ assertEquals("getLargestQueueSize", 1, queue.getLargestQueueSize());
+ assertEquals("size", 1, queue.size());
- assertEquals( "add", true, queue.add( "1" ) );
- assertEquals( "getLargestQueueSize", 1, queue.getLargestQueueSize() );
- assertEquals( "size", 1, queue.size() );
-
- assertEquals( "add", true, queue.add( "2" ) );
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
+ assertTrue("add", queue.add("2"));
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
try {
- queue.add( "3" );
- fail( "Expected IllegalStateException" );
- } catch( IllegalStateException e ) {
+ queue.add("3");
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException e) {
// Expected
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
}
}
@Test
public void testAddAll() {
+ TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>(3);
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>( 3 );
-
- queue.addAll( Arrays.asList( "1", "2" ) );
- assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
- assertEquals( "size", 2, queue.size() );
+ queue.addAll(Arrays.asList("1", "2"));
+ assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
+ assertEquals("size", 2, queue.size());
try {
- queue.addAll( Arrays.asList( "3", "4" ) );
- fail( "Expected IllegalStateException" );
- } catch( IllegalStateException e ) {
+ queue.addAll(Arrays.asList("3", "4"));
+ fail("Expected IllegalStateException");
+ } catch (IllegalStateException e) {
// Expected
- assertEquals( "getLargestQueueSize", 3, queue.getLargestQueueSize() );
- assertEquals( "size", 3, queue.size() );
+ assertEquals("getLargestQueueSize", 3, queue.getLargestQueueSize());
+ assertEquals("size", 3, queue.size());
}
}
}
</dependency>
</dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
<!--
Maven Site Configuration
super(Preconditions.checkNotNull(message), cause);
if (errors != null && errors.length > 0) {
- errorList = ImmutableList.copyOf( Arrays.asList( errors ) );
+ errorList = ImmutableList.copyOf(Arrays.asList(errors));
} else {
// Add a default RpcError.
errorList = ImmutableList.of(RpcResultBuilder.newError(ErrorType.APPLICATION, null,
@Override
public String toString() {
- return MoreObjects.toStringHelper( this ).add( "message", getMessage() )
- .add( "errorList", errorList ).toString();
+ return MoreObjects.toStringHelper(this).add("message", getMessage())
+ .add("errorList", errorList).toString();
}
}
* The QName from XML consists of local name of element and XML namespace, but
* for our use, we added module revision to it.
*
+ * <p>
* In YANG context QName is full name of defined node, type, procedure or
* notification. QName consists of XML namespace, YANG model revision and local
* name of defined type. It is used to prevent name clashes between nodes with
* node in the YANG module</li>
* </ul>
*
+ * <p>
* QName may also have <code>prefix</code> assigned, but prefix does not
* affect equality and identity of two QNames and carry only information
* which may be useful for serializers / deserializers.
- *
- *
*/
public final class QName implements Immutable, Serializable, Comparable<QName> {
private static final Interner<QName> INTERNER = Interners.newWeakInterner();
private static String checkLocalName(final String localName) {
Preconditions.checkArgument(localName != null, "Parameter 'localName' may not be null.");
- Preconditions.checkArgument(!Strings.isNullOrEmpty(localName), "Parameter 'localName' must be a non-empty string.");
+ Preconditions.checkArgument(!Strings.isNullOrEmpty(localName),
+ "Parameter 'localName' must be a non-empty string.");
for (final char c : ILLEGAL_CHARACTERS) {
if (localName.indexOf(c) != -1) {
throw new IllegalArgumentException("Invalid input:" + input);
}
+ public static QName create(final QName base, final String localName) {
+ return create(base.getModule(), localName);
+ }
+
+ /**
+ * Creates new QName.
+ *
+ * @param qnameModule
+ * Namespace and revision enclosed as a QNameModule
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return Instance of QName
+ */
+ public static QName create(final QNameModule qnameModule, final String localName) {
+ return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
+ }
+
+ /**
+ * Creates new QName.
+ *
+ * @param namespace
+ * Namespace of QName or null if namespace is undefined.
+ * @param revision
+ * Revision of namespace or null if revision is unspecified.
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return Instance of QName
+ */
+ public static QName create(final URI namespace, final Date revision, final String localName) {
+ return create(QNameModule.create(namespace, revision), localName);
+ }
+
+ /**
+ * Creates new QName.
+ *
+ * @param namespace
+ * Namespace of QName or null if namespace is undefined.
+ * @param revision
+ * Revision of namespace or null if revision is unspecified.
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return Instance of QName
+ */
+ public static QName create(final String namespace, final String localName, final Date revision) {
+ final URI namespaceUri = parseNamespace(namespace);
+ return create(QNameModule.create(namespaceUri, revision), localName);
+ }
+
+ /**
+ * Creates new QName.
+ *
+ * @param namespace
+ * Namespace of QName, MUST NOT BE Null.
+ * @param revision
+ * Revision of namespace / YANG module. MUST NOT BE null, MUST BE
+ * in format <code>YYYY-mm-dd</code>.
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return A new QName
+ * @throws NullPointerException
+ * If any of parameters is null.
+ * @throws IllegalArgumentException
+ * If <code>namespace</code> is not valid URI or
+ * <code>revision</code> is not according to format
+ * <code>YYYY-mm-dd</code>.
+ */
+ public static QName create(final String namespace, final String revision, final String localName) {
+ final URI namespaceUri = parseNamespace(namespace);
+ final Date revisionDate = parseRevision(revision);
+ return create(namespaceUri, revisionDate, localName);
+ }
+
+ /**
+ * Creates new QName.
+ *
+ * @param namespace
+ * Namespace of QName, MUST NOT BE Null.
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return A new QName
+ * @throws NullPointerException
+ * If any of parameters is null.
+ * @throws IllegalArgumentException
+ * If <code>namespace</code> is not valid URI.
+ */
+ public static QName create(final String namespace, final String localName) {
+ return create(parseNamespace(namespace), null, localName);
+ }
+
/**
* Get the module component of the QName.
*
/**
* Returns YANG schema identifier which were defined for this node in the
- * YANG module
+ * YANG module.
*
* @return YANG schema identifier which were defined for this node in the
* YANG module
/**
* Returns revision of the YANG module if the module has defined revision,
- * otherwise returns <code>null</code>
+ * otherwise returns <code>null</code>.
*
* @return revision of the YANG module if the module has defined revision,
* otherwise returns <code>null</code>
}
/**
- *
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also instance of
* {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
return Objects.equals(localName, other.localName) && module.equals(other.module);
}
- public static QName create(final QName base, final String localName) {
- return create(base.getModule(), localName);
- }
-
- /**
- * Creates new QName.
- *
- * @param qnameModule
- * Namespace and revision enclosed as a QNameModule
- * @param localName
- * Local name part of QName. MUST NOT BE null.
- * @return Instance of QName
- */
- public static QName create(final QNameModule qnameModule, final String localName) {
- return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
- }
-
- /**
- * Creates new QName.
- *
- * @param namespace
- * Namespace of QName or null if namespace is undefined.
- * @param revision
- * Revision of namespace or null if revision is unspecified.
- * @param localName
- * Local name part of QName. MUST NOT BE null.
- * @return Instance of QName
- */
- public static QName create(final URI namespace, final Date revision, final String localName) {
- return create(QNameModule.create(namespace, revision), localName);
- }
-
- /**
- * Creates new QName.
- *
- * @param namespace
- * Namespace of QName or null if namespace is undefined.
- * @param revision
- * Revision of namespace or null if revision is unspecified.
- * @param localName
- * Local name part of QName. MUST NOT BE null.
- * @return Instance of QName
- */
- public static QName create(final String namespace, final String localName, final Date revision) {
- final URI namespaceUri = parseNamespace(namespace);
- return create(QNameModule.create(namespaceUri, revision), localName);
- }
-
- /**
- * Creates new QName.
- *
- * @param namespace
- * Namespace of QName, MUST NOT BE Null.
- * @param revision
- * Revision of namespace / YANG module. MUST NOT BE null, MUST BE
- * in format <code>YYYY-mm-dd</code>.
- * @param localName
- * Local name part of QName. MUST NOT BE null.
- * @return A new QName
- * @throws NullPointerException
- * If any of parameters is null.
- * @throws IllegalArgumentException
- * If <code>namespace</code> is not valid URI or
- * <code>revision</code> is not according to format
- * <code>YYYY-mm-dd</code>.
- */
- public static QName create(final String namespace, final String revision, final String localName) {
- final URI namespaceUri = parseNamespace(namespace);
- final Date revisionDate = parseRevision(revision);
- return create(namespaceUri, revisionDate, localName);
- }
-
private static URI parseNamespace(final String namespace) {
try {
return new URI(namespace);
}
}
- /**
- * Creates new QName.
- *
- * @param namespace
- * Namespace of QName, MUST NOT BE Null.
- * @param localName
- * Local name part of QName. MUST NOT BE null.
- * @return A new QName
- * @throws NullPointerException
- * If any of parameters is null.
- * @throws IllegalArgumentException
- * If <code>namespace</code> is not valid URI.
- */
- public static QName create(final String namespace, final String localName) {
- return create(parseNamespace(namespace), null, localName);
- }
-
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
}
/**
- * Return string representation of revision in format
- * <code>YYYY-mm-dd</code>
+ * Return string representation of revision in format <code>YYYY-mm-dd</code>
*
+ * <p>
* YANG Specification defines format for <code>revision</code> as
* YYYY-mm-dd. This format for revision is reused accross multiple places
* such as capabilities URI, YANG modules, etc.
return create(getNamespace(), null, localName);
}
+ @SuppressWarnings("checkstyle:illegalCatch")
public static Date parseRevision(final String formatedDate) {
try {
return getRevisionFormat().parse(formatedDate);
* Formats {@link Date} representing revision to format
* <code>YYYY-mm-dd</code>
*
+ * <p>
* YANG Specification defines format for <code>revision</code> as
* YYYY-mm-dd. This format for revision is reused accross multiple places
* such as capabilities URI, YANG modules, etc.
}
/**
- *
* Compares this QName to other, without comparing revision.
*
+ * <p>
* Compares instance of this to other instance of QName and returns true if
* both instances have equal <code>localName</code> ({@link #getLocalName()}
* ) and <code>namespace</code> ({@link #getNamespace()}).
@Override
public String toString() {
- return MoreObjects.toStringHelper(QNameModule.class).omitNullValues().add("ns", getNamespace()).add("rev", getFormattedRevision()).toString();
+ return MoreObjects.toStringHelper(QNameModule.class).omitNullValues().add("ns", getNamespace())
+ .add("rev", getFormattedRevision()).toString();
}
}
private String str;
+ @SuppressWarnings("checkstyle:redundantModifier")
public Proxy() {
// For Externalizable
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final int compareTo(final Revision o) {
return toDate().compareTo(o.toDate());
}
/**
* Returns a short string that identifies the general type of error condition.
+ *
* <p>
* The following outlines suggested values as defined by netconf (<a href="https://tools.ietf.org/html/rfc6241#page-89">RFC 6241</a>):
* <pre>
String getMessage();
/**
- *
* Returns a string containing additional information to provide extended
* and/or implementation-specific debugging information.
*
String getInfo();
/**
- *
* Returns an exception cause.
*
* @return a Throwable if the error was triggered by exception, null otherwise.
private final T result;
private final boolean successful;
- RpcResultImpl( final boolean successful, final T result,
- final Collection<RpcError> errors ) {
+ RpcResultImpl(final boolean successful, final T result,
+ final Collection<RpcError> errors) {
this.successful = successful;
this.result = result;
this.errors = errors;
private final ErrorType errorType;
private final Throwable cause;
- RpcErrorImpl( final ErrorSeverity severity, final ErrorType errorType,
+ RpcErrorImpl(final ErrorSeverity severity, final ErrorType errorType,
final String tag, final String message, final String applicationTag, final String info,
- final Throwable cause ) {
+ final Throwable cause) {
this.severity = severity;
this.errorType = errorType;
this.tag = tag;
private T result;
private final boolean successful;
- private RpcResultBuilder( final boolean successful, final T result ) {
+ private RpcResultBuilder(final boolean successful, final T result) {
this.successful = successful;
this.result = result;
}
*
* @param result the result value
*/
- public static <T> RpcResultBuilder<T> success( final T result ) {
+ public static <T> RpcResultBuilder<T> success(final T result) {
return new RpcResultBuilder<>(true, result);
}
*
* @param builder builder for the result value
*/
- public static <T> RpcResultBuilder<T> success( final Builder<T> builder ) {
+ public static <T> RpcResultBuilder<T> success(final Builder<T> builder) {
return success(builder.build());
}
*
* @param success true if successful, false otherwise.
*/
- public static <T> RpcResultBuilder<T> status( final boolean success ) {
+ public static <T> RpcResultBuilder<T> status(final boolean success) {
return new RpcResultBuilder<>(success, null);
}
*
* @param other the other RpcResult.
*/
- public static <T> RpcResultBuilder<T> from( final RpcResult<T> other ) {
+ public static <T> RpcResultBuilder<T> from(final RpcResult<T> other) {
return new RpcResultBuilder<>(other.isSuccessful(), other.getResult())
- .withRpcErrors( other.getErrors() );
+ .withRpcErrors(other.getErrors());
}
/**
*
* @return an RpcError
*/
- public static RpcError newError( final ErrorType errorType, final String tag, final String message ) {
- return new RpcErrorImpl( ErrorSeverity.ERROR, errorType,
- tag != null ? tag : "operation-failed", message, null, null, null );
+ public static RpcError newError(final ErrorType errorType, final String tag, final String message) {
+ return new RpcErrorImpl(ErrorSeverity.ERROR, errorType,
+ tag != null ? tag : "operation-failed", message, null, null, null);
}
/**
* @param tag a short string that identifies the general type of error condition. See
* {@link RpcError#getTag} for a list of suggested values.
* @param message a string suitable for human display that describes the error condition.
- * * @param applicationTag a short string that identifies the specific type of error condition.
+ * @param applicationTag a short string that identifies the specific type of error condition.
* @param info a string containing additional information to provide extended
* and/or implementation-specific debugging information.
* @param cause the exception that triggered the error.
*
* @return an RpcError
*/
- public static RpcError newError( final ErrorType errorType, final String tag, final String message,
- final String applicationTag, final String info, final Throwable cause ) {
- return new RpcErrorImpl( ErrorSeverity.ERROR, errorType,
- tag != null ? tag : "operation-failed", message, applicationTag, info, cause );
+ public static RpcError newError(final ErrorType errorType, final String tag, final String message,
+ final String applicationTag, final String info, final Throwable cause) {
+ return new RpcErrorImpl(ErrorSeverity.ERROR, errorType,
+ tag != null ? tag : "operation-failed", message, applicationTag, info, cause);
}
/**
*
* @return an RpcError
*/
- public static RpcError newWarning( final ErrorType errorType, final String tag, final String message ) {
- return new RpcErrorImpl( ErrorSeverity.WARNING, errorType, tag, message, null, null, null );
+ public static RpcError newWarning(final ErrorType errorType, final String tag, final String message) {
+ return new RpcErrorImpl(ErrorSeverity.WARNING, errorType, tag, message, null, null, null);
}
/**
* @param tag a short string that identifies the general type of warning condition. See
* {@link RpcError#getTag} for a list of suggested values.
* @param message a string suitable for human display that describes the warning condition.
- * * @param applicationTag a short string that identifies the specific type of warning condition.
+ * @param applicationTag a short string that identifies the specific type of warning condition.
* @param info a string containing additional information to provide extended
* and/or implementation-specific debugging information.
* @param cause the exception that triggered the warning.
*
* @return an RpcError
*/
- public static RpcError newWarning( final ErrorType errorType, final String tag, final String message,
- final String applicationTag, final String info, final Throwable cause ) {
- return new RpcErrorImpl( ErrorSeverity.WARNING, errorType, tag, message,
- applicationTag, info, cause );
+ public static RpcError newWarning(final ErrorType errorType, final String tag, final String message,
+ final String applicationTag, final String info, final Throwable cause) {
+ return new RpcErrorImpl(ErrorSeverity.WARNING, errorType, tag, message,
+ applicationTag, info, cause);
}
/**
*
* @param result the result value
*/
- public RpcResultBuilder<T> withResult( final T result ) {
+ public RpcResultBuilder<T> withResult(final T result) {
this.result = result;
return this;
}
*
* @param builder builder for the result value
*/
- public RpcResultBuilder<T> withResult( final Builder<T> builder ) {
+ public RpcResultBuilder<T> withResult(final Builder<T> builder) {
return withResult(builder.build());
}
- private void addError( final ErrorSeverity severity, final ErrorType errorType,
+ private void addError(final ErrorSeverity severity, final ErrorType errorType,
final String tag, final String message, final String applicationTag, final String info,
- final Throwable cause ) {
+ final Throwable cause) {
- addError( new RpcErrorImpl( severity, errorType,
+ addError(new RpcErrorImpl(severity, errorType,
tag != null ? tag : "operation-failed", message,
- applicationTag, info, cause ) );
+ applicationTag, info, cause));
}
- private void addError( final RpcError error ) {
+ private void addError(final RpcError error) {
if (errors == null) {
errors = new ImmutableList.Builder<>();
}
- errors.add( error );
+ errors.add(error);
}
/**
* {@link RpcError#getTag} for a list of suggested values.
* @param message a string suitable for human display that describes the warning condition.
*/
- public RpcResultBuilder<T> withWarning( final ErrorType errorType, final String tag, final String message ) {
- addError( ErrorSeverity.WARNING, errorType, tag, message, null, null, null );
+ public RpcResultBuilder<T> withWarning(final ErrorType errorType, final String tag, final String message) {
+ addError(ErrorSeverity.WARNING, errorType, tag, message, null, null, null);
return this;
}
* and/or implementation-specific debugging information.
* @param cause the exception that triggered the warning.
*/
- public RpcResultBuilder<T> withWarning( final ErrorType errorType, final String tag, final String message,
- final String applicationTag, final String info, final Throwable cause ) {
- addError( ErrorSeverity.WARNING, errorType, tag, message, applicationTag, info, cause );
+ public RpcResultBuilder<T> withWarning(final ErrorType errorType, final String tag, final String message,
+ final String applicationTag, final String info, final Throwable cause) {
+ addError(ErrorSeverity.WARNING, errorType, tag, message, applicationTag, info, cause);
return this;
}
* @param errorType the conceptual layer at which the error occurred.
* @param message a string suitable for human display that describes the error condition.
*/
- public RpcResultBuilder<T> withError( final ErrorType errorType, final String message ) {
- addError( ErrorSeverity.ERROR, errorType, null, message, null, null, null );
+ public RpcResultBuilder<T> withError(final ErrorType errorType, final String message) {
+ addError(ErrorSeverity.ERROR, errorType, null, message, null, null, null);
return this;
}
* {@link RpcError#getTag} for a list of suggested values.
* @param message a string suitable for human display that describes the error condition.
*/
- public RpcResultBuilder<T> withError( final ErrorType errorType, final String tag, final String message ) {
- addError( ErrorSeverity.ERROR, errorType, tag, message, null, null, null );
+ public RpcResultBuilder<T> withError(final ErrorType errorType, final String tag, final String message) {
+ addError(ErrorSeverity.ERROR, errorType, tag, message, null, null, null);
return this;
}
* @param message a string suitable for human display that describes the error condition.
* @param cause the exception that triggered the error.
*/
- public RpcResultBuilder<T> withError( final ErrorType errorType, final String message,
- final Throwable cause ) {
- addError( ErrorSeverity.ERROR, errorType, null, message, null, null, cause );
+ public RpcResultBuilder<T> withError(final ErrorType errorType, final String message,
+ final Throwable cause) {
+ addError(ErrorSeverity.ERROR, errorType, null, message, null, null, cause);
return this;
}
* and/or implementation-specific debugging information.
* @param cause the exception that triggered the error.
*/
- public RpcResultBuilder<T> withError( final ErrorType errorType, final String tag, final String message,
- final String applicationTag, final String info, final Throwable cause ) {
- addError( ErrorSeverity.ERROR, errorType, tag, message, applicationTag, info, cause );
+ public RpcResultBuilder<T> withError(final ErrorType errorType, final String tag, final String message,
+ final String applicationTag, final String info, final Throwable cause) {
+ addError(ErrorSeverity.ERROR, errorType, tag, message, applicationTag, info, cause);
return this;
}
*
* @param error the RpcError
*/
- public RpcResultBuilder<T> withRpcError( final RpcError error ) {
- addError( error );
+ public RpcResultBuilder<T> withRpcError(final RpcError error) {
+ addError(error);
return this;
}
*
* @param errors the list of RpcErrors
*/
- public RpcResultBuilder<T> withRpcErrors( final Collection<RpcError> errors ) {
+ public RpcResultBuilder<T> withRpcErrors(final Collection<RpcError> errors) {
if (errors != null) {
for (RpcError error : errors) {
- addError( error );
+ addError(error);
}
}
return this;
/**
* Builds RpcResult and wraps it in a Future
*
+ * <p>
* This is a convenience method to assist those writing rpcs
* that produce immediate results. It allows you to replace
*
- * Futures.immediateFuture(rpcResult.build())
- *
+ * {@code Futures.immediateFuture(rpcResult.build())}
* with
- *
- * rpcResult.buildFuture();
+ * {@code rpcResult.buildFuture();}
*
* @return Future for RpcResult built by RpcResultBuilder
*
public final class SimpleDateFormatUtil {
/**
- * revision format according to Yang spec
+ * revision format according to Yang spec.
*/
private static final String REVISION_SIMPLE_DATE = "yyyy-MM-dd";
/**
- * default Yang date that is used when date is not present
+ * default Yang date that is used when date is not present.
*/
private static final String DEFAULT_DATE = "1970-01-01";
/**
- * {@link SimpleDateFormatUtil#DEFAULT_DATE} for revision statement
+ * {@link SimpleDateFormatUtil#DEFAULT_DATE} for revision statement.
*/
public static final Date DEFAULT_DATE_REV;
/**
- * {@link SimpleDateFormatUtil#DEFAULT_DATE} for import statement
+ * {@link SimpleDateFormatUtil#DEFAULT_DATE} for import statement.
*/
public static final Date DEFAULT_DATE_IMP;
/**
- * {@link SimpleDateFormatUtil#DEFAULT_DATE} for belongs-to statement
+ * {@link SimpleDateFormatUtil#DEFAULT_DATE} for belongs-to statement.
*/
public static final Date DEFAULT_BELONGS_TO_DATE;
URI.create("urn:ietf:params:netconf:capability:yang-library:1.0");
/**
- * Prefix for YANG-specific XPath functions
+ * Prefix for YANG-specific XPath functions.
*/
public static final String YANG_XPATH_FUNCTIONS_PREFIX = "yang";
private final String str;
private String reference;
- private YangVersion(final String str, final String reference) {
+ YangVersion(final String str, final String reference) {
this.str = Preconditions.checkNotNull(str);
this.reference = Preconditions.checkNotNull(reference);
}
@Test
public void testOperationFailedException() {
- final Throwable cause = new Throwable( "mock cause" );
+ final Throwable cause = new Throwable("mock cause");
final RpcError rpcErrorShort = RpcResultBuilder.newError(RpcError.ErrorType.RPC, "tag", "msg");
final OperationFailedException operationFailedException1 = new OperationFailedException("error msg", cause,
rpcErrorShort);
- final OperationFailedException operationFailedException2 = new OperationFailedException("error msg", rpcErrorShort);
+ final OperationFailedException operationFailedException2 = new OperationFailedException("error msg",
+ rpcErrorShort);
assertEquals(operationFailedException1.getErrorList(), operationFailedException2.getErrorList());
assertTrue(operationFailedException1.toString().contains("error msg"));
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+
import java.net.URI;
import java.util.Date;
import org.junit.Test;
public class QNameTest {
- private final String namespace = "urn:foo", revision = "2013-12-24", localName = "bar";
- private final URI ns;
-
- public QNameTest() throws Exception {
- this.ns = new URI(namespace);
- }
+ private final String namespace = "urn:foo";
+ private final String revision = "2013-12-24";
+ private final String localName = "bar";
+ private final URI ns = URI.create(namespace);
@Test
public void testStringSerialization() throws Exception {
{
- QName qName = QName.create(namespace, revision, localName);
+ QName qname = QName.create(namespace, revision, localName);
assertEquals(QName.QNAME_LEFT_PARENTHESIS + namespace + QName.QNAME_REVISION_DELIMITER
- + revision + QName.QNAME_RIGHT_PARENTHESIS + localName, qName.toString());
- QName copied = QName.create(qName.toString());
- assertEquals(qName, copied);
+ + revision + QName.QNAME_RIGHT_PARENTHESIS + localName, qname.toString());
+ QName copied = QName.create(qname.toString());
+ assertEquals(qname, copied);
}
// no revision
{
- QName qName = new QName(ns, localName);
+ QName qname = new QName(ns, localName);
assertEquals(QName.QNAME_LEFT_PARENTHESIS + namespace + QName.QNAME_RIGHT_PARENTHESIS
- + localName, qName.toString());
- QName copied = QName.create(qName.toString());
- assertEquals(qName, copied);
+ + localName, qname.toString());
+ QName copied = QName.create(qname.toString());
+ assertEquals(qname, copied);
}
// no namespace nor revision
{
- QName qName = new QName(null, localName);
- assertEquals(localName, qName.toString());
- QName copied = QName.create(qName.toString());
- assertEquals(qName, copied);
+ QName qname = new QName(null, localName);
+ assertEquals(localName, qname.toString());
+ QName copied = QName.create(qname.toString());
+ assertEquals(qname, copied);
}
}
@Test
public void testCompareTo() throws Exception {
- String A = "a";
- String B = "b";
+ final String A = "a";
+ final String B = "b";
- QName a = QName.create(A);
- QName b = QName.create(A);
- assertTrue(a.compareTo(b) == 0);
- assertTrue(b.compareTo(a) == 0);
+ QName qa = QName.create(A);
+ QName qb = QName.create(A);
+ assertTrue(qa.compareTo(qb) == 0);
+ assertTrue(qb.compareTo(qa) == 0);
// compare with localName
- a = QName.create(A);
- b = QName.create(B);
- assertTrue(a.compareTo(b) < 0);
- assertTrue(b.compareTo(a) > 0);
+ qa = QName.create(A);
+ qb = QName.create(B);
+ assertTrue(qa.compareTo(qb) < 0);
+ assertTrue(qb.compareTo(qa) > 0);
// compare with namespace
- a = QName.create(A, revision, A);
- b = QName.create(B, revision, A);
- assertTrue(a.compareTo(b) < 0);
- assertTrue(b.compareTo(a) > 0);
+ qa = QName.create(A, revision, A);
+ qb = QName.create(B, revision, A);
+ assertTrue(qa.compareTo(qb) < 0);
+ assertTrue(qb.compareTo(qa) > 0);
// compare with 1 null namespace
- a = QName.create(null, QName.parseRevision(revision), A);
- b = QName.create(URI.create(A), QName.parseRevision(revision), A);
- assertTrue(a.compareTo(b) < 0);
- assertTrue(b.compareTo(a) > 0);
+ qa = QName.create(null, QName.parseRevision(revision), A);
+ qb = QName.create(URI.create(A), QName.parseRevision(revision), A);
+ assertTrue(qa.compareTo(qb) < 0);
+ assertTrue(qb.compareTo(qa) > 0);
// compare with both null namespace
- b = QName.create(null, QName.parseRevision(revision), A);
- assertTrue(a.compareTo(b) == 0);
- assertTrue(b.compareTo(a) == 0);
+ qb = QName.create(null, QName.parseRevision(revision), A);
+ assertTrue(qa.compareTo(qb) == 0);
+ assertTrue(qb.compareTo(qa) == 0);
// compare with revision
- a = QName.create(A, "2013-12-24", A);
- b = QName.create(A, "2013-12-25", A);
- assertTrue(a.compareTo(b) < 0);
- assertTrue(b.compareTo(a) > 0);
+ qa = QName.create(A, "2013-12-24", A);
+ qb = QName.create(A, "2013-12-25", A);
+ assertTrue(qa.compareTo(qb) < 0);
+ assertTrue(qb.compareTo(qa) > 0);
// compare with 1 null revision
- a = QName.create(URI.create(A), null, A);
- b = QName.create(URI.create(A), QName.parseRevision(revision), A);
- assertTrue(a.compareTo(b) < 0);
- assertTrue(b.compareTo(a) > 0);
+ qa = QName.create(URI.create(A), null, A);
+ qb = QName.create(URI.create(A), QName.parseRevision(revision), A);
+ assertTrue(qa.compareTo(qb) < 0);
+ assertTrue(qb.compareTo(qa) > 0);
// compare with both null revision
- b = QName.create(URI.create(A), null, A);
- assertTrue(a.compareTo(b) == 0);
- assertTrue(b.compareTo(a) == 0);
+ qb = QName.create(URI.create(A), null, A);
+ assertTrue(qa.compareTo(qb) == 0);
+ assertTrue(qb.compareTo(qa) == 0);
}
@Test
public void testQName() {
- final QName qName = QName.create(namespace, revision, localName);
- final QName qName1 = QName.create(namespace, localName);
- final QName qName2 = QName.create(qName1, localName);
- assertEquals(qName1, qName.withoutRevision());
- assertEquals(qName1, qName2);
- assertTrue(qName.isEqualWithoutRevision(qName1));
+ final QName qname = QName.create(namespace, revision, localName);
+ final QName qname1 = QName.create(namespace, localName);
+ final QName qname2 = QName.create(qname1, localName);
+ assertEquals(qname1, qname.withoutRevision());
+ assertEquals(qname1, qname2);
+ assertTrue(qname.isEqualWithoutRevision(qname1));
assertNotNull(QName.formattedRevision(new Date()));
- assertNotNull(qName.hashCode());
- assertEquals(qName, qName.intern());
+ assertNotNull(qname.hashCode());
+ assertEquals(qname, qname.intern());
}
@Test
public void testQNameModule() {
- final QNameModule qNameModule = QNameModule.create(ns, new Date());
- assertNotNull(qNameModule.toString());
- assertNotNull(qNameModule.getRevisionNamespace());
+ final QNameModule qnameModule = QNameModule.create(ns, new Date());
+ assertNotNull(qnameModule.toString());
+ assertNotNull(qnameModule.getRevisionNamespace());
}
private static void assertLocalNameFails(final String localName) {
new QName(null, localName);
fail("Local name should fail:" + localName);
} catch (IllegalArgumentException e) {
+ // Expected
}
}
-}
\ No newline at end of file
+}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
@Test
public void testSuccess() {
- RpcResult<String> result = RpcResultBuilder.<String>success().withResult( "foo" ).build();
- verifyRpcResult( result, true, "foo" );
- assertNotNull( "getErrors returned null", result.getErrors() );
- assertEquals( "getErrors size", 0, result.getErrors().size() );
+ RpcResult<String> result = RpcResultBuilder.<String>success().withResult("foo").build();
+ verifyRpcResult(result, true, "foo");
+ assertNotNull("getErrors returned null", result.getErrors());
+ assertEquals("getErrors size", 0, result.getErrors().size());
- result = RpcResultBuilder.success( "bar" ).build();
- verifyRpcResult( result, true, "bar" );
+ result = RpcResultBuilder.success("bar").build();
+ verifyRpcResult(result, true, "bar");
}
@Test
public void testFailed() {
- Throwable cause = new Throwable( "mock cause" );
- Throwable cause2 = new Throwable( "mock cause2" );
+ Throwable cause = new Throwable("mock cause");
+ Throwable cause2 = new Throwable("mock cause2");
RpcResult<String> result = RpcResultBuilder.<String>failed()
- .withError( ErrorType.PROTOCOL, "error message 1" )
- .withError( ErrorType.APPLICATION, "lock_denied", "error message 2" )
- .withError( ErrorType.RPC, "in-use", "error message 3", "my-app-tag", "my-info", cause )
- .withError( ErrorType.TRANSPORT, "error message 4", cause2 )
+ .withError(ErrorType.PROTOCOL, "error message 1")
+ .withError(ErrorType.APPLICATION, "lock_denied", "error message 2")
+ .withError(ErrorType.RPC, "in-use", "error message 3", "my-app-tag", "my-info", cause)
+ .withError(ErrorType.TRANSPORT, "error message 4", cause2)
.build();
- verifyRpcResult( result, false, null );
- verifyRpcError( result, 0, ErrorSeverity.ERROR, ErrorType.PROTOCOL, "operation-failed",
- "error message 1", null, null, null );
- verifyRpcError( result, 1, ErrorSeverity.ERROR, ErrorType.APPLICATION, "lock_denied",
- "error message 2", null, null, null );
- verifyRpcError( result, 2, ErrorSeverity.ERROR, ErrorType.RPC, "in-use",
- "error message 3", "my-app-tag", "my-info", cause );
- verifyRpcError( result, 3, ErrorSeverity.ERROR, ErrorType.TRANSPORT, "operation-failed",
- "error message 4", null, null, cause2 );
- assertEquals( "getErrors size", 4, result.getErrors().size() );
+ verifyRpcResult(result, false, null);
+ verifyRpcError(result, 0, ErrorSeverity.ERROR, ErrorType.PROTOCOL, "operation-failed",
+ "error message 1", null, null, null);
+ verifyRpcError(result, 1, ErrorSeverity.ERROR, ErrorType.APPLICATION, "lock_denied",
+ "error message 2", null, null, null);
+ verifyRpcError(result, 2, ErrorSeverity.ERROR, ErrorType.RPC, "in-use",
+ "error message 3", "my-app-tag", "my-info", cause);
+ verifyRpcError(result, 3, ErrorSeverity.ERROR, ErrorType.TRANSPORT, "operation-failed",
+ "error message 4", null, null, cause2);
+ assertEquals("getErrors size", 4, result.getErrors().size());
}
@Test
public void testWithWarnings() {
- Throwable cause = new Throwable( "mock cause" );
+ Throwable cause = new Throwable("mock cause");
RpcResult<String> result = RpcResultBuilder.<String>success()
- .withWarning( ErrorType.APPLICATION, "lock_denied", "message 1" )
- .withWarning( ErrorType.RPC, "in-use", "message 2", "my-app-tag", "my-info", cause )
+ .withWarning(ErrorType.APPLICATION, "lock_denied", "message 1")
+ .withWarning(ErrorType.RPC, "in-use", "message 2", "my-app-tag", "my-info", cause)
.build();
- verifyRpcResult( result, true, null );
- verifyRpcError( result, 0, ErrorSeverity.WARNING, ErrorType.APPLICATION, "lock_denied",
- "message 1", null, null, null );
- verifyRpcError( result, 1, ErrorSeverity.WARNING, ErrorType.RPC, "in-use",
- "message 2", "my-app-tag", "my-info", cause );
- assertEquals( "getErrors size", 2, result.getErrors().size() );
+ verifyRpcResult(result, true, null);
+ verifyRpcError(result, 0, ErrorSeverity.WARNING, ErrorType.APPLICATION, "lock_denied",
+ "message 1", null, null, null);
+ verifyRpcError(result, 1, ErrorSeverity.WARNING, ErrorType.RPC, "in-use",
+ "message 2", "my-app-tag", "my-info", cause);
+ assertEquals("getErrors size", 2, result.getErrors().size());
}
@Test
public void testFrom() {
- Throwable cause = new Throwable( "mock cause" );
+ Throwable cause = new Throwable("mock cause");
RpcResult<String> result = RpcResultBuilder.<String>success()
- .withResult( "foo" )
- .withWarning( ErrorType.RPC, "in-use", "message", "my-app-tag", "my-info", cause )
+ .withResult("foo")
+ .withWarning(ErrorType.RPC, "in-use", "message", "my-app-tag", "my-info", cause)
.build();
- RpcResult<String> copy = RpcResultBuilder.from( result )
- .withError( ErrorType.PROTOCOL, "error message" )
+ RpcResult<String> copy = RpcResultBuilder.from(result)
+ .withError(ErrorType.PROTOCOL, "error message")
.build();
- verifyRpcResult( copy, true, "foo" );
- verifyRpcError( copy, 0, ErrorSeverity.WARNING, ErrorType.RPC, "in-use",
- "message", "my-app-tag", "my-info", cause );
- verifyRpcError( copy, 1, ErrorSeverity.ERROR, ErrorType.PROTOCOL, "operation-failed",
- "error message", null, null, null );
+ verifyRpcResult(copy, true, "foo");
+ verifyRpcError(copy, 0, ErrorSeverity.WARNING, ErrorType.RPC, "in-use",
+ "message", "my-app-tag", "my-info", cause);
+ verifyRpcError(copy, 1, ErrorSeverity.ERROR, ErrorType.PROTOCOL, "operation-failed",
+ "error message", null, null, null);
}
@Test
public void testWithRpcErrors() {
- Throwable cause = new Throwable( "mock cause" );
+ Throwable cause = new Throwable("mock cause");
RpcResult<String> result = RpcResultBuilder.<String>failed()
- .withWarning( ErrorType.RPC, "in-use", "message", "my-app-tag", "my-info", cause )
- .withError( ErrorType.PROTOCOL, "error message" )
+ .withWarning(ErrorType.RPC, "in-use", "message", "my-app-tag", "my-info", cause)
+ .withError(ErrorType.PROTOCOL, "error message")
.build();
RpcResult<String> result2 = RpcResultBuilder.<String>failed()
- .withRpcErrors( result.getErrors() )
+ .withRpcErrors(result.getErrors())
.build();
- verifyRpcError( result2, 0, ErrorSeverity.WARNING, ErrorType.RPC, "in-use",
- "message", "my-app-tag", "my-info", cause );
- verifyRpcError( result2, 1, ErrorSeverity.ERROR, ErrorType.PROTOCOL, "operation-failed",
- "error message", null, null, null );
+ verifyRpcError(result2, 0, ErrorSeverity.WARNING, ErrorType.RPC, "in-use",
+ "message", "my-app-tag", "my-info", cause);
+ verifyRpcError(result2, 1, ErrorSeverity.ERROR, ErrorType.PROTOCOL, "operation-failed",
+ "error message", null, null, null);
}
@Test
"info", null);
rpcResultBuilder.withRpcError(rpcErrorShort);
final RpcResult<Object> rpcResult = rpcResultBuilder.build();
- final RpcResultBuilder<RpcResult<Object>> rpcResultRpcResultBuilder1 = RpcResultBuilder.success
- (rpcResultBuilder);
- final RpcResultBuilder<RpcResult<Object>> rpcResultRpcResultBuilder2 = rpcResultRpcResultBuilder1.withResult
- (rpcResultBuilder);
+ final RpcResultBuilder<RpcResult<Object>> rpcResultRpcResultBuilder1 = RpcResultBuilder.success(
+ rpcResultBuilder);
+ final RpcResultBuilder<RpcResult<Object>> rpcResultRpcResultBuilder2 = rpcResultRpcResultBuilder1.withResult(
+ rpcResultBuilder);
assertEquals(rpcErrorShort.getErrorType(), rpcErrorShortWarn.getErrorType());
assertEquals(rpcErrorLong.getErrorType(), rpcErrorLongWarn.getErrorType());
assertEquals(rpcResultRpcResultBuilder1, rpcResultRpcResultBuilder2);
assertNotNull(rpcResultBuilder.buildFuture());
- assertEquals("RpcResult [successful=true, result=null, errors=[RpcError [message=msg, severity=ERROR, " +
- "errorType=RPC, tag=tag, applicationTag=null, info=null, cause=null]]]", rpcResult.toString());
+ assertEquals("RpcResult [successful=true, result=null, errors=[RpcError [message=msg, severity=ERROR, "
+ + "errorType=RPC, tag=tag, applicationTag=null, info=null, cause=null]]]", rpcResult.toString());
}
@SuppressWarnings("unchecked")
@Test
public void testSerialization() throws Exception {
- RpcResult<String> result = RpcResultBuilder.<String>success().withResult( "foo" ).build();
+ RpcResult<String> result = RpcResultBuilder.<String>success().withResult("foo").build();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
verifyRpcResult(clone, true, "foo");
- Throwable cause = new Throwable( "mock cause" );
+ Throwable cause = new Throwable("mock cause");
result = RpcResultBuilder.<String>failed()
- .withError( ErrorType.RPC, "in-use", "error message", "my-app-tag", "my-info", cause )
+ .withError(ErrorType.RPC, "in-use", "error message", "my-app-tag", "my-info", cause)
.build();
bos = new ByteArrayOutputStream();
clone = (RpcResult<String>) in.readObject();
verifyRpcResult(clone, false, null);
- verifyRpcError( result, 0, ErrorSeverity.ERROR, ErrorType.RPC, "in-use",
- "error message", "my-app-tag", "my-info", cause );
+ verifyRpcError(result, 0, ErrorSeverity.ERROR, ErrorType.RPC, "in-use",
+ "error message", "my-app-tag", "my-info", cause);
}
- void verifyRpcError( final RpcResult<?> result, final int errorIndex, final ErrorSeverity expSeverity,
+ void verifyRpcError(final RpcResult<?> result, final int errorIndex, final ErrorSeverity expSeverity,
final ErrorType expErrorType, final String expTag, final String expMessage, final String expAppTag,
- final String expInfo, final Throwable expCause ) {
-
- List<RpcError> errors = new ArrayList<>( result.getErrors() );
- assertTrue( "Expected error at index " + errorIndex + " not found",
- errorIndex < errors.size() );
- RpcError error = errors.get( errorIndex );
- assertEquals( "getSeverity", expSeverity, error.getSeverity() );
- assertEquals( "getErrorType", expErrorType, error.getErrorType() );
- assertEquals( "getTag", expTag, error.getTag() );
- assertEquals( "getMessage", expMessage, error.getMessage() );
- assertEquals( "getApplicationTag", expAppTag, error.getApplicationTag() );
- assertEquals( "getInfo", expInfo, error.getInfo() );
- assertEquals( "getCause", expCause, error.getCause() );
+ final String expInfo, final Throwable expCause) {
+
+ List<RpcError> errors = new ArrayList<>(result.getErrors());
+ assertTrue("Expected error at index " + errorIndex + " not found",
+ errorIndex < errors.size());
+ RpcError error = errors.get(errorIndex);
+ assertEquals("getSeverity", expSeverity, error.getSeverity());
+ assertEquals("getErrorType", expErrorType, error.getErrorType());
+ assertEquals("getTag", expTag, error.getTag());
+ assertEquals("getMessage", expMessage, error.getMessage());
+ assertEquals("getApplicationTag", expAppTag, error.getApplicationTag());
+ assertEquals("getInfo", expInfo, error.getInfo());
+ assertEquals("getCause", expCause, error.getCause());
}
- void verifyRpcResult( final RpcResult<?> result, final boolean expSuccess, final Object expValue ) {
- assertEquals( "isSuccessful", expSuccess, result.isSuccessful() );
- assertEquals( "getResult", expValue, result.getResult() );
+ void verifyRpcResult(final RpcResult<?> result, final boolean expSuccess, final Object expValue) {
+ assertEquals("isSuccessful", expSuccess, result.isSuccessful());
+ assertEquals("getResult", expValue, result.getResult());
}
-}
\ No newline at end of file
+}
import org.opendaylight.yangtools.yang.common.QName;
/**
- *
* Container of attributes, which may be attached to nodes.
- *
*/
public interface AttributesContainer {
-
/**
* Returns immutable map of QName and value of the attribute.
*
Map<QName, String> getAttributes();
/**
- * Returns attribute value by supplied QName
- *
+ * Returns attribute value by supplied QName.
*
* @param name Attribute name
* @return Value of attribute if present, null otherwise.
*/
Object getAttributeValue(QName name);
-
}
import org.opendaylight.yangtools.util.HashCodeBuilder;
final class FixedYangInstanceIdentifier extends YangInstanceIdentifier implements Cloneable {
- static final FixedYangInstanceIdentifier EMPTY_INSTANCE = new FixedYangInstanceIdentifier(ImmutableList.of(), new HashCodeBuilder<>().build());
+ static final FixedYangInstanceIdentifier EMPTY_INSTANCE = new FixedYangInstanceIdentifier(ImmutableList.of(),
+ new HashCodeBuilder<>().build());
private static final long serialVersionUID = 1L;
+
private final ImmutableList<PathArgument> path;
private transient volatile YangInstanceIdentifier parent;
@Override
public PathArgument getLastPathArgument() {
- return path.isEmpty()? null : path.get(path.size() - 1);
+ return path.isEmpty() ? null : path.get(path.size() - 1);
}
@Nonnull
// TODO rename to ModifyOperation
/**
- * https://tools.ietf.org/html/rfc6241#section-7.2
+ * See https://tools.ietf.org/html/rfc6241#section-7.2.
*/
public enum ModifyAction {
MERGE(true), REPLACE(true), CREATE(false), DELETE(false), REMOVE(false), NONE(true, false);
public static ModifyAction fromXmlValue(final String xmlNameOfAction) {
switch (xmlNameOfAction) {
- case "merge":
- return MERGE;
- case "replace":
- return REPLACE;
- case "remove":
- return REMOVE;
- case "delete":
- return DELETE;
- case "create":
- return CREATE;
- case "none":
- return NONE;
- default:
- throw new IllegalArgumentException("Unknown operation " + xmlNameOfAction + " available operations "
- + Arrays.toString(ModifyAction.values()));
+ case "merge":
+ return MERGE;
+ case "replace":
+ return REPLACE;
+ case "remove":
+ return REMOVE;
+ case "delete":
+ return DELETE;
+ case "create":
+ return CREATE;
+ case "none":
+ return NONE;
+ default:
+ throw new IllegalArgumentException("Unknown operation " + xmlNameOfAction + " available operations "
+ + Arrays.toString(ModifyAction.values()));
}
}
private final boolean asDefaultPermitted;
private final boolean onElementPermitted;
- private ModifyAction(final boolean asDefaultPermitted, final boolean onElementPermitted) {
+ ModifyAction(final boolean asDefaultPermitted, final boolean onElementPermitted) {
this.asDefaultPermitted = asDefaultPermitted;
this.onElementPermitted = onElementPermitted;
}
- private ModifyAction(final boolean asDefaultPermitted) {
+ ModifyAction(final boolean asDefaultPermitted) {
this(asDefaultPermitted, true);
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public final boolean addAll(@Nonnull final Collection<? extends PathArgument> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean removeAll(@Nonnull final Collection<?> c) {
+ @SuppressWarnings("checkstyle:parameterName")
+ public final boolean addAll(final int index, final Collection<? extends PathArgument> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean retainAll(@Nonnull final Collection<?> c) {
+ @SuppressWarnings("checkstyle:parameterName")
+ public final boolean removeAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
- public final void clear() {
+ @SuppressWarnings("checkstyle:parameterName")
+ public final boolean retainAll(@Nonnull final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean addAll(final int index, final Collection<? extends PathArgument> c) {
+ public final void clear() {
throw new UnsupportedOperationException();
}
}
private final List<PathArgument> base;
private final List<PathArgument> stack;
- public StackedPathArguments(@Nonnull final YangInstanceIdentifier base, @Nonnull final List<PathArgument> stack) {
+ StackedPathArguments(@Nonnull final YangInstanceIdentifier base, @Nonnull final List<PathArgument> stack) {
Verify.verify(!stack.isEmpty());
this.base = base.getPathArguments();
this.stack = stack;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
final PathArgument srch = (PathArgument) Preconditions.checkNotNull(o);
return stack.contains(srch) || base.contains(srch);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public int indexOf(final Object o) {
final PathArgument srch = (PathArgument) Preconditions.checkNotNull(o);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public int lastIndexOf(final Object o) {
final PathArgument srch = (PathArgument) Preconditions.checkNotNull(o);
return ret;
}
-
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public boolean contains(final Object o) {
final PathArgument srch = (PathArgument) Preconditions.checkNotNull(o);
return Iterators.contains(iterator(), srch);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public int indexOf(final Object o) {
final PathArgument srch = (PathArgument) Preconditions.checkNotNull(o);
return super.indexOf(srch);
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public int lastIndexOf(final Object o) {
final PathArgument srch = (PathArgument) Preconditions.checkNotNull(o);
private transient volatile StackedPathArguments pathArguments;
private transient volatile StackedReversePathArguments reversePathArguments;
- StackedYangInstanceIdentifier(final YangInstanceIdentifier parent, final PathArgument pathArgument, final int hash) {
+ StackedYangInstanceIdentifier(final YangInstanceIdentifier parent, final PathArgument pathArgument,
+ final int hash) {
super(hash);
this.parent = Preconditions.checkNotNull(parent);
this.pathArgument = Preconditions.checkNotNull(pathArgument);
* which conceptually is XPath expression minimized to uniquely identify element
* in data tree which conforms to constraints maintained by YANG Model,
* effectively this makes Instance Identifier a path to element in data tree.
- * </p>
+ *
* <p>
* Constraints put in YANG specification on instance-identifier allowed it to be
* effectively represented in Java and it's evaluation does not require
* full-blown XPath processor.
- * </p>
- * <h3>Path Arguments</h3>
+ *
* <p>
+ * <h3>Path Arguments</h3>
* Path to the node represented in instance identifier consists of
* {@link PathArgument} which carries necessary information to uniquely identify
* node on particular level in the subtree.
- * </p>
+ *
* <ul>
* <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
* <code>0..1</code> in particular subtree in data tree.</li>
* <code>augmentation</code> node.</li>
* </ul>
*
- *
* @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
*/
public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
}
@Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
+
@Nonnull abstract Collection<PathArgument> tryPathArguments();
+
@Nonnull abstract Collection<PathArgument> tryReversePathArguments();
/**
* @return Ancestor {@link YangInstanceIdentifier}
* @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
*/
- @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
+ @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
/**
* Returns an ordered iteration of path arguments.
return create(Arrays.asList(path));
}
- @Override
- public final int hashCode() {
- /*
- * The caching is safe, since the object contract requires
- * immutability of the object and all objects referenced from this
- * object.
- * Used lists, maps are immutable. Path Arguments (elements) are also
- * immutable, since the PathArgument contract requires immutability.
- */
- return hash;
- }
-
boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
}
}
/**
- * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
+ * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
*
* @param name QName of {@link NodeIdentifier}
* @return Instance Identifier with additional path argument added to the end.
}
/**
- *
- * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
+ * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
*
* @param arg Path argument which should be added to the end
* @return Instance Identifier with additional path argument added to the end.
return ret;
}
+ @Override
+ public final int hashCode() {
+ /*
+ * The caching is safe, since the object contract requires
+ * immutability of the object and all objects referenced from this
+ * object.
+ * Used lists, maps are immutable. Path Arguments (elements) are also
+ * immutable, since the PathArgument contract requires immutability.
+ */
+ return hash;
+ }
+
private static int hashCode(final Object value) {
if (value == null) {
return 0;
// Static factories & helpers
/**
- * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
+ * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
+ * QName.
*
* @param name QName of first node identifier
* @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
}
/**
- *
* Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
*
* @param origin InstanceIdentifier from which path arguments are copied.
}
/**
- * Path argument / component of InstanceIdentifier
- *
+ * Path argument / component of InstanceIdentifier.
* Path argument uniquely identifies node in data tree on particular
* level.
+ *
* <p>
* This interface itself is used as common parent for actual
* path arguments types and should not be implemented by user code.
+ *
* <p>
* Path arguments SHOULD contain only minimum of information
* required to uniquely identify node on particular subtree level.
*
+ * <p>
* For actual path arguments types see:
* <ul>
* <li>{@link NodeIdentifier} - Identifier of container or leaf
* If applicable returns unique QName of data node as defined in YANG
* Schema.
*
+ * <p>
* This method may return null, if the corresponding schema node, does
* not have QName associated, such as in cases of augmentations.
*
String toRelativeString(PathArgument previous);
}
- private static abstract class AbstractPathArgument implements PathArgument {
+ private abstract static class AbstractPathArgument implements PathArgument {
private static final long serialVersionUID = -4546547994250849340L;
private final QName nodeType;
private transient int hashValue;
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public int compareTo(@Nonnull final PathArgument o) {
return nodeType.compareTo(o.getNodeType());
}
}
/**
- * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
- * particular subtree.
+ * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
+ * node in particular subtree.
*
+ * <p>
* Augmentation is uniquely identified by set of all possible child nodes.
* This is possible
* to identify instance of augmentation,
* statement must not add multiple nodes from same namespace
* / module to the target node.
*
- *
* @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
*/
public static final class AugmentationIdentifier implements PathArgument {
}
/**
- *
* Construct new augmentation identifier using supplied set of possible
- * child nodes
+ * child nodes.
*
* @param childNames
* Set of possible child nodes.
}
/**
- * Returns set of all possible child nodes
+ * Returns set of all possible child nodes.
*
* @return set of all possible child nodes.
*/
}
@Override
- public boolean equals(final Object o) {
- if (this == o) {
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (!(o instanceof AugmentationIdentifier)) {
+ if (!(obj instanceof AugmentationIdentifier)) {
return false;
}
- AugmentationIdentifier that = (AugmentationIdentifier) o;
+ AugmentationIdentifier that = (AugmentationIdentifier) obj;
return childNames.equals(that.childNames);
}
}
@Override
+ @SuppressWarnings("checkstyle:parameterName")
public int compareTo(@Nonnull final PathArgument o) {
if (!(o instanceof AugmentationIdentifier)) {
return -1;
if (thisSize == otherSize) {
Iterator<QName> otherIterator = otherChildNames.iterator();
for (QName name : childNames) {
- int c = name.compareTo(otherIterator.next());
- if (c != 0) {
- return c;
+ int child = name.compareTo(otherIterator.next());
+ if (child != 0) {
+ return child;
}
}
return 0;
}
/**
- * Fluent Builder of Instance Identifier instances
+ * Fluent Builder of Instance Identifier instances.
*/
public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
/**
InstanceIdentifierBuilder node(QName nodeType);
/**
- * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
+ * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
+ * instance identifier.
*
* @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
* @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
/**
- *
- * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
+ * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
*
* @return {@link YangInstanceIdentifier}
*/
private final HashCodeBuilder<PathArgument> hash;
private final List<PathArgument> path;
- public YangInstanceIdentifierBuilder() {
+ YangInstanceIdentifierBuilder() {
this.hash = new HashCodeBuilder<>();
this.path = new ArrayList<>();
}
- public YangInstanceIdentifierBuilder(final Iterable<PathArgument> prefix, final int hash) {
+ YangInstanceIdentifierBuilder(final Iterable<PathArgument> prefix, final int hash) {
this.path = Lists.newArrayList(prefix);
this.hash = new HashCodeBuilder<>(hash);
}
import org.opendaylight.yangtools.concepts.Codec;
-public interface BinaryCodec<T> extends Codec<T, byte[]>{
+public interface BinaryCodec<T> extends Codec<T, byte[]> {
@Override
T serialize(byte[] data);
package org.opendaylight.yangtools.yang.data.api.codec;
import java.util.Set;
-
import org.opendaylight.yangtools.concepts.Codec;
-public interface BitsCodec<T> extends Codec<T, Set<String>>{
+public interface BitsCodec<T> extends Codec<T, Set<String>> {
@Override
T serialize(Set<String> data);
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
/**
- *
- * Codec which serializes / deserializes InstanceIdentifier
+ * Codec which serializes / deserializes InstanceIdentifier.
*
* @param <T> Target type
*/
public interface InstanceIdentifierCodec<T> extends Codec<T,YangInstanceIdentifier> {
+
@Override
T serialize(YangInstanceIdentifier data);
import org.opendaylight.yangtools.concepts.Codec;
/**
- *
- * FIXME: Should be changed to {@link UnsignedLong}
+ * FIXME: Should be changed to {@link UnsignedLong}.
*
* @author ttkacik
*
* @param <T>
* Output type of serialization.
*/
-public interface Uint32Codec<T> extends Codec<T,Long> {
+public interface Uint32Codec<T> extends Codec<T, Long> {
@Override
T serialize(Long data);
import org.opendaylight.yangtools.concepts.Codec;
/**
- * FIXME: Should be changed to {@link UnsignedLong}
+ * FIXME: Should be changed to {@link UnsignedLong}.
*
* @author ttkacik
*
* @param <T>
* Output type of serialization.
*/
-public interface Uint64Codec<T> extends Codec<T,BigInteger> {
+public interface Uint64Codec<T> extends Codec<T, BigInteger> {
@Override
T serialize(BigInteger data);
import org.opendaylight.yangtools.concepts.Codec;
/**
- *
- * FIXME: Should be changed to UnsignedByte
+ * FIXME: Should be changed to UnsignedByte.
*
* @author ttkacik
*
* @param <T>
* Output type of serialization.
*/
-public interface Uint8Codec<T> extends Codec<T,Short> {
+public interface Uint8Codec<T> extends Codec<T, Short> {
@Override
T serialize(Short data);
NodeIdentifier getIdentifier();
/**
+ * Return value represented as a DOMSource. Returned source contains top level element
+ * that duplicates the anyxml node.
+ *
* @return anyxml node value represented as DOMSource.
- * Returned source contains top level element that duplicates the anyxml node.
*/
@Override
DOMSource getValue();
/**
* Data instance of <code>augment</code> associated with parent node.
*
+ * <p>
* Augmentation is addition of subtree defined by other external YANG Model and
* is schema for subtree is described by instance of {@link AugmentationSchema}
* associated with parent node of this node.
*
+ * <p>
* Augmentation node MUST NOT be direct child of other augmentation node.
- *
*/
public interface AugmentationNode extends MixinNode, DataContainerNode<AugmentationIdentifier>,
DataContainerChild<AugmentationIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
/**
- * Gets identifier of augmentation node
- *
- * Returned identifier of augmentation node contains all possible
+ * Gets identifier of augmentation node. Returned identifier of augmentation node contains all possible
* direct child QNames.
*
- * This is sufficient to identify instance of augmentation,
- * since RFC6020 states that <code>augment</code> that augment
- * statement must not add multiple nodes from same namespace
- * / module
- * to the target node.
+ * <p>
+ * This is sufficient to identify instance of augmentation, since RFC6020 states that <code>augment</code>
+ * that augment statement must not add multiple nodes from same namespace / module to the target node.
*
* @return Identifier which uniquelly identifies augmentation in particular subtree.
- *
*/
@Override
AugmentationIdentifier getIdentifier();
/**
* Node representing data instance of <code>choice</code>.
*
+ * <p>
* Choice node is instance of one of possible alternatives, from which only one is allowed to exist at one time in
* particular context of parent node.
*
+ * <p>
* YANG Model and schema for choice is described by instance of
* {@link org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode}.
*
+ * <p>
* Valid alternatives of subtree are described by instances of
* {@link org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode}, which are retrieved via
* {@link org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode#getCases()}.
*/
-public interface ChoiceNode extends //
- MixinNode, //
- DataContainerNode<NodeIdentifier>,
+public interface ChoiceNode extends MixinNode, DataContainerNode<NodeIdentifier>,
DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
- * Data subtree with cardinality 0..1 in the context of parent node
+ * Data subtree with cardinality 0..1 in the context of parent node.
*
+ * <p>
* Node which does not have value but contains valid {@link DataContainerChild} nodes.
*
- * Schema of this node is described by instance of {@link org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode}.
- *
+ * <p>
+ * Schema of this node is described by instance of
+ * {@link org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode}.
*/
-public interface ContainerNode extends //
- AttributesContainer,
- DataContainerNode<NodeIdentifier>,
+public interface ContainerNode extends AttributesContainer, DataContainerNode<NodeIdentifier>,
DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
- *
* Marker interface for direct children of {@link DataContainerNode}.
*
* <h3>Implementation notes</h3>
* <li>{@link ChoiceNode}
* <li>{@link MapNode}
* <li>{@link AugmentationNode}
- *</ul>
+ * </ul>
*
* @param <K> Path Argument Type which is used to identify node
* @param <V> Value type
*/
public interface DataContainerChild<K extends PathArgument,V> extends NormalizedNode<K, V> {
-
@Override
K getIdentifier();
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
- *
* Abstract node which does not have value but contains valid {@link DataContainerChild} nodes.
- *
* Schema of this node is described by instance of {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer}.
*
+ * <p>
* <h2>Implementation notes</h2>
* This interface should not be implemented directly, but rather implementing one of it's subclasses
* <ul>
*/
public interface DataContainerNode<K extends PathArgument> extends //
NormalizedNodeContainer<K, PathArgument, DataContainerChild<? extends PathArgument, ?>> {
-
/**
- * Returns iteration of all child nodes
- *
+ * Returns iteration of all child nodes.
* Order of returned child nodes may be defined by subinterfaces.
*
- * <b>Implementation Notes:</b>
* <p>
+ * <b>Implementation Notes:</b>
* All nodes returned in this iterable, MUST also be accessible via
* {@link #getChild(PathArgument)} using their associated identifier.
*
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
/**
- * Leaf node with multiplicity 0..1
+ * Leaf node with multiplicity 0..1.
*
+ * <p>
* Leaf node has a value, but no child nodes in the data tree, schema
* for leaf node and its value is described by {@link org.opendaylight.yangtools.yang.model.api.LeafSchemaNode}.
*
*/
public interface LeafNode<T> extends AttributesContainer, DataContainerChild<NodeIdentifier, T>,
ValueNode<NodeIdentifier, T> {
-
/**
- * Returns value of this leaf node
+ * Returns value of this leaf node.
*
* @return Returned value of this leaf node. Value SHOULD meet criteria defined by schema.
*/
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
/**
+ * Leaf node with multiplicity 0...n.
*
- * Leaf node with multiplicity 0...n
- *
+ * <p>
* Leaf node has a value, but no child nodes in the data tree, schema
* for leaf node and its value is described by
* {@link org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode}.
*/
public interface LeafSetEntryNode<T> extends AttributesContainer, NormalizedNode<NodeWithValue, T>,
ValueNode<NodeWithValue, T> {
-
/**
* Returns {@link NodeWithValue} which identifies this leaf set entry.
- *
* Returned {@link NodeWithValue} contains same value as this node.
*
+ * <p>
* <h3>Implementation notes</h3> Invocation of
* {@link NodeWithValue#getValue()} on returned instance of
* {@link NodeWithValue} must returns
* following condition is allways met:
* <code>true == this.getIdentifier().getValue().equals(this.getValue())</code>
*
- *
* @return {@link NodeWithValue} which identifies this leaf set entry.
*/
@Override
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
/**
- * Node representing set of simple leaf nodes.
+ * Node representing set of simple leaf nodes. Node containing instances of {@link LeafSetEntryNode}.
*
- * Node containing instances of {@link LeafSetEntryNode}
- *
- * Schema and semantics of this node are described by instance of {@link org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode}.
+ * <p>
+ * Schema and semantics of this node are described by instance of
+ * {@link org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode}.
*
* @param <T> Type of leaf node values.
*/
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
/**
- *
* Instance of Map entry, this node does not contains value, but child nodes.
- *
*/
public interface MapEntryNode extends AttributesContainer, DataContainerNode<NodeIdentifierWithPredicates> {
-
/**
- *
* Returns identifier of this node in parent map node
*
+ * <p>
* Contents of identifier is defined by <code>key</code> (
* {@link org.opendaylight.yangtools.yang.model.api.ListSchemaNode#getKeyDefinition()}
* ) statement in YANG schema for associated list item and child {@link LeafNode}s
*/
@Override
NodeIdentifierWithPredicates getIdentifier();
-
}
* Containment node, which contains {@link MapEntryNode} of the same type, which may
* be quickly retrieved using key.
*
+ * <p>
* This node maps to the list node in YANG schema, schema and semantics of this node,
* its children and key construction is defined by YANG <code>list</code>
* statement and its <code>key</code> and <code>ordered-by</code> substatements.
- *
*/
-public interface MapNode extends //
- MixinNode,
- DataContainerChild<NodeIdentifier, Collection<MapEntryNode>>,
+public interface MapNode extends MixinNode, DataContainerChild<NodeIdentifier, Collection<MapEntryNode>>,
NormalizedNodeContainer<NodeIdentifier, NodeIdentifierWithPredicates, MapEntryNode> {
}
package org.opendaylight.yangtools.yang.data.api.schema;
/**
- *
* Marker interface for nodes, which are mixins - their content
* belongs to parent node and in serialized form this node
* does not exists, but it's children are present.
- *
*/
public interface MixinNode {
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
- *
* Node which is normalized according to the YANG schema
* is identifiable by a {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier}.
*
- * See subinterfaces of this interface for concretization
- * of node.
+ * <p>
+ * See subinterfaces of this interface for concretization of node.
*
* @param <K> Local identifier of node
* @param <V> Value of node
/**
* Node which is not leaf, but has child {@link NormalizedNode}s as its valzue.
*
- *
+ * <p>
* NormalizedNodeContainer does not have a value, but it has a child
* nodes. Definition of possible and valid child nodes is introduced
* in subclasses of this interface.
*
+ * <p>
* This interface should not be used directly, but rather use of of derived subinterfaces
* such as {@link DataContainerNode}, {@link MapNode}, {@link LeafSetNode}.
*
* @param <V>
* Child Node type
*/
-public interface NormalizedNodeContainer<I extends PathArgument, K extends PathArgument, V extends NormalizedNode<? extends K, ?>>
- extends NormalizedNode<I, Collection<V>> {
+public interface NormalizedNodeContainer<I extends PathArgument, K extends PathArgument,
+ V extends NormalizedNode<? extends K, ?>> extends NormalizedNode<I, Collection<V>> {
@Override
I getIdentifier();
throw new UnsupportedOperationException("Utility class should not be instantiated");
}
- public static Optional<NormalizedNode<?, ?>> findNode(final YangInstanceIdentifier rootPath, final NormalizedNode<?, ?> rootNode, final YangInstanceIdentifier childPath) {
+ public static Optional<NormalizedNode<?, ?>> findNode(final YangInstanceIdentifier rootPath,
+ final NormalizedNode<?, ?> rootNode, final YangInstanceIdentifier childPath) {
final Optional<YangInstanceIdentifier> relativePath = childPath.relativeTo(rootPath);
return relativePath.isPresent() ? findNode(rootNode, relativePath.get()) : Optional.absent();
}
- public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent, final Iterable<PathArgument> relativePath) {
+ public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent,
+ final Iterable<PathArgument> relativePath) {
checkNotNull(parent, "Parent must not be null");
checkNotNull(relativePath, "Relative path must not be null");
return currentNode;
}
- public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent, final PathArgument... relativePath) {
+ public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent,
+ final PathArgument... relativePath) {
return findNode(parent, Arrays.asList(relativePath));
}
- public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent, final Iterable<PathArgument> relativePath) {
+ public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent,
+ final Iterable<PathArgument> relativePath) {
return findNode(Optional.fromNullable(parent), relativePath);
}
- public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent, final PathArgument... relativePath) {
+ public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent,
+ final PathArgument... relativePath) {
return findNode(parent, Arrays.asList(relativePath));
}
- public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree, final YangInstanceIdentifier path) {
+ public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree,
+ final YangInstanceIdentifier path) {
checkNotNull(tree, "Tree must not be null");
checkNotNull(path, "Path must not be null");
}
@SuppressWarnings({ "unchecked", "rawtypes" })
- public static Optional<NormalizedNode<?, ?>> getDirectChild(final NormalizedNode<?, ?> node, final PathArgument pathArg) {
+ public static Optional<NormalizedNode<?, ?>> getDirectChild(final NormalizedNode<?, ?> node,
+ final PathArgument pathArg) {
if (node instanceof LeafNode<?> || node instanceof LeafSetEntryNode<?>) {
return Optional.absent();
} else if (node instanceof DataContainerNode<?>) {
private static String toStringTree(final PathArgument identifier) {
if (identifier instanceof NodeIdentifierWithPredicates) {
- return identifier.getNodeType().getLocalName() +
- ((NodeIdentifierWithPredicates) identifier).getKeyValues().values();
+ return identifier.getNodeType().getLocalName()
+ + ((NodeIdentifierWithPredicates) identifier).getKeyValues().values();
} else if (identifier instanceof AugmentationIdentifier) {
return "augmentation";
} else {
*/
package org.opendaylight.yangtools.yang.data.api.schema;
-
/**
- *
* Leaf set node which preserves user-supplied ordering.
*
+ * <p>
* This node represents a data instance of <code>leaf-list</code> with
* <code>ordered-by user;</code> substatement.
*
+ * <p>
* Except preserving user-ordering all other semantics and behaviour is same
* as in {@link LeafSetNode}.
*
package org.opendaylight.yangtools.yang.data.api.schema;
/**
- *
* Map node which preserves user-supplied ordering.
*
* <p>
* <p>
* Except preserving user-ordering all other semantics and behaviour is same as
* in {@link MapNode}.
- *
*/
public interface OrderedMapNode extends MapNode, OrderedNodeContainer<MapEntryNode> {
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
/**
- *
* Normalized Node container which preserves user supplied ordering
* and allows addressing of child elements by position.
*
* @param <V> child type
*/
-public interface OrderedNodeContainer<V extends NormalizedNode<?, ?>> extends MixinNode, NormalizedNode<NodeIdentifier, Collection<V>> {
-
+public interface OrderedNodeContainer<V extends NormalizedNode<?, ?>> extends MixinNode,
+ NormalizedNode<NodeIdentifier, Collection<V>> {
/**
- * Returns child node by position
+ * Returns child node by position.
*
* @param position Position of child node
* @return Child Node
V getChild(int position);
/**
- * Returns count of child nodes
+ * Returns count of child nodes.
*
* @return count of child nodes.
*/
/**
* List entry node, which does not have value, but child nodes.
- *
* Represents an instance of data, which schema is instance of
* {@link org.opendaylight.yangtools.yang.model.api.ListSchemaNode} with key undefined.
*
+ * <p>
* This nodes itself does not contain any ordering information, user supplied
* ordering is preserved by parent node, which is instance of {@link UnkeyedListNode}.
- *
- *
*/
public interface UnkeyedListEntryNode extends DataContainerNode<NodeIdentifier> {
import java.util.Collection;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-
/**
- *
* Containment node, which contains {@link UnkeyedListEntryNode} of the same type, which may
* be quickly retrieved using key.
*
* Ordering of the elements is user-defined during construction of instance of this
* interface. Ordered view of elements (iteration)
* is provided by {@link #getValue()} call.
- *
*/
-public interface UnkeyedListNode extends
- DataContainerChild<NodeIdentifier, Collection<UnkeyedListEntryNode>>,
+public interface UnkeyedListNode extends DataContainerChild<NodeIdentifier, Collection<UnkeyedListEntryNode>>,
OrderedNodeContainer<UnkeyedListEntryNode> {
}
DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
/**
- * @return DataSchemaNode - schema of contained XML data
+ * Returns the schema corresponding to the node's datea.
+ *
+ * @return schema of contained XML data
*/
@Nonnull
ContainerSchemaNode getSchemaOfAnyXmlData();
*/
/**
- *
* Definition of normalized YANG DOM Model
*
* Normalized DOM Model brings more direct mapping between YANG Model, DOM
* <h3>Tree / subtree structure</h3> <h4>Grammar representation</h4>
*
* <pre>
- * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument}*
- * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier}| {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates}| {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue} | {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier}
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument}*
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier}
+ * | {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates}
+ * | {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue}
+ * | {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier}
*
* TreeRoot = {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
- * {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode} = ( {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} | {@link org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode} | {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} | {@link org.opendaylight.yangtools.yang.data.api.schema.MapNode} | {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode})*
- * ContainerDataNode = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier} {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode} =
+ * ( {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode}
+ * | {@link org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode}
+ * | {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
+ * | {@link org.opendaylight.yangtools.yang.data.api.schema.MapNode}
+ * | {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode})*
+ * ContainerDataNode =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
*
- * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier} SimpleValue
- * {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier} {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
- * {@link org.opendaylight.yangtools.yang.data.api.schema.MapNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier} {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode}
- * {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates} {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier} SimpleValue
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.MapNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
*
* // Special nodes
- * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier} {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode}*
- * {@link org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier} {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
- * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode} = {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue} SimpleValue
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode}*
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode}
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode} =
+ * {@link org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue} SimpleValue
* </pre>
*
* The resulting tree organization is following:
* code using these interfaces.
*
*/
-package org.opendaylight.yangtools.yang.data.api.schema;
\ No newline at end of file
+package org.opendaylight.yangtools.yang.data.api.schema;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-public abstract class ForwardingNormalizedNodeStreamAttributeWriter extends ForwardingNormalizedNodeStreamWriter implements NormalizedNodeStreamAttributeWriter {
+public abstract class ForwardingNormalizedNodeStreamAttributeWriter extends ForwardingNormalizedNodeStreamWriter
+ implements NormalizedNodeStreamAttributeWriter {
@Override
protected abstract NormalizedNodeStreamAttributeWriter delegate();
}
@Override
- public void leafSetEntryNode(final QName name, final Object value, final Map<QName, String> attributes) throws IOException {
+ public void leafSetEntryNode(final QName name, final Object value, final Map<QName, String> attributes)
+ throws IOException {
delegate().leafSetEntryNode(name, value, attributes);
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-public abstract class ForwardingNormalizedNodeStreamWriter extends ForwardingObject implements NormalizedNodeStreamWriter {
+public abstract class ForwardingNormalizedNodeStreamWriter extends ForwardingObject
+ implements NormalizedNodeStreamWriter {
@Override
protected abstract NormalizedNodeStreamWriter delegate();
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
- * Extension to the NormalizedNodeStreamWriter with attribute support
+ * Extension to the NormalizedNodeStreamWriter with attribute support.
*/
public interface NormalizedNodeStreamAttributeWriter extends NormalizedNodeStreamWriter {
- void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value, Map<QName, String> attributes) throws IOException;
+ void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value, Map<QName, String> attributes)
+ throws IOException;
void leafSetEntryNode(QName name, Object value, Map<QName, String> attributes) throws IOException;
- void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException;
+ void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint,
+ Map<QName, String> attributes) throws IOException;
- void startYangModeledAnyXmlNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException;
+ void startYangModeledAnyXmlNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint,
+ Map<QName, String> attributes) throws IOException;
- void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException;
+ void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint,
+ Map<QName, String> attributes) throws IOException;
- void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint, Map<QName, String> attributes) throws IOException;
+ void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint,
+ Map<QName, String> attributes) throws IOException;
}
* 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
int UNKNOWN_SIZE = -1;
/**
- *
* Emits a leaf node event with supplied value.
*
* @param name
void leafNode(NodeIdentifier name, 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(QName, Object)} calls are valid. Leaf set event is
void startLeafSet(NodeIdentifier name, 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(QName, Object)} calls are valid. Leaf set event is
void startOrderedLeafSet(NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException;
/**
- * Emits a leaf set entry node
+ * Emits a leaf set entry node.
*
* @param name
* name of the node as defined in the schema.
void leafSetEntryNode(QName name, Object value) throws IOException;
/**
- *
* Emits start of new container.
*
* <p>
void startContainerNode(NodeIdentifier name, int childSizeHint) throws IOException;
/**
- *
* Emits start of unkeyed list node event.
*
* <p>
void startUnkeyedListItem(NodeIdentifier name, int childSizeHint) throws IOException;
/**
- *
* Emits start of map node event.
*
* <p>
void startMapNode(NodeIdentifier name, int childSizeHint) throws IOException;
/**
- *
* Emits start of map entry.
*
* <p>
void startMapEntryNode(NodeIdentifierWithPredicates identifier, int childSizeHint) throws IOException;
/**
- *
* Emits start of map node event.
*
* <p>
void startOrderedMapNode(NodeIdentifier name, int childSizeHint) throws IOException;
/**
- *
- *
+ * Emits start of a choice node event.
*
* @param name
* name of node as defined in schema, namespace and revision are
void anyxmlNode(NodeIdentifier name, Object value) throws IOException;
/**
- *
- * Emits start of new yang modeled anyXml node.
- *
- * <p>
- * End of yang modeled anyXml node event is emitted by invoking {@link #endNode()}.
- *
- * <p>
- * Valid sub-events are:
- * <ul>
- * <li>{@link #leafNode}</li>
- * <li>{@link #startContainerNode}</li>
- * <li>{@link #startLeafSet}</li>
- * <li>{@link #startMapNode}</li>
- * <li>{@link #startUnkeyedList}</li>
- * </ul>
- *
- * @param name
- * name of node as defined in schema, namespace and revision are
- * derived from parent node.
- * @param childSizeHint
- * Non-negative count of expected direct child nodes or
- * {@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
- * If emitted node is invalid in current context or was emitted
- * multiple times.
- * @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
- */
+ * Emits start of new yang modeled anyXml node.
+ *
+ * <p>
+ * End of yang modeled anyXml node event is emitted by invoking {@link #endNode()}.
+ *
+ * <p>
+ * Valid sub-events are:
+ * <ul>
+ * <li>{@link #leafNode}</li>
+ * <li>{@link #startContainerNode}</li>
+ * <li>{@link #startLeafSet}</li>
+ * <li>{@link #startMapNode}</li>
+ * <li>{@link #startUnkeyedList}</li>
+ * </ul>
+ *
+ * @param name
+ * name of node as defined in schema, namespace and revision are
+ * derived from parent node.
+ * @param childSizeHint
+ * Non-negative count of expected direct child nodes or
+ * {@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
+ * If emitted node is invalid in current context or was emitted
+ * multiple times.
+ * @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 startYangModeledAnyXmlNode(NodeIdentifier name, int childSizeHint) throws IOException;
/**
}
/**
- * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple {@link #forStreamWriter(NormalizedNodeStreamWriter)}
- * method, this allows the caller to switch off RFC6020 XML compliance, providing better
- * throughput. The reason is that the XML mapping rules in RFC6020 require the encoding
- * to emit leaf nodes which participate in a list's key first and in the order in which
- * they are defined in the key. For JSON, this requirement is completely relaxed and leaves
- * can be ordered in any way we see fit. The former requires a bit of work: first a lookup
- * for each key and then for each emitted node we need to check whether it was already
- * emitted.
+ * Create a new writer backed by a {@link NormalizedNodeStreamWriter}. Unlike the simple
+ * {@link #forStreamWriter(NormalizedNodeStreamWriter)} method, this allows the caller to switch off RFC6020 XML
+ * compliance, providing better throughput. The reason is that the XML mapping rules in RFC6020 require
+ * the encoding to emit leaf nodes which participate in a list's key first and in the order in which they are
+ * defined in the key. For JSON, this requirement is completely relaxed and leaves can be ordered in any way we
+ * see fit. The former requires a bit of work: first a lookup for each key and then for each emitted node we need
+ * to check whether it was already emitted.
*
* @param writer Back-end writer
* @param orderKeyLeaves whether the returned instance should be RFC6020 XML compliant.
* @return A new instance.
*/
- public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer, final boolean orderKeyLeaves) {
+ public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer,
+ final boolean orderKeyLeaves) {
return orderKeyLeaves ? new OrderedNormalizedNodeWriter(writer) : new NormalizedNodeWriter(writer);
}
} else if (node instanceof LeafNode) {
final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
if (writer instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) writer).leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
+ ((NormalizedNodeStreamAttributeWriter) writer).leafNode(nodeAsLeaf.getIdentifier(),
+ nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
} else {
writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
}
if (node instanceof ContainerNode) {
final ContainerNode n = (ContainerNode) node;
if (writer instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
+ ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(n.getIdentifier(),
+ childSizeHint(n.getValue()), n.getAttributes());
} else {
writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
}
if (node instanceof YangModeledAnyXmlNode) {
final YangModeledAnyXmlNode n = (YangModeledAnyXmlNode) node;
if (writer instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) writer).startYangModeledAnyXmlNode(n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
+ ((NormalizedNodeStreamAttributeWriter) writer).startYangModeledAnyXmlNode(n.getIdentifier(),
+ childSizeHint(n.getValue()), n.getAttributes());
} else {
writer.startYangModeledAnyXmlNode(n.getIdentifier(), childSizeHint(n.getValue()));
}
protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
final NormalizedNodeStreamWriter nnWriter = getWriter();
if (nnWriter instanceof NormalizedNodeStreamAttributeWriter) {
- ((NormalizedNodeStreamAttributeWriter) nnWriter).startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
+ ((NormalizedNodeStreamAttributeWriter) nnWriter).startMapEntryNode(node.getIdentifier(),
+ childSizeHint(node.getValue()), node.getAttributes());
} else {
nnWriter.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
}
/**
* Exception thrown when a proposed change fails validation before being
* applied into the Data Tree because the Data Tree has been modified
- * in way that a conflicting
- * node is present.
+ * in way that a conflicting node is present.
*/
public class ConflictingModificationAppliedException extends DataValidationFailedException {
-
- /**
- *
- */
private static final long serialVersionUID = 1L;
- public ConflictingModificationAppliedException(final YangInstanceIdentifier path, final String message, final Throwable cause) {
+ public ConflictingModificationAppliedException(final YangInstanceIdentifier path, final String message,
+ final Throwable cause) {
super(path, message, cause);
}
public ConflictingModificationAppliedException(final YangInstanceIdentifier path, final String message) {
super(path, message);
}
-
}
* equals implementation must result in identity comparison.
*/
@Override
- boolean equals(Object o);
+ boolean equals(Object obj);
}
/**
* Applies the {@code node} to the {@code cursor}, note that if the top node of (@code node} is RootNode
- * you need to use {@link #applyRootedNodeToCursor(DataTreeModificationCursor, YangInstanceIdentifier, DataTreeCandidateNode) applyRootedNodeToCursor}
- * method that works with rooted node candidates
+ * you need to use {@link #applyRootedNodeToCursor(DataTreeModificationCursor, YangInstanceIdentifier,
+ * DataTreeCandidateNode) applyRootedNodeToCursor} method that works with rooted node candidates.
+ *
* @param cursor cursor from the modification we want to apply the {@code node} to
* @param node candidate tree to apply
*/
public static void applyToCursor(final DataTreeModificationCursor cursor, final DataTreeCandidateNode node) {
switch (node.getModificationType()) {
- case DELETE:
- cursor.delete(node.getIdentifier());
- break;
- case SUBTREE_MODIFIED:
+ case DELETE:
+ cursor.delete(node.getIdentifier());
+ break;
+ case SUBTREE_MODIFIED:
cursor.enter(node.getIdentifier());
AbstractNodeIterator iterator = new ExitingNodeIterator(null, node.getChildNodes().iterator());
- do {
- iterator = iterator.next(cursor);
- } while (iterator != null);
- break;
- case UNMODIFIED:
- // No-op
- break;
- case WRITE:
- cursor.write(node.getIdentifier(), node.getDataAfter().get());
- break;
- default:
- throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
+ do {
+ iterator = iterator.next(cursor);
+ } while (iterator != null);
+ break;
+ case UNMODIFIED:
+ // No-op
+ break;
+ case WRITE:
+ cursor.write(node.getIdentifier(), node.getDataAfter().get());
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
}
}
/**
* Applies the {@code node} that is rooted(doesn't have an identifier) in tree A to tree B's {@code cursor}
- * at location specified by {@code rootPath}
+ * at location specified by {@code rootPath}.
+ *
* @param cursor cursor from the modification we want to apply the {@code node} to
* @param rootPath path in the {@code cursor}'s tree we want to apply to candidate to
* @param node candidate tree to apply
*/
- public static void applyRootedNodeToCursor(final DataTreeModificationCursor cursor, final YangInstanceIdentifier rootPath, final DataTreeCandidateNode node) {
+ public static void applyRootedNodeToCursor(final DataTreeModificationCursor cursor,
+ final YangInstanceIdentifier rootPath, final DataTreeCandidateNode node) {
switch (node.getModificationType()) {
case DELETE:
cursor.delete(rootPath.getLastPathArgument());
while (iterator.hasNext()) {
final DataTreeCandidateNode node = iterator.next();
switch (node.getModificationType()) {
- case DELETE:
- cursor.delete(node.getIdentifier());
- break;
- case APPEARED:
- case DISAPPEARED:
- case SUBTREE_MODIFIED:
- final Collection<DataTreeCandidateNode> children = node.getChildNodes();
- if (!children.isEmpty()) {
- cursor.enter(node.getIdentifier());
+ case DELETE:
+ cursor.delete(node.getIdentifier());
+ break;
+ case APPEARED:
+ case DISAPPEARED:
+ case SUBTREE_MODIFIED:
+ final Collection<DataTreeCandidateNode> children = node.getChildNodes();
+ if (!children.isEmpty()) {
+ cursor.enter(node.getIdentifier());
return new ExitingNodeIterator(this, children.iterator());
- }
- break;
- case UNMODIFIED:
- // No-op
- break;
- case WRITE:
- cursor.write(node.getIdentifier(), node.getDataAfter().get());
- break;
- default:
- throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
+ }
+ break;
+ case UNMODIFIED:
+ // No-op
+ break;
+ case WRITE:
+ cursor.write(node.getIdentifier(), node.getDataAfter().get());
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
}
}
exitNode(cursor);
private final AbstractNodeIterator parent;
- public ExitingNodeIterator(@Nullable final AbstractNodeIterator parent,
+ ExitingNodeIterator(@Nullable final AbstractNodeIterator parent,
@Nonnull final Iterator<DataTreeCandidateNode> iterator) {
super(iterator);
this.parent = parent;
@Beta
public final class DataTreeCandidates {
private static final Logger LOG = LoggerFactory.getLogger(DataTreeCandidates.class);
+
private DataTreeCandidates() {
throw new UnsupportedOperationException();
}
- public static DataTreeCandidate newDataTreeCandidate(final YangInstanceIdentifier rootPath, final DataTreeCandidateNode rootNode) {
+ public static DataTreeCandidate newDataTreeCandidate(final YangInstanceIdentifier rootPath,
+ final DataTreeCandidateNode rootNode) {
return new DefaultDataTreeCandidate(rootPath, rootNode);
}
- public static DataTreeCandidate fromNormalizedNode(final YangInstanceIdentifier rootPath, final NormalizedNode<?, ?> node) {
+ public static DataTreeCandidate fromNormalizedNode(final YangInstanceIdentifier rootPath,
+ final NormalizedNode<?, ?> node) {
return new DefaultDataTreeCandidate(rootPath, new NormalizedNodeDataTreeCandidateNode(node));
}
DataTreeCandidateNodes.applyToCursor(cursor, candidate.getRootNode());
}
- public static void applyToModification(final DataTreeModification modification, final DataTreeCandidate candidate) {
+ public static void applyToModification(final DataTreeModification modification,
+ final DataTreeCandidate candidate) {
if (modification instanceof CursorAwareDataTreeModification) {
applyToCursorAwareModification((CursorAwareDataTreeModification) modification, candidate);
return;
final DataTreeCandidateNode node = candidate.getRootNode();
final YangInstanceIdentifier path = candidate.getRootPath();
switch (node.getModificationType()) {
- case DELETE:
- modification.delete(path);
- LOG.debug("Modification {} deleted path {}", modification, path);
- break;
- case SUBTREE_MODIFIED:
- LOG.debug("Modification {} modified path {}", modification, path);
+ case DELETE:
+ modification.delete(path);
+ LOG.debug("Modification {} deleted path {}", modification, path);
+ break;
+ case SUBTREE_MODIFIED:
+ LOG.debug("Modification {} modified path {}", modification, path);
- NodeIterator iterator = new NodeIterator(null, path, node.getChildNodes().iterator());
- do {
- iterator = iterator.next(modification);
- } while (iterator != null);
- break;
- case UNMODIFIED:
- LOG.debug("Modification {} unmodified path {}", modification, path);
- // No-op
- break;
- case WRITE:
- modification.write(path, node.getDataAfter().get());
- LOG.debug("Modification {} written path {}", modification, path);
- break;
- default:
- throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
+ NodeIterator iterator = new NodeIterator(null, path, node.getChildNodes().iterator());
+ do {
+ iterator = iterator.next(modification);
+ } while (iterator != null);
+ break;
+ case UNMODIFIED:
+ LOG.debug("Modification {} unmodified path {}", modification, path);
+ // No-op
+ break;
+ case WRITE:
+ modification.write(path, node.getDataAfter().get());
+ LOG.debug("Modification {} written path {}", modification, path);
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
}
}
private final YangInstanceIdentifier path;
private final NodeIterator parent;
- public NodeIterator(@Nullable final NodeIterator parent, @Nonnull final YangInstanceIdentifier path,
+ NodeIterator(@Nullable final NodeIterator parent, @Nonnull final YangInstanceIdentifier path,
@Nonnull final Iterator<DataTreeCandidateNode> iterator) {
this.iterator = Preconditions.checkNotNull(iterator);
this.path = Preconditions.checkNotNull(path);
final YangInstanceIdentifier child = path.node(node.getIdentifier());
switch (node.getModificationType()) {
- case DELETE:
- modification.delete(child);
- LOG.debug("Modification {} deleted path {}", modification, child);
- break;
- case APPEARED:
- case DISAPPEARED:
- case SUBTREE_MODIFIED:
- LOG.debug("Modification {} modified path {}", modification, child);
- return new NodeIterator(this, child, node.getChildNodes().iterator());
- case UNMODIFIED:
- LOG.debug("Modification {} unmodified path {}", modification, child);
- // No-op
- break;
- case WRITE:
- modification.write(child, node.getDataAfter().get());
- LOG.debug("Modification {} written path {}", modification, child);
- break;
- default:
- throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
+ case DELETE:
+ modification.delete(child);
+ LOG.debug("Modification {} deleted path {}", modification, child);
+ break;
+ case APPEARED:
+ case DISAPPEARED:
+ case SUBTREE_MODIFIED:
+ LOG.debug("Modification {} modified path {}", modification, child);
+ return new NodeIterator(this, child, node.getChildNodes().iterator());
+ case UNMODIFIED:
+ LOG.debug("Modification {} unmodified path {}", modification, child);
+ // No-op
+ break;
+ case WRITE:
+ modification.write(child, node.getDataAfter().get());
+ LOG.debug("Modification {} written path {}", modification, child);
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported modification " + node.getModificationType());
}
}
/**
* DataTree configuration class.
*
+ * <p>
* TreeConfig supports currently the following options:
* <ul>
* <li>treeType</li>
* <li>enable/disable mandatory nodes validation</li>
* </ul>
*
+ * <p>
* TreeConfig can be easily extended in order to support further data tree
* configuration options, like following:
* <ul>
* <li>other schema aware validation options</li>
* </ul>
*
+ * <p>
* This can be useful when strict validation is not required or useful for some
* reasons.
- *
*/
@Beta
public class DataTreeConfiguration implements Immutable {
public static DataTreeConfiguration getDefault(final TreeType treeType) {
Preconditions.checkNotNull(treeType);
switch (treeType) {
- case CONFIGURATION:
- return DEFAULT_CONFIGURATION;
- case OPERATIONAL:
- return DEFAULT_OPERATIONAL;
- default:
- return new DataTreeConfiguration(treeType, YangInstanceIdentifier.EMPTY, false, true);
+ case CONFIGURATION:
+ return DEFAULT_CONFIGURATION;
+ case OPERATIONAL:
+ return DEFAULT_OPERATIONAL;
+ default:
+ return new DataTreeConfiguration(treeType, YangInstanceIdentifier.EMPTY, false, true);
}
}
return new DataTreeConfiguration(treeType, rootPath, uniqueIndexes, mandatoryNodesValidation);
}
}
-}
\ No newline at end of file
+}
*/
package org.opendaylight.yangtools.yang.data.api.schema.tree;
+import com.google.common.base.Optional;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import com.google.common.base.Optional;
-
/**
* Read-only snapshot of a {@link DataTree}. The snapshot is stable and isolated,
* e.g. data tree changes occurring after the snapshot has been taken are not
* equals implementation must result in identity comparison.
*/
@Override
- boolean equals(Object o);
+ boolean equals(Object obj);
}
*/
package org.opendaylight.yangtools.yang.data.api.schema.tree;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
- * Exception thrown when a proposed change fails validation before being
- * applied into the datastore. This can have multiple reasons, for example
- * the datastore has been concurrently modified such that a conflicting
- * node is present, or the modification is structurally incorrect.
+ * Exception thrown when a proposed change fails validation before being applied into the datastore. This can have
+ * multiple reasons, for example the datastore has been concurrently modified such that a conflicting node is present,
+ * or the modification is structurally incorrect.
*/
public class DataValidationFailedException extends Exception {
private static final long serialVersionUID = 1L;
+
private final YangInstanceIdentifier path;
/**
public DataValidationFailedException(final YangInstanceIdentifier path, final String message) {
this(path, message, null);
}
+
/**
- * Create a new instance, initializing
+ * Create a new instance, initializing the cause.
*
* @param path Object path which caused this exception
* @param message Specific message describing the failure
* @param cause Exception which triggered this failure, may be null
*/
- public DataValidationFailedException(final YangInstanceIdentifier path, final String message, final Throwable cause) {
+ public DataValidationFailedException(final YangInstanceIdentifier path, final String message,
+ final Throwable cause) {
super(message, cause);
this.path = Preconditions.checkNotNull(path);
}
@Override
public String toString() {
- return MoreObjects.toStringHelper(this).add("rootPath", getRootPath()).add("rootNode", getRootNode()).toString();
+ return MoreObjects.toStringHelper(this).add("rootPath", getRootPath()).add("rootNode", getRootNode())
+ .toString();
}
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
- * Exception thrown when a proposed change fails validation before being
- * applied into the datastore because of incorrect structure of user supplied
- * data.
- *
+ * Exception thrown when a proposed change fails validation before being applied into the datastore
+ * because of incorrect structure of user supplied data.
*/
public class IncorrectDataStructureException extends DataValidationFailedException {
-
- /**
- *
- */
private static final long serialVersionUID = 1L;
- public IncorrectDataStructureException(final YangInstanceIdentifier path, final String message, final Throwable cause) {
+ public IncorrectDataStructureException(final YangInstanceIdentifier path, final String message,
+ final Throwable cause) {
super(path, message, cause);
}
public IncorrectDataStructureException(final YangInstanceIdentifier path, final String message) {
super(path, message);
}
-
}
package org.opendaylight.yangtools.yang.data.api.schema.tree;
/**
- * Enumeration of all possible node modification states. These are used in
- * data tree modification context to quickly assess what sort of modification
- * the node is undergoing.
+ * Enumeration of all possible node modification states. These are used in data tree modification context to quickly
+ * assess what sort of modification the node is undergoing.
*/
public enum ModificationType {
/**
* This node has appeared because it is implied by one of its children. This type is usually produced when a
* structural container is created to host some leaf entries. It does not have an associated before-image.
*
+ * <p>
* Its semantics is a combination of SUBTREE_MODIFIED and WRITE, depending on which context it is being interpreted.
*
+ * <p>
* Users who track the value of the node can treat it as a WRITE. Users transforming a {@link DataTreeCandidate} to
* operations on a {@link DataTreeModification} should interpret it as a SUBTREE_MODIFIED and examine its children.
* This is needed to correctly deal with concurrent operations on the nodes children, as issuing a write on the
* This node has disappeared because it is no longer implied by any children. This type is usually produced when a
* structural container is removed because it has become empty. It does not have an associated after-image.
*
- * Its semantics is a combination of SUBTREE_MODIFIED and DELETE, depending on which context it is being interpreted.
- * Users who track the value of the node can treat it as a DELETE, as the container has disappeared. Users
- * transforming a {@link DataTreeCandidate} to operations on a {@link DataTreeModification} should interpret it as
- * a SUBTREE_MODIFIED and examine its children.
+ * <p>
+ * Its semantics is a combination of SUBTREE_MODIFIED and DELETE, depending on which context it is being
+ * interpreted. Users who track the value of the node can treat it as a DELETE, as the container has disappeared.
+ * Users transforming a {@link DataTreeCandidate} to operations on a {@link DataTreeModification} should interpret
+ * it as a SUBTREE_MODIFIED and examine its children.
*
+ * <p>
* This is needed to correctly deal with concurrent operations on the nodes children, as issuing a delete on the
* DataTreeModification would end up removing any leaves which have not been present at the DataTree which emitted
* this event.
* modified or written did not exist when transaction started
* and still does not exists when transaction is processed.
*
+ * <p>
* Note if node existed in first place and was removed by other transaction,
* thrown exception should be {@link ConflictingModificationAppliedException}.
- *
- *
*/
public class ModifiedNodeDoesNotExistException extends DataValidationFailedException {
-
- /**
- *
- */
private static final long serialVersionUID = 1L;
- public ModifiedNodeDoesNotExistException(final YangInstanceIdentifier path, final String message, final Throwable cause) {
+ public ModifiedNodeDoesNotExistException(final YangInstanceIdentifier path, final String message,
+ final Throwable cause) {
super(path, message, cause);
}
public ModifiedNodeDoesNotExistException(final YangInstanceIdentifier path, final String message) {
super(path, message);
}
-
}
*/
package org.opendaylight.yangtools.yang.data.api.schema.tree;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-
import com.google.common.base.Optional;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
/**
* A tree node which has references to its child leaves. This are typically
public interface StoreTreeNode<C extends StoreTreeNode<C>> {
/**
- * Returns a direct child of the node
+ * Returns a direct child of the node.
*
* @param child Identifier of child
* @return Optional with node if the child is existing, {@link Optional#absent()} otherwise.
}
/**
- * Finds a node in tree
+ * Finds a node in tree.
+ *
* @param <T>
* Store tree node type.
* @param tree Data Tree
public static <T extends StoreTreeNode<T>> T findNodeChecked(final T tree, final YangInstanceIdentifier path) {
T current = tree;
- int i = 1;
+ int depth = 1;
for (PathArgument pathArg : path.getPathArguments()) {
Optional<T> potential = current.getChild(pathArg);
if (!potential.isPresent()) {
throw new IllegalArgumentException(String.format("Child %s is not present in tree.",
- path.getAncestor(i)));
+ path.getAncestor(depth)));
}
current = potential.get();
- ++i;
+ ++depth;
}
return current;
}
/**
- * Finds a node or closest parent in the tree
+ * Finds a node or closest parent in the tree.
+ *
* @param <T>
* Store tree node type.
* @param tree Data Tree
* @param path Path to the node
* @return Map.Entry Entry with key which is path to closest parent and value is parent node.
- *
*/
public static <T extends StoreTreeNode<T>> Entry<YangInstanceIdentifier, T> findClosest(final T tree,
final YangInstanceIdentifier path) {
return new SimpleImmutableEntry<>(path.getAncestor(nesting - 1), parent.get());
}
- public static <T extends StoreTreeNode<T>> Optional<T> getChild(final Optional<T> parent, final PathArgument child) {
+ public static <T extends StoreTreeNode<T>> Optional<T> getChild(final Optional<T> parent,
+ final PathArgument child) {
if (parent.isPresent()) {
return parent.get().getChild(child);
}
private NormalizedNode<?, ?> data;
private Version subtreeVersion;
- protected AbstractMutableContainerNode(final AbstractContainerNode parent, final Map<PathArgument, TreeNode> children) {
+ protected AbstractMutableContainerNode(final AbstractContainerNode parent,
+ final Map<PathArgument, TreeNode> children) {
this.data = parent.getData();
this.version = parent.getVersion();
this.subtreeVersion = parent.getSubtreeVersion();
children = null;
return ret;
}
-}
\ No newline at end of file
+}
this(data, version, MapAdaptor.getDefaultInstance().initialSnapshot(1), subtreeVersion);
}
- LazyContainerNode(final NormalizedNode<?, ?> data, final Version version, final Map<PathArgument, TreeNode> children,
- final Version subtreeVersion) {
+ LazyContainerNode(final NormalizedNode<?, ?> data, final Version version,
+ final Map<PathArgument, TreeNode> children, final Version subtreeVersion) {
super(data, version, children, subtreeVersion);
}
* A very basic data tree node. It has a version (when it was last modified), a subtree version (when any of its
* children were modified) and some read-only data.
*
+ * <p>
* Semantic difference between these two is important when dealing with modifications involving parent/child
* relationships and what operations can be execute concurrently without creating a data dependency conflict.
*
+ * <p>
* A replace/delete operation cannot be applied to this node if the subtree version does not match. This mismatch
* still allows modifications to its descendants.
*
+ * <p>
* A mismatch in node version indicates a replacement, preventing a modification of descendants or itself.
*/
// FIXME: BUG-2399: clarify that versioning rules are not enforced for non-presence containers, as they are not
* {@link TreeNodeFactory#createTreeNodeRecursively}. Each call to <code>createTreeNodeRecursively</code>
* calls either {@link #createNormalizedNodeRecursively} or {@link #createOrderedNodeRecursively}
* which depends on type of child node.
- * <br> The root node that is returned holds reference to data node and whole subtree of children also containing references
- * to data nodes.
+ * <br> The root node that is returned holds reference to data node and whole subtree of children also containing
+ * references to data nodes.
*
* @param version version of indexed data
* @param data reference to data node
/**
* Method creates and returns Normalized Node Container as root and recursively creates whole subtree
- * from all of the container child iterables stored in {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer#getValue()}
+ * from all of the container child iterables stored in
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer#getValue()}
* <br>
- * The reason why is this method called recursively is that in background method calls {@link TreeNodeFactory#createTreeNodeRecursively}
- * for each child stored in NormalizedNode and after each child is created the method calls again {@link #createNormalizedNodeRecursively} method
- * until all of the children are resolved.
+ * The reason why is this method called recursively is that in background method calls
+ * {@link TreeNodeFactory#createTreeNodeRecursively} for each child stored in NormalizedNode and after each child
+ * is created the method calls again {@link #createNormalizedNodeRecursively} method until all of the children are
+ * resolved.
*
* @param version version of indexed data
* @param container Normalized Node Container
/**
* Method creates and returns Ordered Node Container as root and recursively creates whole subtree
- * from all of the container child iterables stored in {@link org.opendaylight.yangtools.yang.data.api.schema.OrderedNodeContainer#getValue()}
+ * from all of the container child iterables stored in
+ * {@link org.opendaylight.yangtools.yang.data.api.schema.OrderedNodeContainer#getValue()}
* <br>
- * The reason why is this method called recursively is that in background method calls {@link TreeNodeFactory#createTreeNodeRecursively}
- * for each child stored in NormalizedNode and after each child is created the method calls again {@link #createNormalizedNodeRecursively} method
- * until all of the children are resolved.
+ * The reason why is this method called recursively is that in background method calls
+ * {@link TreeNodeFactory#createTreeNodeRecursively} for each child stored in NormalizedNode and after each child
+ * is created the method calls again {@link #createNormalizedNodeRecursively} method until all of the children are
+ * resolved.
*
* @param version version of indexed data
* @param container Ordered Node Container
public static TreeNode createTreeNodeRecursively(final NormalizedNode<?, ?> data, final Version version) {
if (data instanceof NormalizedNodeContainer<?, ?, ?>) {
@SuppressWarnings("unchecked")
- NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>> container = (NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>>) data;
+ NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>> container =
+ (NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>>) data;
return createNormalizedNodeRecursively(version, container);
}
* Asynchronous interface to evaluation. It is functionally the same as an XPathExpression, but allows for asynchronous
* execution of evaluation of the expression.
*
+ * <p>
* FIXME: Whether or not the resulting XPathResult can perform blocking calls is up for grabs, but implementations are
* definitely allowed to perform things like on-demand data transformation from foreign object and data models.
*
* {@link XPathResult} at some point it the future. If it fails to match anything, it {@link Future#get()} will
* return {@link Optional#absent()}.
*
+ * <p>
* FIXME: The amount of overhead an implementation can incur on the user as data from the resulting
* {@link XPathResult} is being accessed is left UNDEFINED.
- *
* Specifically, the user is expected to store each result returned directly or indirectly in a local
* variable instead of repeated calls to the result's methods, as these may incur CPU processing overhead.
- *
* Furthermore all method invocations can throw {@link LazyXPathExpressionException}, which the users are
* expected to handle gracefully. RESILIENT USERS ARE EXPECTED TO CATCH {@link LazyXPathExpressionException}
* AND RECOVER IN THE SAME MANNER THEY WOULD IF AN {@link XPathExpressionException} WOULD HAVE BEEN THROWN.
- *
* [ FIXME: would it be appropriate to allow implementations to SneakyThrow {@link XPathExpressionException}
* and not introduce a RuntimeExpcetion ? ]
*
* expense of additional processing being performed on them. The decision to optimize a particular expression is left
* to the user's discretion.
*
+ * <p>
* Implementations supporting profile-driven and similar optimizations which depend on data being gathered during
* evaluation should not implement this interface, but rather perform these optimizations transparently behind the
* scenes. That implies the users can expect those optimizations not interfering with the user's ability to evaluate
* Base interface for various things an XPath evaluation can return.
*
* @param <T> type of returned value
- *
- * FIXME: do we want to support all the modes of
- * <a href="http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResultType">DOM XPath</a> ?
- * The default DataTree (yang-data-impl) implementation can support ORDERED_NODE_SNAPSHOT_TYPE. The clustered
- * datastore may want to implement ORDERED_NODE_ITERATOR_TYPE (via iterators).
*/
@Beta
+// FIXME: do we want to support all the modes of
+// <a href="http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResultType">DOM XPath</a> ?
+// The default DataTree (yang-data-impl) implementation can support ORDERED_NODE_SNAPSHOT_TYPE. The clustered
+// datastore may want to implement ORDERED_NODE_ITERATOR_TYPE (via iterators).
public interface XPathResult<T> {
/**
* Get the value contained in this result.
/**
* Compile an XPath expression for execution on {@link XPathDocument}s produced by this context.
*
+ * <p>
* The user must provide a prefix-to-mapping {@link Converter}, which will be used to convert any prefixes found
* in the XPath expression being compiled in the resulting context.
*
* implementation. Users are expected to resolve these via their service resolution framework, be it
* {@link java.util.ServiceLoader}, OSGi or similar.
*
+ * <p>
* Implementations are required to support {@link java.util.ServiceLoader}.
*/
public interface XPathSchemaContextFactory {
ModifyAction.fromXmlValue("exception call");
fail();
} catch (IllegalArgumentException e) {
+ // Expected
}
}
}
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
-import javax.annotation.Nonnull;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
l.remove(null);
fail();
} catch (UnsupportedOperationException e) {
+ // Expected
}
try {
l.addAll(null);
fail();
} catch (UnsupportedOperationException e) {
+ // Expected
}
try {
l.removeAll(null);
fail();
} catch (UnsupportedOperationException e) {
+ // Expected
}
try {
l.retainAll(null);
fail();
} catch (UnsupportedOperationException e) {
+ // Expected
}
try {
l.clear();
fail();
} catch (UnsupportedOperationException e) {
+ // Expected
}
try {
l.addAll(0, null);
fail();
} catch (UnsupportedOperationException e) {
+ // Expected
}
}
final QName qNameLeaf = QName.create(qNameModule, "leaf-a");
final Map<QName, Object> entryLeaf = new HashMap<>();
entryLeaf.put(qNameList, "leaf");
- final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates = new YangInstanceIdentifier
- .NodeIdentifierWithPredicates(qNameList , entryLeaf);
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(qNameList , entryLeaf);
final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.of(qNameRoot).node(qNameList)
.node(nodeIdentifierWithPredicates).node(qNameLeaf);
final PathArgument pathArgumentToRoot = yangInstanceIdentifier.getAncestor(1).getPathArguments().iterator()
.next();
- final StackedPathArguments stackedPathArguments = (StackedPathArguments)yangInstanceIdentifier.getPathArguments();
+ final StackedPathArguments stackedPathArguments = (StackedPathArguments)yangInstanceIdentifier
+ .getPathArguments();
assertTrue(yangInstanceIdentifier.pathArgumentsEqual(yangInstanceIdentifier));
assertEquals(pathArgumentToRoot, stackedPathArguments.get(0));
assertEquals(4, stackedPathArguments.size());
assertEquals(0, stackedPathArguments.indexOf(pathArgumentToRoot));
assertEquals(0, stackedPathArguments.lastIndexOf(pathArgumentToRoot));
- final StackedReversePathArguments stackedReversePathArguments = (StackedReversePathArguments)yangInstanceIdentifier
- .getReversePathArguments();
+ final StackedReversePathArguments stackedReversePathArguments =
+ (StackedReversePathArguments)yangInstanceIdentifier.getReversePathArguments();
final QName rootQname = pathArgumentToRoot.getNodeType();
final QName leafQname = stackedReversePathArguments.get(0).getNodeType();
assertEquals(qNameRoot, rootQname);
stackedYangInstanceIdentifier.getAncestor(12);
fail();
} catch (IllegalArgumentException e) {
+ // Expected
}
}
-}
\ No newline at end of file
+}
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
@Test
public void testGetLastPathArgument() {
- YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
- assertEquals( "getLastPathArgument", new NodeIdentifier(NODENAME2), id1.getLastPathArgument());
+ YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ assertEquals("getLastPathArgument", new NodeIdentifier(NODENAME2), id1.getLastPathArgument());
YangInstanceIdentifier id2 = YangInstanceIdentifier.create();
- assertNull( id2.getLastPathArgument() );
+ assertNull(id2.getLastPathArgument());
}
@Test
public void testHashCodeEquals() {
- YangInstanceIdentifier id1 = YangInstanceIdentifier.create(NodeIdentifier.create(NODENAME1), new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), NodeIdentifier.create(NODENAME2));
+ YangInstanceIdentifier id1 = YangInstanceIdentifier.create(NodeIdentifier.create(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ NodeIdentifier.create(NODENAME2));
- assertEquals( "hashCode", id1.hashCode(), id2.hashCode() );
+ assertEquals("hashCode", id1.hashCode(), id2.hashCode());
}
@Test
public void testEquals() {
- YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier id3 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME2), new NodeIdentifier(NODENAME1));
- YangInstanceIdentifier id4 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1));
-
- assertEquals( "equals", false, id1.equals( null ) );
- assertEquals( "equals", true, id1.equals( id1 ) );
- assertEquals( "equals", true, id1.equals( id2 ) );
- assertEquals( "equals", false, id1.equals( id3 ) );
- assertEquals( "equals", false, id1.equals( id4 ) );
- assertEquals( "equals", false, id1.equals( new Object() ) );
+ final YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ final YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ final YangInstanceIdentifier id3 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME2),
+ new NodeIdentifier(NODENAME1));
+ final YangInstanceIdentifier id4 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1));
+
+ assertEquals("equals", false, id1.equals(null));
+ assertEquals("equals", true, id1.equals(id1));
+ assertEquals("equals", true, id1.equals(id2));
+ assertEquals("equals", false, id1.equals(id3));
+ assertEquals("equals", false, id1.equals(id4));
+ assertEquals("equals", false, id1.equals(new Object()));
}
@Test
public void testToString() {
- YangInstanceIdentifier id = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
+ YangInstanceIdentifier id = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
- assertNotNull( id.toString() );
+ assertNotNull(id.toString());
}
@Test
public void testNode() {
- YangInstanceIdentifier id = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
+ final YangInstanceIdentifier id = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier newID = id.node( NODENAME3 );
+ YangInstanceIdentifier newID = id.node(NODENAME3);
- assertNotNull( "InstanceIdentifier is null", newID );
- assertEquals( "Path size", 3, newID.getPathArguments().size() );
+ assertNotNull("InstanceIdentifier is null", newID);
+ assertEquals("Path size", 3, newID.getPathArguments().size());
Iterator<PathArgument> it = newID.getPathArguments().iterator();
- assertEquals( "PathArg 1 node type", NODENAME1, it.next().getNodeType() );
- assertEquals( "PathArg 2 node type", NODENAME2, it.next().getNodeType() );
- assertEquals( "PathArg 3 node type", NODENAME3, it.next().getNodeType() );
+ assertEquals("PathArg 1 node type", NODENAME1, it.next().getNodeType());
+ assertEquals("PathArg 2 node type", NODENAME2, it.next().getNodeType());
+ assertEquals("PathArg 3 node type", NODENAME3, it.next().getNodeType());
- newID = id.node( new NodeIdentifier( NODENAME3 ) );
+ newID = id.node(new NodeIdentifier(NODENAME3));
- assertNotNull( "InstanceIdentifier is null", newID );
- assertEquals( "Path size", 3, newID.getPathArguments().size() );
+ assertNotNull("InstanceIdentifier is null", newID);
+ assertEquals("Path size", 3, newID.getPathArguments().size());
it = newID.getPathArguments().iterator();
- assertEquals( "PathArg 1 node type", NODENAME1, it.next().getNodeType() );
- assertEquals( "PathArg 2 node type", NODENAME2, it.next().getNodeType() );
- assertEquals( "PathArg 3 node type", NODENAME3, it.next().getNodeType() );
+ assertEquals("PathArg 1 node type", NODENAME1, it.next().getNodeType());
+ assertEquals("PathArg 2 node type", NODENAME2, it.next().getNodeType());
+ assertEquals("PathArg 3 node type", NODENAME3, it.next().getNodeType());
}
@Test
public void testRelativeTo() {
-
- YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2),
- new NodeIdentifier(NODENAME3), new NodeIdentifier(NODENAME4));
- YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier id3 = YangInstanceIdentifier.create(
- Lists.newArrayList(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2)));
-
- Optional<YangInstanceIdentifier> relative = id1.relativeTo( id2 );
- assertEquals( "isPresent", true, relative.isPresent() );
-
- List<PathArgument> p = relative.get().getPathArguments();
- assertEquals( "Path size", 2, p.size() );
- assertEquals( "PathArg 1 node type", NODENAME3, p.get(0).getNodeType() );
- assertEquals( "PathArg 2 node type", NODENAME4, p.get(1).getNodeType() );
-
- relative = id2.relativeTo( id3 );
- assertEquals( "isPresent", true, relative.isPresent() );
- assertEquals( "Path size", 0, relative.get().getPathArguments().size() );
-
- relative = id2.relativeTo( id1 );
- assertEquals( "isPresent", false, relative.isPresent() );
+ final YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2), new NodeIdentifier(NODENAME3), new NodeIdentifier(NODENAME4));
+ final YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ final YangInstanceIdentifier id3 = YangInstanceIdentifier.create(Lists.newArrayList(
+ new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2)));
+
+ Optional<YangInstanceIdentifier> relative = id1.relativeTo(id2);
+ assertEquals("isPresent", true, relative.isPresent());
+
+ List<PathArgument> path = relative.get().getPathArguments();
+ assertEquals("Path size", 2, path.size());
+ assertEquals("PathArg 1 node type", NODENAME3, path.get(0).getNodeType());
+ assertEquals("PathArg 2 node type", NODENAME4, path.get(1).getNodeType());
+
+ relative = id2.relativeTo(id3);
+ assertEquals("isPresent", true, relative.isPresent());
+ assertEquals("Path size", 0, relative.get().getPathArguments().size());
+
+ relative = id2.relativeTo(id1);
+ assertEquals("isPresent", false, relative.isPresent());
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testContainsNull() {
final YangInstanceIdentifier id = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1));
- id.contains( null );
+ id.contains(null);
}
@Test
public void testContains() {
-
- YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2),
- new NodeIdentifier(NODENAME3), new NodeIdentifier(NODENAME4));
- YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier id3 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME2));
- YangInstanceIdentifier id4 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1), new NodeIdentifier(NODENAME3));
-
- assertEquals( "contains", true, id2.contains( id1 ) );
- assertEquals( "contains", true, id2.contains( id3 ) );
- assertEquals( "contains", false, id1.contains( id2 ) );
- assertEquals( "contains", false, id2.contains( id4 ) );
+ final YangInstanceIdentifier id1 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2), new NodeIdentifier(NODENAME3), new NodeIdentifier(NODENAME4));
+ final YangInstanceIdentifier id2 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ final YangInstanceIdentifier id3 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME2));
+ final YangInstanceIdentifier id4 = YangInstanceIdentifier.create(new NodeIdentifier(NODENAME1),
+ new NodeIdentifier(NODENAME3));
+
+ assertEquals("contains", true, id2.contains(id1));
+ assertEquals("contains", true, id2.contains(id3));
+ assertEquals("contains", false, id1.contains(id2));
+ assertEquals("contains", false, id2.contains(id4));
}
@Test
public void testOf() {
+ YangInstanceIdentifier newID = YangInstanceIdentifier.of(NODENAME1);
- YangInstanceIdentifier newID = YangInstanceIdentifier.of( NODENAME1 );
+ assertNotNull("InstanceIdentifier is null", newID);
+ assertEquals("Path size", 1, newID.getPathArguments().size());
+ assertEquals("PathArg 1 node type", NODENAME1, newID.getPathArguments().get(0).getNodeType());
- assertNotNull( "InstanceIdentifier is null", newID );
- assertEquals( "Path size", 1, newID.getPathArguments().size() );
- assertEquals( "PathArg 1 node type", NODENAME1, newID.getPathArguments().get(0).getNodeType() );
-
- assertNotNull( newID.toString() ); // for code coverage
+ assertNotNull(newID.toString()); // for code coverage
}
@Test
public void testBuilder() {
-
YangInstanceIdentifier newID = YangInstanceIdentifier.builder()
- .node( NODENAME1 )
- .nodeWithKey( NODENAME2, Collections.singletonMap( KEY1, "foo" ) )
- .nodeWithKey( NODENAME3, KEY2, "bar" ).build();
+ .node(NODENAME1)
+ .nodeWithKey(NODENAME2, Collections.singletonMap(KEY1, "foo"))
+ .nodeWithKey(NODENAME3, KEY2, "bar").build();
- assertNotNull( "InstanceIdentifier is null", newID );
- assertEquals( "Path size", 3, newID.getPathArguments().size() );
+ assertNotNull("InstanceIdentifier is null", newID);
+ assertEquals("Path size", 3, newID.getPathArguments().size());
Iterator<PathArgument> it = newID.getPathArguments().iterator();
- assertEquals( "PathArg 1 node type", NODENAME1, it.next().getNodeType() );
- verifyNodeIdentifierWithPredicates( "PathArg 2", it.next(), NODENAME2, KEY1, "foo" );
- verifyNodeIdentifierWithPredicates( "PathArg 3", it.next(), NODENAME3, KEY2, "bar" );
+ assertEquals("PathArg 1 node type", NODENAME1, it.next().getNodeType());
+ verifyNodeIdentifierWithPredicates("PathArg 2", it.next(), NODENAME2, KEY1, "foo");
+ verifyNodeIdentifierWithPredicates("PathArg 3", it.next(), NODENAME3, KEY2, "bar");
- newID = YangInstanceIdentifier.builder( newID ).node( NODENAME4 ).build();
+ newID = YangInstanceIdentifier.builder(newID).node(NODENAME4).build();
- assertNotNull( "InstanceIdentifier is null", newID );
- assertEquals( "Path size", 4, newID.getPathArguments().size() );
+ assertNotNull("InstanceIdentifier is null", newID);
+ assertEquals("Path size", 4, newID.getPathArguments().size());
it = newID.getPathArguments().iterator();
- assertEquals( "PathArg 1 node type", NODENAME1, it.next().getNodeType() );
- assertEquals( "PathArg 2 node type", NODENAME2, it.next().getNodeType() );
- assertEquals( "PathArg 3 node type", NODENAME3, it.next().getNodeType() );
- assertEquals( "PathArg 4 node type", NODENAME4, it.next().getNodeType() );
+ assertEquals("PathArg 1 node type", NODENAME1, it.next().getNodeType());
+ assertEquals("PathArg 2 node type", NODENAME2, it.next().getNodeType());
+ assertEquals("PathArg 3 node type", NODENAME3, it.next().getNodeType());
+ assertEquals("PathArg 4 node type", NODENAME4, it.next().getNodeType());
- newID = YangInstanceIdentifier.builder().node( NODENAME1 ).build();
+ newID = YangInstanceIdentifier.builder().node(NODENAME1).build();
- assertNotNull( "InstanceIdentifier is null", newID );
- assertEquals( "Path size", 1, newID.getPathArguments().size() );
- assertEquals( "PathArg 1 node type", NODENAME1, newID.getPathArguments().get(0).getNodeType() );
+ assertNotNull("InstanceIdentifier is null", newID);
+ assertEquals("Path size", 1, newID.getPathArguments().size());
+ assertEquals("PathArg 1 node type", NODENAME1, newID.getPathArguments().get(0).getNodeType());
}
private static void verifyNodeIdentifierWithPredicates(final String prefix,
- final PathArgument arg, final QName nodeName, final QName key, final Object value ) {
+ final PathArgument arg, final QName nodeName, final QName key, final Object value) {
- assertNotNull( prefix + " is null", arg );
- assertEquals( prefix + " class", NodeIdentifierWithPredicates.class, arg.getClass() );
+ assertNotNull(prefix + " is null", arg);
+ assertEquals(prefix + " class", NodeIdentifierWithPredicates.class, arg.getClass());
NodeIdentifierWithPredicates node = (NodeIdentifierWithPredicates)arg;
- assertEquals( prefix + " node type", nodeName, node.getNodeType() );
- assertEquals( prefix + " key values map size", 1, node.getKeyValues().size() );
+ assertEquals(prefix + " node type", nodeName, node.getNodeType());
+ assertEquals(prefix + " key values map size", 1, node.getKeyValues().size());
Entry<QName, Object> entry = node.getKeyValues().entrySet().iterator().next();
- assertEquals( prefix + " key values map entry key", key, entry.getKey() );
- assertEquals( prefix + " key values map entry value", value, entry.getValue() );
+ assertEquals(prefix + " key values map entry key", key, entry.getKey());
+ assertEquals(prefix + " key values map entry value", value, entry.getValue());
}
@Test
public void testNodeIdentifierWithPredicates() {
- NodeIdentifierWithPredicates node1 = new NodeIdentifierWithPredicates( NODENAME1, KEY1, "foo" );
- verifyNodeIdentifierWithPredicates( "NodeIdentifierWithPredicates", node1, NODENAME1, KEY1, "foo" );
+ NodeIdentifierWithPredicates node1 = new NodeIdentifierWithPredicates(NODENAME1, KEY1, "foo");
+ verifyNodeIdentifierWithPredicates("NodeIdentifierWithPredicates", node1, NODENAME1, KEY1, "foo");
- NodeIdentifierWithPredicates node2 = new NodeIdentifierWithPredicates( NODENAME1, KEY1, "foo" );
+ NodeIdentifierWithPredicates node2 = new NodeIdentifierWithPredicates(NODENAME1, KEY1, "foo");
- assertEquals( "hashCode", node1.hashCode(), node2.hashCode() );
- assertEquals( "equals", true, node1.equals( node2 ) );
+ assertEquals("hashCode", node1.hashCode(), node2.hashCode());
+ assertEquals("equals", true, node1.equals(node2));
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME2, KEY1, "foo" ) ) );
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME1, KEY2, "foo" ) ) );
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME1, KEY1, "bar" ) ) );
- assertEquals( "equals", false, node1.equals( new Object() ) );
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME2, KEY1, "foo")));
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME1, KEY2, "foo")));
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME1, KEY1, "bar")));
+ assertEquals("equals", false, node1.equals(new Object()));
- assertNotNull( node1.toString() ); // for code coverage
- assertNotNull( node1.toRelativeString(node2) );
+ assertNotNull(node1.toString()); // for code coverage
+ assertNotNull(node1.toRelativeString(node2));
- NodeIdentifierWithPredicates node3 = new NodeIdentifierWithPredicates( NODENAME1,
- ImmutableMap.<QName, Object>builder().put( KEY1, 10 ).put( KEY2, 20 ).build() );
+ NodeIdentifierWithPredicates node3 = new NodeIdentifierWithPredicates(NODENAME1,
+ ImmutableMap.<QName, Object>builder().put(KEY1, 10).put(KEY2, 20).build());
- NodeIdentifierWithPredicates node4 = new NodeIdentifierWithPredicates( NODENAME1,
- ImmutableMap.<QName, Object>builder().put( KEY1, 10 ).put( KEY2, 20 ).build() );
+ NodeIdentifierWithPredicates node4 = new NodeIdentifierWithPredicates(NODENAME1,
+ ImmutableMap.<QName, Object>builder().put(KEY1, 10).put(KEY2, 20).build());
- assertEquals( "hashCode", node3.hashCode(), node4.hashCode() );
- assertEquals( "equals", true, node3.equals( node4 ) );
+ assertEquals("hashCode", node3.hashCode(), node4.hashCode());
+ assertEquals("equals", true, node3.equals(node4));
- assertEquals( "equals", false, node3.equals( node1 ) );
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME1,
- ImmutableMap.<QName, Object>builder().put( KEY1, 10 ).put( KEY3, 20 ).build() ) ) );
+ assertEquals("equals", false, node3.equals(node1));
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME1,
+ ImmutableMap.<QName, Object>builder().put(KEY1, 10).put(KEY3, 20).build())));
- node1 = new NodeIdentifierWithPredicates( NODENAME1, KEY1, new byte[]{1,2} );
- node2 = new NodeIdentifierWithPredicates( NODENAME1, KEY1, new byte[]{1,2} );
+ node1 = new NodeIdentifierWithPredicates(NODENAME1, KEY1, new byte[]{1,2});
+ node2 = new NodeIdentifierWithPredicates(NODENAME1, KEY1, new byte[]{1,2});
- assertEquals( "hashCode", node1.hashCode(), node2.hashCode() );
- assertEquals( "equals", true, node1.equals( node2 ) );
+ assertEquals("hashCode", node1.hashCode(), node2.hashCode());
+ assertEquals("equals", true, node1.equals(node2));
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME1, KEY1, new byte[]{1,3} ) ) );
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME1, KEY1, new byte[]{1} ) ) );
- assertEquals( "equals", false,
- node1.equals( new NodeIdentifierWithPredicates( NODENAME1, KEY1, new byte[]{1,2,3} ) ) );
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME1, KEY1, new byte[]{1,3})));
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME1, KEY1, new byte[]{1})));
+ assertEquals("equals", false,
+ node1.equals(new NodeIdentifierWithPredicates(NODENAME1, KEY1, new byte[]{1,2,3})));
}
@Test
public void testNodeWithValue() {
- NodeWithValue<?> node1 = new NodeWithValue<>( NODENAME1, "foo" );
- assertEquals( "getNodeType", NODENAME1, node1.getNodeType() );
- assertEquals( "getValue", "foo", node1.getValue() );
+ NodeWithValue<?> node1 = new NodeWithValue<>(NODENAME1, "foo");
+ assertEquals("getNodeType", NODENAME1, node1.getNodeType());
+ assertEquals("getValue", "foo", node1.getValue());
- NodeWithValue<?> node2 = new NodeWithValue<>( NODENAME1, "foo" );
+ NodeWithValue<?> node2 = new NodeWithValue<>(NODENAME1, "foo");
- assertEquals( "hashCode", node1.hashCode(), node2.hashCode() );
- assertEquals( "equals", true, node1.equals( node2 ) );
+ assertEquals("hashCode", node1.hashCode(), node2.hashCode());
+ assertEquals("equals", true, node1.equals(node2));
- assertEquals( "equals", false, node1.equals( new NodeWithValue<>( NODENAME1, "bar" ) ) );
- assertEquals( "equals", false, node1.equals( new NodeWithValue<>( NODENAME2, "foo" ) ) );
- assertEquals( "equals", false, node1.equals( new Object() ) );
+ assertEquals("equals", false, node1.equals(new NodeWithValue<>(NODENAME1, "bar")));
+ assertEquals("equals", false, node1.equals(new NodeWithValue<>(NODENAME2, "foo")));
+ assertEquals("equals", false, node1.equals(new Object()));
- assertNotNull( node1.toString() ); // for code coverage
- assertNotNull( node1.toRelativeString(node2) );
+ assertNotNull(node1.toString()); // for code coverage
+ assertNotNull(node1.toRelativeString(node2));
- NodeWithValue<?> node3 = new NodeWithValue<>( NODENAME1, new byte[]{1,2} );
- NodeWithValue<?> node4 = new NodeWithValue<>( NODENAME1, new byte[]{1,2} );
+ NodeWithValue<?> node3 = new NodeWithValue<>(NODENAME1, new byte[]{1,2});
+ NodeWithValue<?> node4 = new NodeWithValue<>(NODENAME1, new byte[]{1,2});
- assertEquals( "hashCode", node3.hashCode(), node4.hashCode() );
- assertEquals( "equals", true, node3.equals( node4 ) );
+ assertEquals("hashCode", node3.hashCode(), node4.hashCode());
+ assertEquals("equals", true, node3.equals(node4));
- assertEquals( "equals", false, node3.equals( new NodeWithValue<>( NODENAME1, new byte[]{1,3} ) ) );
- assertEquals( "equals", false, node3.equals( node1 ) );
+ assertEquals("equals", false, node3.equals(new NodeWithValue<>(NODENAME1, new byte[]{1,3})));
+ assertEquals("equals", false, node3.equals(node1));
}
@Test
public void testNodeIdentifier() {
- NodeIdentifier node1 = new NodeIdentifier( NODENAME1 );
- assertEquals( "getNodeType", NODENAME1, node1.getNodeType() );
- NodeIdentifier node2 = new NodeIdentifier( NODENAME1 );
- AugmentationIdentifier node3 = new AugmentationIdentifier( Sets.newHashSet( NODENAME1, NODENAME2 ) );
+ final NodeIdentifier node1 = new NodeIdentifier(NODENAME1);
+ assertEquals("getNodeType", NODENAME1, node1.getNodeType());
+ final NodeIdentifier node2 = new NodeIdentifier(NODENAME1);
+ final AugmentationIdentifier node3 = new AugmentationIdentifier(Sets.newHashSet(NODENAME1, NODENAME2));
- assertEquals( "hashCode", node1.hashCode(), node2.hashCode() );
- assertEquals( "compareTo", 0, node1.compareTo( node2 ) );
- assertEquals( "compareTo", true, node1.compareTo( new NodeIdentifier( NODENAME3 ) ) != 0 );
+ assertEquals("hashCode", node1.hashCode(), node2.hashCode());
+ assertEquals("compareTo", 0, node1.compareTo(node2));
+ assertEquals("compareTo", true, node1.compareTo(new NodeIdentifier(NODENAME3)) != 0);
- assertEquals( "equals", false, node1.equals( null ) );
- assertEquals( "equals", false, node1.equals( node3 ) );
- assertEquals( "equals", true, node1.equals( node1 ) );
- assertEquals( "equals", true, node1.equals( node2 ) );
- assertEquals( "equals", false, node1.equals( new NodeIdentifier( NODENAME3 ) ) );
- assertEquals( "equals", false, node1.equals( new Object() ) );
+ assertEquals("equals", false, node1.equals(null));
+ assertEquals("equals", false, node1.equals(node3));
+ assertEquals("equals", true, node1.equals(node1));
+ assertEquals("equals", true, node1.equals(node2));
+ assertEquals("equals", false, node1.equals(new NodeIdentifier(NODENAME3)));
+ assertEquals("equals", false, node1.equals(new Object()));
- assertNotNull( node1.toString() ); // for code coverage
+ assertNotNull(node1.toString()); // for code coverage
}
- @Test(expected=UnsupportedOperationException.class)
+ @Test(expected = UnsupportedOperationException.class)
public void testAugmentationIdentifierNodeType() {
- AugmentationIdentifier node1 = new AugmentationIdentifier( Sets.newHashSet( NODENAME1, NODENAME2 ) );
+ AugmentationIdentifier node1 = new AugmentationIdentifier(Sets.newHashSet(NODENAME1, NODENAME2));
node1.getNodeType();
}
@Test
public void testAugmentationIdentifier() {
- AugmentationIdentifier node1 = new AugmentationIdentifier( Sets.newHashSet( NODENAME1, NODENAME2 ) );
- assertEquals( "getPossibleChildNames", Sets.newHashSet( NODENAME1, NODENAME2 ), node1.getPossibleChildNames() );
- AugmentationIdentifier node2 = new AugmentationIdentifier( Sets.newHashSet( NODENAME2, NODENAME1 ) );
- AugmentationIdentifier node3 = new AugmentationIdentifier( Sets.newHashSet( NODENAME1, NODENAME3 ) );
- AugmentationIdentifier node4 = new AugmentationIdentifier( Sets.newHashSet( NODENAME1, NODENAME2, NODENAME3 ) );
- NodeIdentifier node5 = new NodeIdentifier( NODENAME3 );
-
- assertEquals( "hashCode", node1.hashCode(), node2.hashCode() );
-
- assertEquals( "equals", true, node1.equals( node1 ) );
- assertEquals( "equals", true, node1.equals( node2 ) );
- assertEquals( "equals", false, node1.equals( node3 ) );
- assertEquals( "equals", false, node1.equals( new AugmentationIdentifier( Sets.newHashSet( NODENAME1 ) ) ) );
- assertEquals( "equals", false, node1.equals( new Object() ) );
-
- assertEquals( "compareTo", -1, node1.compareTo( node5 ) );
- assertNotEquals( "compareTo", -1, node1.compareTo( node2 ) );
- assertEquals( "compareTo", 0, node1.compareTo( node2 ) );
- assertEquals( "compareTo", 1, node1.compareTo( node4 ) );
- assertEquals( "compareTo", -1, node4.compareTo( node1 ) );
-
- assertNotNull( node1.toString() ); // for code coverage
- assertNotNull( node1.toRelativeString(node5));
+ final AugmentationIdentifier node1 = new AugmentationIdentifier(Sets.newHashSet(NODENAME1, NODENAME2));
+ assertEquals("getPossibleChildNames", Sets.newHashSet(NODENAME1, NODENAME2), node1.getPossibleChildNames());
+ final AugmentationIdentifier node2 = new AugmentationIdentifier(Sets.newHashSet(NODENAME2, NODENAME1));
+ final AugmentationIdentifier node3 = new AugmentationIdentifier(Sets.newHashSet(NODENAME1, NODENAME3));
+ final AugmentationIdentifier node4 = new AugmentationIdentifier(Sets.newHashSet(NODENAME1, NODENAME2,
+ NODENAME3));
+ final NodeIdentifier node5 = new NodeIdentifier(NODENAME3);
+
+ assertEquals("hashCode", node1.hashCode(), node2.hashCode());
+
+ assertEquals("equals", true, node1.equals(node1));
+ assertEquals("equals", true, node1.equals(node2));
+ assertEquals("equals", false, node1.equals(node3));
+ assertEquals("equals", false, node1.equals(new AugmentationIdentifier(Sets.newHashSet(NODENAME1))));
+ assertEquals("equals", false, node1.equals(new Object()));
+
+ assertEquals("compareTo", -1, node1.compareTo(node5));
+ assertNotEquals("compareTo", -1, node1.compareTo(node2));
+ assertEquals("compareTo", 0, node1.compareTo(node2));
+ assertEquals("compareTo", 1, node1.compareTo(node4));
+ assertEquals("compareTo", -1, node4.compareTo(node1));
+
+ assertNotNull(node1.toString()); // for code coverage
+ assertNotNull(node1.toRelativeString(node5));
}
- private static YangInstanceIdentifier serdes(final YangInstanceIdentifier id) throws IOException, ClassNotFoundException {
+ private static YangInstanceIdentifier serdes(final YangInstanceIdentifier id) throws IOException,
+ ClassNotFoundException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (final ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(id);
final DataContainerNode<?> mockedDataContainerNode = mock(DataContainerNode.class);
final ContainerNode mockedContainerNode = mock(ContainerNode.class);
doReturn(Optional.of(mockedContainerNode)).when(mockedDataContainerNode).getChild(any(PathArgument.class));
- assertEquals(mockedContainerNode, NormalizedNodes.getDirectChild(mockedDataContainerNode, mockedPathArgument).get());
+ assertEquals(mockedContainerNode, NormalizedNodes.getDirectChild(mockedDataContainerNode, mockedPathArgument)
+ .get());
final MapNode mockedMapNode = mock(MapNode.class);
final QName listQName = QName.create("test-ns", "test-list");
new NodeIdentifierWithPredicates(listQName, listKeyQName, "str-value");
final MapEntryNode mockedMapEntryNode = mock(MapEntryNode.class);
doReturn(Optional.of(mockedMapEntryNode)).when(mockedMapNode).getChild(any(NodeIdentifierWithPredicates.class));
- assertEquals(mockedMapEntryNode, NormalizedNodes.getDirectChild(mockedMapNode, nodeIdentifierWithPredicates).get());
+ assertEquals(mockedMapEntryNode, NormalizedNodes.getDirectChild(mockedMapNode, nodeIdentifierWithPredicates)
+ .get());
assertEquals(Optional.absent(), NormalizedNodes.getDirectChild(mockedMapNode, mockedPathArgument));
final LeafSetNode<?> mockedLeafSetNode = mock(LeafSetNode.class);
stringTree = NormalizedNodes.toStringTree(mockedAugmentationNode);
assertNotNull(stringTree);
- assertEquals("augmentation {\n list-node {\n list-node[key-leaf-value] {\n leaf-node " +
- "str-value-1\n }\n }\n}\n", stringTree);
+ assertEquals("augmentation {\n list-node {\n list-node[key-leaf-value] {\n leaf-node "
+ + "str-value-1\n }\n }\n}\n", stringTree);
}
}
@Test
public void testNormalizedNodeWriter() throws IOException {
final NormalizedNodeStreamWriter loggingNormalizedNodeStreamWriter = new LoggingNormalizedNodeStreamWriter();
- final NormalizedNodeWriter orderedNormalizedNodeWriter = NormalizedNodeWriter.forStreamWriter
- (loggingNormalizedNodeStreamWriter);
+ final NormalizedNodeWriter orderedNormalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
+ loggingNormalizedNodeStreamWriter);
assertEquals(loggingNormalizedNodeStreamWriter, orderedNormalizedNodeWriter.getWriter());
orderedNormalizedNodeWriter.flush();
orderedNormalizedNodeWriter.close();
- final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter
- (loggingNormalizedNodeStreamWriter, false);
+ final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
+ loggingNormalizedNodeStreamWriter, false);
assertNotNull(normalizedNodeWriter.write(mockedMapEntryNode));
@Test
public void testFromNormalizedNode() {
final NormalizedNode<?, ?> mockedNormalizedNode = mock(NormalizedNode.class);
- final DataTreeCandidateNode dataTreeCandidateNode = DataTreeCandidateNodes.fromNormalizedNode(mockedNormalizedNode);
+ final DataTreeCandidateNode dataTreeCandidateNode = DataTreeCandidateNodes.fromNormalizedNode(
+ mockedNormalizedNode);
assertNotNull(dataTreeCandidateNode);
}
doReturn(Optional.absent()).when(mockedNormalizedNodeContainer).getChild(any(PathArgument.class));
assertNull(normalizedNodeDataTreeCandidateNode2.getModifiedChild(mockedPathArgument));
- doReturn(Optional.of(mockedChildNormNode1)).when(mockedNormalizedNodeContainer).getChild(any(PathArgument.class));
+ doReturn(Optional.of(mockedChildNormNode1)).when(mockedNormalizedNodeContainer).getChild(
+ any(PathArgument.class));
assertNotNull(normalizedNodeDataTreeCandidateNode2.getModifiedChild(mockedPathArgument));
}
}
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
+
import java.util.Map;
import org.junit.Test;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
+
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
package org.opendaylight.yangtools.yang.data.api.schema.tree.spi;
import static org.junit.Assert.assertFalse;
+
import org.junit.Test;
public class VersionTest {
assertFalse(v1.equals(v2));
assertFalse(v2.equals(v1));
- }
+ }
@Test
public void testNext() {