<artifactId>jsr305</artifactId>
<scope>provided</scope>
</dependency>
-
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-test-model</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-test-model</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
</dependency>
<dependency><groupId>junit</groupId>
<artifactId>junit</artifactId>
}
- private class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
+ private static class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
private final ImmutableSortedMap<QName, ValueContext> keyValueContexts;
private final ListSchemaNode schema;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSortedMap;
import java.lang.reflect.Method;
import java.util.Collection;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.SortedMap;
+import java.util.TreeMap;
import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.binding.Augmentable;
abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataContainerCodecContext<T> {
private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
+ private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
+
+ @Override
+ public int compare(final Method o1, final Method o2) {
+ return o1.getName().compareTo(o2.getName());
+ }
+ };
+
private final ImmutableMap<String, LeafNodeCodecContext> leafChild;
private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
- private final ImmutableMap<Method, NodeContextSupplier> byMethod;
+ private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
protected final Method augmentationGetter;
Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass());
Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
- Map<Method, NodeContextSupplier> byMethodBuilder = new HashMap<>();
+ SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
}
}
}
- this.byMethod = ImmutableMap.copyOf(byMethodBuilder);
+ this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
if (Augmentable.class.isAssignableFrom(bindingClass())) {
try {
augmentationGetter = bindingClass().getMethod("getAugmentation", Class.class);
return byMethod.keySet();
}
-}
\ No newline at end of file
+}
*/
package org.opendaylight.yangtools.binding.data.codec.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Collections;
-import java.util.Map.Entry;
-
import javassist.ClassPool;
-
import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcComplexUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcComplexUsesAugmentBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugmentBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeLeafOnlyAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ContainerWithUsesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUses;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.RpcComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.RpcComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ContainerWithUsesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ListViaUses;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListKey;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import java.util.Collections;
+
+import static org.junit.Assert.assertEquals;
+
public class AugmentationSubstitutionTest extends AbstractBindingRuntimeTest {
*/
package org.opendaylight.yangtools.binding.data.codec.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Collections;
-import java.util.Map.Entry;
-
import javassist.ClassPool;
-
import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcComplexUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcComplexUsesAugmentBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugmentBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeLeafOnlyAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ContainerWithUsesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUses;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.put.top.input.top.level.list.choice.in.list.ComplexViaUsesWithDifferentNameBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.top.top.level.list.choice.in.list.ComplexViaUsesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.RpcComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.RpcComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ContainerWithUsesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ListViaUses;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.put.top.input.top.level.list.choice.in.list.ComplexViaUsesWithDifferentNameBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.top.top.level.list.choice.in.list.ComplexViaUsesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListKey;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import java.util.Collections;
+
+import static org.junit.Assert.assertEquals;
+
public class CaseSubstitutionTest extends AbstractBindingRuntimeTest {
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.test;
+
+import com.google.common.collect.Iterables;
+import javassist.ClassPool;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
+import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
+import org.opendaylight.yangtools.yang.binding.Identifier;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class InstanceIdentifierSerializeDeserializeTest extends AbstractBindingRuntimeTest{
+ public static final String TOP_LEVEL_LIST_KEY_VALUE = "foo";
+
+ private static final TopLevelListKey TOP_FOO_KEY = new TopLevelListKey("foo");
+ private static final InstanceIdentifier<TopLevelList> BA_TOP_LEVEL_LIST = InstanceIdentifier
+ .builder(Top.class).child(TopLevelList.class, TOP_FOO_KEY).toInstance();
+ private static final InstanceIdentifier<TreeLeafOnlyAugment> BA_TREE_LEAF_ONLY =
+ BA_TOP_LEVEL_LIST.augmentation(TreeLeafOnlyAugment.class);
+ private static final InstanceIdentifier<TreeComplexUsesAugment> BA_TREE_COMPLEX_USES =
+ BA_TOP_LEVEL_LIST.augmentation(TreeComplexUsesAugment.class);
+
+ public static final QName TOP_QNAME =
+ QName.create("urn:opendaylight:params:xml:ns:yang:yangtools:test:binding", "2014-07-01", "top");
+ public static final QName TOP_LEVEL_LIST_QNAME = QName.create(TOP_QNAME, "top-level-list");
+ public static final QName TOP_LEVEL_LIST_KEY = QName.create(TOP_QNAME, "name");
+ private static final QName SIMPLE_VALUE_QNAME = QName.create(TreeComplexUsesAugment.QNAME, "simple-value");
+
+ public static final YangInstanceIdentifier BI_TOP_PATH = YangInstanceIdentifier.builder().node(TOP_QNAME).build();
+ public static final YangInstanceIdentifier BI_TOP_LEVEL_LIST_PATH = BI_TOP_PATH.node(TOP_LEVEL_LIST_QNAME);
+ public static final YangInstanceIdentifier BI_TOP_LEVEL_LIST_1_PATH = BI_TOP_LEVEL_LIST_PATH
+ .node(new YangInstanceIdentifier.NodeIdentifierWithPredicates(TOP_LEVEL_LIST_QNAME, TOP_LEVEL_LIST_KEY, TOP_LEVEL_LIST_KEY_VALUE));
+
+ private BindingNormalizedNodeCodecRegistry registry;
+
+ @Before
+ public void setup() {
+ super.setup();
+ JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault());
+ registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils));
+ registry.onBindingRuntimeContextUpdated(getRuntimeContext());
+ }
+
+ @Test
+ public void testYangIIToBindingAwareII() {
+ InstanceIdentifier<?> instanceIdentifier = registry.fromYangInstanceIdentifier(BI_TOP_PATH);
+ assertEquals(Top.class, instanceIdentifier.getTargetType());
+ }
+
+ @Test
+ public void testYangIIToBindingAwareIIListWildcarded() {
+ InstanceIdentifier<?> instanceIdentifier = registry.fromYangInstanceIdentifier(BI_TOP_LEVEL_LIST_PATH);
+ assertEquals(TopLevelList.class, instanceIdentifier.getTargetType());
+ assertTrue(instanceIdentifier.isWildcarded());
+ }
+
+ @Test
+ public void testYangIIToBindingAwareIIListWithKey() {
+ InstanceIdentifier<?> instanceIdentifier = registry.fromYangInstanceIdentifier(BI_TOP_LEVEL_LIST_1_PATH);
+ InstanceIdentifier.PathArgument last = Iterables.getLast(instanceIdentifier.getPathArguments());
+ assertEquals(TopLevelList.class, instanceIdentifier.getTargetType());
+ assertFalse(instanceIdentifier.isWildcarded());
+ assertTrue(last instanceof InstanceIdentifier.IdentifiableItem);
+ Identifier key = ((InstanceIdentifier.IdentifiableItem) last).getKey();
+ assertEquals(TopLevelListKey.class, key.getClass());
+ assertEquals(TOP_LEVEL_LIST_KEY_VALUE, ((TopLevelListKey)key).getName());
+ }
+
+ @Test
+ public void testBindingAwareIIToYangIContainer() {
+ YangInstanceIdentifier yangInstanceIdentifier = registry.toYangInstanceIdentifier(
+ InstanceIdentifier.create(Top.class).child(TopLevelList.class));
+ YangInstanceIdentifier.PathArgument lastPathArgument = yangInstanceIdentifier.getLastPathArgument();
+ assertTrue(lastPathArgument instanceof YangInstanceIdentifier.NodeIdentifier);
+ assertEquals(TopLevelList.QNAME, lastPathArgument.getNodeType());
+ }
+
+ @Test
+ public void testBindingAwareIIToYangIIWildcard() {
+ YangInstanceIdentifier yangInstanceIdentifier = registry.toYangInstanceIdentifier(
+ InstanceIdentifier.create(Top.class).child(TopLevelList.class));
+ YangInstanceIdentifier.PathArgument lastPathArgument = yangInstanceIdentifier.getLastPathArgument();
+ assertTrue(lastPathArgument instanceof YangInstanceIdentifier.NodeIdentifier);
+ assertEquals(TopLevelList.QNAME, lastPathArgument.getNodeType());
+ }
+
+ @Test
+ public void testBindingAwareIIToYangIIListWithKey() {
+ YangInstanceIdentifier yangInstanceIdentifier = registry.toYangInstanceIdentifier(
+ InstanceIdentifier.create(Top.class).child(TopLevelList.class, TOP_FOO_KEY));
+ YangInstanceIdentifier.PathArgument lastPathArgument = yangInstanceIdentifier.getLastPathArgument();
+ assertTrue(lastPathArgument instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates);
+ assertTrue(((YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument).getKeyValues().containsValue(TOP_LEVEL_LIST_KEY_VALUE));
+ assertEquals(TopLevelList.QNAME, lastPathArgument.getNodeType());
+ }
+
+ @Test
+ public void testBindingAwareIIToYangIIAugmentation() {
+ YangInstanceIdentifier.PathArgument lastArg = registry.toYangInstanceIdentifier(BA_TREE_COMPLEX_USES).getLastPathArgument();
+ assertTrue(lastArg instanceof YangInstanceIdentifier.AugmentationIdentifier);
+ }
+
+ @Test
+ public void testBindingAwareIIToYangIILeafOnlyAugmentation() {
+ YangInstanceIdentifier.PathArgument leafOnlyLastArg = registry.toYangInstanceIdentifier(BA_TREE_LEAF_ONLY).getLastPathArgument();
+ assertTrue(leafOnlyLastArg instanceof YangInstanceIdentifier.AugmentationIdentifier);
+ assertTrue(((YangInstanceIdentifier.AugmentationIdentifier) leafOnlyLastArg).getPossibleChildNames().contains(SIMPLE_VALUE_QNAME));
+ }
+}
*/
package org.opendaylight.yangtools.binding.data.codec.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import javassist.ClassPool;
-
import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeLeafOnlyAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListKey;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
public class InstanceIdentifierTest extends AbstractBindingRuntimeTest {
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.test;
+
+import javassist.ClassPool;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.ChoiceContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.ChoiceContainerBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.TopBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.choice.identifier.ExtendedBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.choice.identifier.extended.ExtendedIdBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.top.level.list.NestedList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.top.level.list.NestedListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.top.level.list.NestedListKey;
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
+import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableAugmentationNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedMapNodeBuilder;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.top;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.topLevelList;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
+
+public class NormalizedNodeSerializeDeserializeTest extends AbstractBindingRuntimeTest{
+
+ public static final String TOP_LEVEL_LIST_FOO_KEY_VALUE = "foo";
+ public static final TopLevelListKey TOP_LEVEL_LIST_FOO_KEY = new TopLevelListKey(TOP_LEVEL_LIST_FOO_KEY_VALUE);
+
+ public static final QName TOP_QNAME =
+ QName.create("urn:opendaylight:params:xml:ns:yang:yangtools:test:binding", "2014-07-01", "top");
+ public static final QName TOP_LEVEL_LIST_QNAME = QName.create(TOP_QNAME, "top-level-list");
+ public static final QName TOP_LEVEL_LIST_KEY_QNAME = QName.create(TOP_QNAME, "name");
+ public static final QName TOP_LEVEL_LEAF_LIST_QNAME = QName.create(TOP_QNAME, "top-level-leaf-list");
+ public static final QName NESTED_LIST_QNAME = QName.create(TOP_QNAME, "nested-list");
+ public static final QName NESTED_LIST_KEY_QNAME = QName.create(TOP_QNAME, "name");
+ public static final QName CHOICE_CONTAINER_QNAME =
+ QName.create("urn:opendaylight:params:xml:ns:yang:yangtools:test:binding", "2014-07-01", "choice-container");
+ public static final QName CHOICE_IDENTIFIER_QNAME = QName.create(CHOICE_CONTAINER_QNAME, "identifier");
+ public static final QName CHOICE_IDENTIFIER_ID_QNAME = QName.create(CHOICE_CONTAINER_QNAME, "id");
+ public static final QName SIMPLE_ID_QNAME = QName.create(CHOICE_CONTAINER_QNAME, "simple-id");
+ public static final QName EXTENDED_ID_QNAME = QName.create(CHOICE_CONTAINER_QNAME, "extended-id");
+ private static final QName SIMPLE_VALUE_QNAME = QName.create(TreeComplexUsesAugment.QNAME, "simple-value");
+
+ private static final InstanceIdentifier<TopLevelList> BA_TOP_LEVEL_LIST = InstanceIdentifier
+ .builder(Top.class).child(TopLevelList.class, TOP_LEVEL_LIST_FOO_KEY).toInstance();
+ private static final InstanceIdentifier<TreeLeafOnlyAugment> BA_TREE_LEAF_ONLY =
+ BA_TOP_LEVEL_LIST.augmentation(TreeLeafOnlyAugment.class);
+ private static final InstanceIdentifier<TreeComplexUsesAugment> BA_TREE_COMPLEX_USES =
+ BA_TOP_LEVEL_LIST.augmentation(TreeComplexUsesAugment.class);
+
+ public static final YangInstanceIdentifier BI_TOP_PATH = YangInstanceIdentifier.of(TOP_QNAME);
+ public static final YangInstanceIdentifier BI_TOP_LEVEL_LIST_PATH = BI_TOP_PATH.node(TOP_LEVEL_LIST_QNAME);
+ public static final YangInstanceIdentifier BI_TOP_LEVEL_LIST_FOO_PATH = BI_TOP_LEVEL_LIST_PATH
+ .node(new YangInstanceIdentifier.NodeIdentifierWithPredicates(TOP_LEVEL_LIST_QNAME, TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE));
+ public static final YangInstanceIdentifier BI_CHOICE_CONTAINER_PATH = YangInstanceIdentifier.of(CHOICE_CONTAINER_QNAME);
+
+ private BindingNormalizedNodeCodecRegistry registry;
+
+ @Before
+ public void setup() {
+ super.setup();
+ JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault());
+ registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils));
+ registry.onBindingRuntimeContextUpdated(getRuntimeContext());
+ }
+
+ @Test
+ public void containerToNormalized() {
+ Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry =
+ registry.toNormalizedNode(InstanceIdentifier.create(Top.class), top());
+ ContainerNode topNormalized = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TOP_QNAME))
+ .withChild(mapNodeBuilder(TOP_LEVEL_LIST_QNAME).build()).build();
+ assertEquals(topNormalized, entry.getValue());
+ }
+
+ @Test
+ public void containerFromNormalized() {
+ ContainerNode topNormalized = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TOP_QNAME))
+ .withChild(mapNodeBuilder(TOP_LEVEL_LIST_QNAME).build()).build();
+ Map.Entry<InstanceIdentifier<?>, DataObject> entry = registry.fromNormalizedNode(BI_TOP_PATH, topNormalized);
+ assertEquals(top(), entry.getValue());
+ }
+
+ @Test
+ public void listWithKeysToNormalized() {
+ Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry =
+ registry.toNormalizedNode(BA_TOP_LEVEL_LIST, topLevelList(TOP_LEVEL_LIST_FOO_KEY));
+ MapEntryNode topLevelListNormalized = ImmutableMapEntryNodeBuilder.create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+ TOP_LEVEL_LIST_QNAME, TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .withChild(leafNode(TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .build();
+ assertEquals(topLevelListNormalized, entry.getValue());
+ }
+
+ @Test
+ public void listWithKeysFromNormalized() {
+ MapEntryNode topLevelListNormalized = ImmutableMapEntryNodeBuilder.create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+ TOP_LEVEL_LIST_QNAME, TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .withChild(leafNode(TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .build();
+ Map.Entry<InstanceIdentifier<?>, DataObject> entry =
+ registry.fromNormalizedNode(BI_TOP_LEVEL_LIST_FOO_PATH, topLevelListNormalized);
+ assertEquals(topLevelList(TOP_LEVEL_LIST_FOO_KEY), entry.getValue());
+ }
+
+ @Test
+ public void leafOnlyAugmentationToNormalized() {
+ Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry =
+ registry.toNormalizedNode(BA_TREE_LEAF_ONLY, new TreeLeafOnlyAugmentBuilder().setSimpleValue("simpleValue").build());
+ Set<QName> augmentationChildren = new HashSet<>();
+ augmentationChildren.add(SIMPLE_VALUE_QNAME);
+ AugmentationNode augmentationNode = ImmutableAugmentationNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.AugmentationIdentifier(augmentationChildren))
+ .withChild(leafNode(SIMPLE_VALUE_QNAME, "simpleValue"))
+ .build();
+ assertEquals(augmentationNode, entry.getValue());
+ }
+
+ @Test
+ public void leafOnlyAugmentationFromNormalized() {
+ Set<QName> augmentationChildren = new HashSet<>();
+ augmentationChildren.add(SIMPLE_VALUE_QNAME);
+ AugmentationNode augmentationNode = ImmutableAugmentationNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.AugmentationIdentifier(augmentationChildren))
+ .withChild(leafNode(SIMPLE_VALUE_QNAME, "simpleValue"))
+ .build();
+ Map.Entry<InstanceIdentifier<?>, DataObject> entry = registry.fromNormalizedNode(BI_TOP_LEVEL_LIST_FOO_PATH.node(
+ new YangInstanceIdentifier.AugmentationIdentifier(augmentationChildren)), augmentationNode);
+ assertEquals(new TreeLeafOnlyAugmentBuilder().setSimpleValue("simpleValue").build(), entry.getValue());
+ }
+
+ @Test
+ public void leafListToNormalized() {
+ List<String> topLevelLeafList = new ArrayList<>();
+ topLevelLeafList.add("foo");
+ Top top = new TopBuilder().setTopLevelLeafList(topLevelLeafList).build();
+
+ Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry =
+ registry.toNormalizedNode(InstanceIdentifier.create(Top.class), top);
+ ContainerNode containerNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TOP_QNAME))
+ .withChild(ImmutableLeafSetNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TOP_LEVEL_LEAF_LIST_QNAME))
+ .withChild(
+ ImmutableLeafSetEntryNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeWithValue(TOP_LEVEL_LEAF_LIST_QNAME, "foo"))
+ .withValue("foo")
+ .build())
+ .build())
+ .build();
+ assertEquals(containerNode, entry.getValue());
+ }
+
+ @Test
+ public void leafListFromNormalized() {
+ ContainerNode topWithLeafList = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TOP_QNAME))
+ .withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TOP_LEVEL_LEAF_LIST_QNAME))
+ .withChild(ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue(TOP_LEVEL_LEAF_LIST_QNAME, "foo")).withValue("foo").build()).build())
+ .build();
+ Map.Entry<InstanceIdentifier<?>, DataObject> entry = registry.fromNormalizedNode(BI_TOP_PATH, topWithLeafList);
+ List<String> topLevelLeafList = new ArrayList<>();
+ topLevelLeafList.add("foo");
+ Top top = new TopBuilder().setTopLevelLeafList(topLevelLeafList).build();
+ assertEquals(top, entry.getValue());
+ }
+
+ @Test
+ public void choiceToNormalized() {
+ ChoiceContainer choiceContainerBA = new ChoiceContainerBuilder().setIdentifier(new ExtendedBuilder().setExtendedId(
+ new ExtendedIdBuilder().setId("identifier_value").build()).build()).build();
+ Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry =
+ registry.toNormalizedNode(InstanceIdentifier.create(ChoiceContainer.class), choiceContainerBA);
+ ContainerNode choiceContainer = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CHOICE_CONTAINER_QNAME))
+ .withChild(ImmutableChoiceNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CHOICE_IDENTIFIER_QNAME))
+ .withChild(ImmutableContainerNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(EXTENDED_ID_QNAME))
+ .withChild(leafNode(CHOICE_IDENTIFIER_ID_QNAME, "identifier_value")).build()).build())
+ .build();
+ assertEquals(choiceContainer, entry.getValue());
+ }
+
+ @Test
+ public void choiceFromNormalized() {
+ ContainerNode choiceContainerBI = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CHOICE_CONTAINER_QNAME))
+ .withChild(ImmutableChoiceNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CHOICE_IDENTIFIER_QNAME))
+ .withChild(ImmutableContainerNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(EXTENDED_ID_QNAME))
+ .withChild(leafNode(CHOICE_IDENTIFIER_ID_QNAME, "identifier_value")).build()).build())
+ .build();
+ Map.Entry<InstanceIdentifier<?>, DataObject> entry = registry.fromNormalizedNode(BI_CHOICE_CONTAINER_PATH, choiceContainerBI);
+ ChoiceContainer choiceContainerBA = new ChoiceContainerBuilder().setIdentifier(new ExtendedBuilder().setExtendedId(
+ new ExtendedIdBuilder().setId("identifier_value").build()).build()).build();
+ assertEquals(choiceContainerBA, entry.getValue());
+ }
+
+ @Test
+ public void orderedLisToNormalized() {
+ InstanceIdentifier<TopLevelList> ii = BA_TOP_LEVEL_LIST;
+ List<NestedList> nestedLists = new ArrayList<>();
+ nestedLists.add(new NestedListBuilder().setKey(new NestedListKey("foo")).build());
+ nestedLists.add(new NestedListBuilder().setKey(new NestedListKey("bar")).build());
+ TopLevelList topLevelList = new TopLevelListBuilder().setKey(TOP_LEVEL_LIST_FOO_KEY).setNestedList(nestedLists).build();
+ Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> entry = registry.toNormalizedNode(ii, topLevelList);
+ MapEntryNode foo = mapEntryBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+ TOP_LEVEL_LIST_QNAME, TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .withChild(leafNode(TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .withChild(
+ ImmutableOrderedMapNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NESTED_LIST_QNAME))
+ .withChild(mapEntry(NESTED_LIST_QNAME, NESTED_LIST_KEY_QNAME, "foo"))
+ .withChild(mapEntry(NESTED_LIST_QNAME, NESTED_LIST_KEY_QNAME, "bar")).build()).build();
+ assertEquals(foo, entry.getValue());
+ }
+
+ @Test
+ public void orderedLisFromNormalized() {
+ MapEntryNode foo = mapEntryBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+ TOP_LEVEL_LIST_QNAME, TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .withChild(leafNode(TOP_LEVEL_LIST_KEY_QNAME, TOP_LEVEL_LIST_FOO_KEY_VALUE))
+ .withChild(
+ ImmutableOrderedMapNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NESTED_LIST_QNAME))
+ .withChild(mapEntry(NESTED_LIST_QNAME, NESTED_LIST_KEY_QNAME, "foo"))
+ .withChild(mapEntry(NESTED_LIST_QNAME, NESTED_LIST_KEY_QNAME, "bar")).build()).build();
+ InstanceIdentifier<TopLevelList> ii = BA_TOP_LEVEL_LIST;
+
+ Map.Entry<InstanceIdentifier<?>, DataObject> entry = registry.fromNormalizedNode(BI_TOP_LEVEL_LIST_FOO_PATH, foo);
+ List<NestedList> nestedLists = new ArrayList<>();
+ nestedLists.add(new NestedListBuilder().setKey(new NestedListKey("foo")).build());
+ nestedLists.add(new NestedListBuilder().setKey(new NestedListKey("bar")).build());
+ TopLevelList topLevelList = new TopLevelListBuilder().setKey(TOP_LEVEL_LIST_FOO_KEY).setNestedList(nestedLists).build();
+ assertEquals(topLevelList, entry.getValue());
+ }
+}
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
return null;
}
final String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
- final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf);
+ final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, node, childOf, module);
genType.addComment(node.getDescription());
genType.setDescription(createDescription(node, genType.getFullyQualifiedName()));
genType.setModuleName(module.getName());
processUsesAugments(notification, module);
final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName,
- notification, BindingTypes.DATA_OBJECT);
+ notification, BindingTypes.DATA_OBJECT, module);
notificationInterface.addImplementsType(NOTIFICATION);
genCtx.get(module).addChildNodeType(notification, notificationInterface);
*/
private void groupingToGenType(final String basePackageName, final GroupingDefinition grouping, final Module module) {
final String packageName = packageNameForGeneratedType(basePackageName, grouping.getPath());
- final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping);
+ final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(packageName, grouping, module);
genCtx.get(module).addGroupingType(grouping.getPath(), genType);
resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes());
groupingsToGenTypes(module, grouping.getGroupings());
for (ChoiceCaseNode caseNode : caseNodes) {
if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
- final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode);
+ final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
caseTypeBuilder.addImplementsType(refChoiceType);
genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
for (DataSchemaNode caseNode : augmentedNodes) {
if (caseNode != null) {
final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
- final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode);
+ final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
caseTypeBuilder.addImplementsType(targetType);
SchemaNode parent = null;
return returnType.toInstance();
}
- private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
- return addDefaultInterfaceDefinition(packageName, schemaNode, null);
+ private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
+ final Module module) {
+ return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
}
/**
* @return generated type builder <code>schemaNode</code>
*/
private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
- final Type parent) {
+ final Type parent, final Module module) {
final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
if (parent == null) {
it.addImplementsType(DATA_OBJECT);
}
if (schemaNode instanceof DataNodeContainer) {
+ groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
}
genTOBuilders.addAll(types);
GeneratedTOBuilder resultTOBuilder = null;
- if (!types.isEmpty()) {
- resultTOBuilder = types.remove(0);
- for (GeneratedTOBuilder genTOBuilder : types) {
- resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
- }
+ if (types.isEmpty()) {
+ throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
+ }
+ resultTOBuilder = types.remove(0);
+ for (GeneratedTOBuilder genTOBuilder : types) {
+ resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
}
final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
-
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-
import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
import org.opendaylight.yangtools.binding.generator.util.Types;
import org.opendaylight.yangtools.concepts.Delegator;
while (iterator.hasNext()) {
QName arg = iterator.next();
DataSchemaNode currentNode = previous.getDataChildByName(arg);
- if (currentNode == null && previous instanceof DataNodeContainer) {
+ if (currentNode == null) {
currentNode = searchInChoices(previous, arg);
}
if (currentNode instanceof DataNodeContainer) {
if (!parentQName.equals(choiceName)) {
// This item is instantiation of choice via uses in other YANG
// module
- if (choiceName.getNamespace().equals(schema.getQName())) {
+ if (choiceName.getNamespace().equals(schema.getQName().getNamespace())) {
// Original definition of grouping is in same namespace
// as original definition of case
// so for sure case is introduced via instantiation of
«generateFields(false)»
- «generateAugmentField(true)»
+ «generateAugmentField(false)»
«generateConstructorsFromIfcs(type)»
«generateFields(true)»
- «generateAugmentField(false)»
+ «generateAugmentField(true)»
«generateCopyConstructor(true)»
«ENDIF»
'''
- def private generateAugmentField(boolean init) '''
+ def private generateAugmentField(boolean isPrivate) '''
«IF augmentField != null»
- private «Map.importedName»<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> «augmentField.name» = new «HashMap.importedName»<>();
+ «IF isPrivate»private «ENDIF»«Map.importedName»<«Class.importedName»<? extends «augmentField.returnType.importedName»>, «augmentField.returnType.importedName»> «augmentField.name» = new «HashMap.importedName»<>();
«ENDIF»
'''
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.sal.java.api.generator.test;
+
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.BASE_PKG;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.COMPILER_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.FS;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.GENERATOR_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.NS_TEST;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.assertFilesCount;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.assertImplementsIfc;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.cleanUp;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.getSourceFiles;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.testCompilation;
+
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.HashSet;
+import java.util.List;
+import org.junit.Test;
+import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.sal.java.api.generator.GeneratorJavaFile;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+/**
+ * Test correct code generation.
+ *
+ */
+public class NestedGroupingCompilationTest extends BaseCompilationTest {
+
+ @Test
+ public void testListGeneration() throws Exception {
+ final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "nested-grouping");
+ assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdir());
+ final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "nested-grouping");
+ assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
+
+ generateTestSources("/compilation/nested-grouping", sourcesOutputDir);
+
+ // Test if all sources are generated
+ File parent = new File(sourcesOutputDir, NS_TEST);
+ File foo = new File(parent, "Foo.java");
+ File fooBuilder = new File(parent, "FooBuilder.java");
+ File testData = new File(parent, "TestData.java");
+ File fooDir = new File(parent, "foo");
+ assertTrue(foo.exists());
+ assertTrue(fooBuilder.exists());
+ assertTrue(testData.exists());
+ assertTrue(fooDir.exists());
+ assertFilesCount(parent, 4);
+
+ parent = new File(parent, "foo");
+ File bar = new File(parent, "Bar.java");
+ assertTrue(bar.exists());
+ assertFilesCount(parent, 1);
+
+ // Test if sources are compilable
+ testCompilation(sourcesOutputDir, compiledOutputDir);
+
+ ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+ Class<?> fooClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.Foo", true, loader);
+ Class<?> barClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.foo.Bar", true, loader);
+
+ // Test generated 'foo'
+ assertTrue(fooClass.isInterface());
+ assertImplementsIfc(fooClass, barClass);
+
+ cleanUp(sourcesOutputDir, compiledOutputDir);
+ }
+
+ private void generateTestSources(String resourceDirPath, File sourcesOutputDir) throws Exception {
+ final List<File> sourceFiles = getSourceFiles(resourceDirPath);
+ final SchemaContext context = parser.parseFiles(sourceFiles);
+ final List<Type> types = bindingGenerator.generateTypes(context);
+ final GeneratorJavaFile generator = new GeneratorJavaFile(new HashSet<>(types));
+ generator.generateToFile(sourcesOutputDir);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+module test {
+ yang-version 1;
+ namespace "urn:opendaylight:test";
+ prefix "t";
+
+ revision "2013-10-08" {
+ }
+
+ container foo {
+ grouping bar {
+ leaf id {
+ type int32;
+ }
+ }
+ uses bar;
+ }
+
+}
* Name of Enclosing Type
* @return <code>new</code> Instance of Generated Type Builder.
*/
- GeneratedTOBuilder addEnclosingTransferObject(final String name);
+ GeneratedTOBuilder addEnclosingTransferObject(String name);
/**
* Adds new Enclosing Transfer Object <code>genTOBuilder</code> into
* @param genTOBuilder
* Name of Enclosing Type
*/
- T addEnclosingTransferObject(final GeneratedTOBuilder genTOBuilder);
+ T addEnclosingTransferObject(GeneratedTOBuilder genTOBuilder);
/**
* Adds String definition of comment into Method Signature definition. <br>
* @param comment
* Comment String.
*/
- T addComment(final String comment);
+ T addComment(String comment);
/**
* The method creates new AnnotationTypeBuilder containing specified package
* Name of Annotation Type
* @return <code>new</code> instance of Annotation Type Builder.
*/
- AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
+ AnnotationTypeBuilder addAnnotation(String packageName, String name);
boolean isAbstract();
* Type to implement
* @return <code>true</code> if the addition of type is successful.
*/
- T addImplementsType(final Type genType);
+ T addImplementsType(Type genType);
/**
* Adds Constant definition and returns <code>new</code> Constant instance. <br>
* Assigned Value
* @return <code>new</code> Constant instance.
*/
- Constant addConstant(final Type type, final String name, final Object value);
+ Constant addConstant(Type type, String name, Object value);
/**
* Adds new Enumeration definition for Generated Type Builder and returns
* Enumeration Name
* @return <code>new</code> instance of Enumeration Builder.
*/
- EnumBuilder addEnumeration(final String name);
+ EnumBuilder addEnumeration(String name);
List<MethodSignatureBuilder> getMethodDefinitions();
* Name of Method
* @return <code>new</code> instance of Method Signature Builder.
*/
- MethodSignatureBuilder addMethod(final String name);
+ MethodSignatureBuilder addMethod(String name);
/**
* Checks if GeneratedTypeBuilder contains method with name
* @param methodName
* is method name
*/
- boolean containsMethod(final String methodName);
+ boolean containsMethod(String methodName);
List<GeneratedPropertyBuilder> getProperties();
* Name of Property
* @return <code>new</code> instance of Generated Property Builder.
*/
- GeneratedPropertyBuilder addProperty(final String name);
+ GeneratedPropertyBuilder addProperty(String name);
/**
* Check whether GeneratedTOBuilder contains property with name
* of property which existance is checked
* @return true if property <code>name</code> exists in list of properties.
*/
- boolean containsProperty(final String name);
+ boolean containsProperty(String name);
/**
* Set a string that contains a human-readable textual description of type
package org.opendaylight.controller.md.sal.test.model.util;
import com.google.common.collect.ImmutableList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugmentBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeLeafOnlyUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeLeafOnlyUsesAugmentBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUses;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUsesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUsesKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.TopBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.top.level.list.NestedList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.top.level.list.NestedListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.TreeLeafOnlyUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ListViaUses;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ListViaUsesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.augment.rev140709.complex.from.grouping.ListViaUsesKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.TopBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.top.level.list.NestedList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.yangtools.test.binding.rev140701.two.level.list.top.level.list.NestedListKey;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-module opendaylight-mdsal-augment-test {
+module opendaylight-yangtools-augment-test {
- namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:augment";
+ namespace "urn:opendaylight:params:xml:ns:yang:yangtools:test:augment";
prefix aug-test;
- import opendaylight-mdsal-list-test {
+ import opendaylight-yangtools-binding-test {
prefix test;
}
import yang-ext {
}
}
-}
\ No newline at end of file
+}
-module opendaylight-mdsal-list-test {
+module opendaylight-yangtools-binding-test {
- namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:list";
+ namespace "urn:opendaylight:params:xml:ns:yang:yangtools:test:binding";
prefix list-test;
"A list of service functions that compose the service chain";
}
}
+ leaf-list top-level-leaf-list {
+ type string;
+ }
+ }
+
+ grouping choice {
+ choice identifier {
+ case simple {
+ container simple-id {
+ leaf id {
+ type int32;
+ }
+ }
+ }
+ case extended {
+ container extended-id {
+ leaf id {
+ type string;
+ }
+ }
+ }
+ }
}
container top {
uses two-level-list;
}
+ container choice-container {
+ uses choice;
+ }
+
rpc put-top {
input {
uses two-level-list;
}
}
-}
\ No newline at end of file
+}
testCompilation(sourcesOutputDir, compiledOutputDir);
// Create URLClassLoader
- File[] roots = File.listRoots();
- URL[] urls = new URL[roots.length + 1];
- for (int i = 0; i < roots.length; i++) {
- urls[i] = roots[i].toURI().toURL();
-
- }
- urls[roots.length] = compiledOutputDir.toURI().toURL();
+ URL[] urls = new URL[2];
+ urls[0] = compiledOutputDir.toURI().toURL();
+ urls[1] = new File(System.getProperty("user.dir")).toURI().toURL();
ClassLoader loader = new URLClassLoader(urls);
// Load class
private static List<File> getSourceFiles(String path) throws Exception {
final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
final File sourcesDir = new File(resPath);
+ final URI currentDir = new File(System.getProperty("user.dir")).toURI();
if (sourcesDir.exists()) {
final List<File> sourceFiles = new ArrayList<>();
final File[] fileArray = sourcesDir.listFiles();
if (fileArray == null) {
throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
}
- sourceFiles.addAll(Arrays.asList(fileArray));
+ for (File sourceFile : fileArray) {
+ sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
+ }
return sourceFiles;
} else {
throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
</dependency>
<!-- Local Dependencies -->
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-test-model</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>binding-model-api</artifactId>
terms of the Eclipse Public License v1.0 which accompanies this distribution,
and is available at http://www.eclipse.org/legal/epl-v10.html
-->
-<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>
- <parent>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yangtools-parent</artifactId>
- <version>0.6.2-SNAPSHOT</version>
- <relativePath>../parent/pom.xml</relativePath>
- </parent>
- <artifactId>features-yangtools</artifactId>
- <packaging>jar</packaging>
- <properties>
- <features.file>features.xml</features.file>
- </properties>
- <build>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <groupId>org.apache.karaf.tooling</groupId>
- <artifactId>karaf-maven-plugin</artifactId>
- <version>${karaf.version}</version>
- <extensions>true</extensions>
- <executions>
- <execution>
- <id>features-create-kar</id>
- <goals>
- <goal>features-create-kar</goal>
- </goals>
- <configuration>
- <featuresFile>${project.build.directory}/classes/${features.file}</featuresFile>
- </configuration>
- </execution>
- </executions>
- <!-- There is no useful configuration for the kar mojo. The features-generate-descriptor mojo configuration may be useful -->
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <executions>
- <execution>
- <id>filter</id>
- <phase>generate-resources</phase>
- <goals>
- <goal>resources</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-artifacts</id>
- <phase>package</phase>
- <goals>
- <goal>attach-artifact</goal>
- </goals>
- <configuration>
- <artifacts>
- <artifact>
- <file>${project.build.directory}/classes/${features.file}</file>
- <type>xml</type>
- <classifier>features</classifier>
- </artifact>
- </artifacts>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <dependenciesToScan>
- <dependency>org.opendaylight.yangtools:features-test</dependency>
- </dependenciesToScan>
- </configuration>
- </plugin>
- </plugins>
- </build>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools.model</groupId>
- <artifactId>ietf-inet-types</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools.model</groupId>
- <artifactId>ietf-yang-types</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools.model</groupId>
- <artifactId>yang-ext</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools.model</groupId>
- <artifactId>opendaylight-l2-types</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools.model</groupId>
- <artifactId>ietf-topology</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools.thirdparty</groupId>
- <artifactId>antlr4-runtime-osgi-nohead</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-composite-node</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-operations</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-parser-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-parser-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-binding</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>concepts</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>object-cache-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>object-cache-guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>object-cache-noop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-generator-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-generator-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-generator-spi</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-generator-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-model-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-type-provider</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-parser-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>restconf-client-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>restconf-client-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>restconf-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>binding-data-codec</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools.thirdparty</groupId>
- <artifactId>xtend-lib-osgi</artifactId>
- <scope>compile</scope>
- </dependency>
- <!-- test the features.xml -->
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>features-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
+<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>
+ <parent>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yangtools-parent</artifactId>
+ <version>0.6.2-SNAPSHOT</version>
+ <relativePath>../parent/pom.xml</relativePath>
+ </parent>
+ <artifactId>features-yangtools</artifactId>
+ <packaging>jar</packaging>
+ <properties>
+ <features.file>features.xml</features.file>
+ </properties>
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.karaf.tooling</groupId>
+ <artifactId>karaf-maven-plugin</artifactId>
+ <version>${karaf.version}</version>
+ <extensions>true</extensions>
+ <executions>
+ <execution>
+ <id>features-create-kar</id>
+ <goals>
+ <goal>features-create-kar</goal>
+ </goals>
+ <configuration>
+ <featuresFile>${project.build.directory}/classes/${features.file}</featuresFile>
+ </configuration>
+ </execution>
+ </executions>
+ <!-- There is no useful configuration for the kar mojo. The features-generate-descriptor mojo configuration may be useful -->
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-resources-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>filter</id>
+ <phase>generate-resources</phase>
+ <goals>
+ <goal>resources</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <phase>package</phase>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/${features.file}</file>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <dependenciesToScan>
+ <dependency>org.opendaylight.yangtools:features-test</dependency>
+ </dependenciesToScan>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-inet-types</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-yang-types</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-yang-types-20130715</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>yang-ext</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>opendaylight-l2-types</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-topology</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.thirdparty</groupId>
+ <artifactId>antlr4-runtime-osgi-nohead</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-composite-node</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-operations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-codec-gson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-parser-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-parser-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-binding</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-common</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>object-cache-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>object-cache-guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>object-cache-noop</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-generator-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-generator-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-generator-spi</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-generator-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-model-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-type-provider</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-parser-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>restconf-client-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>restconf-client-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>restconf-common</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-data-codec</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.thirdparty</groupId>
+ <artifactId>xtend-lib-osgi</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
+
+ <!-- test the features.xml -->
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>features-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
</project>
<feature version='${project.version}'>odl-yangtools-binding</feature>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-inet-types/${ietf.inet.types.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types/${ietf.yang.types.version}</bundle>
+ <bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types-20130715/${ietf.yang.types.20130715.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/yang-ext/${yang.ext.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/opendaylight-l2-types/${opendaylight.l2.types.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-topology/${ietf.topology.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.thirdparty/antlr4-runtime-osgi-nohead/${antlr4.version}</bundle>
<bundle>mvn:commons-io/commons-io/${commons.io.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-api/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.yangtools/yang-data-composite-node/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-impl/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-operations/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.yangtools/yang-data-composite-node/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-util/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-model-api/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-model-util/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.yangtools/yang-parser-impl/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-parser-api/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.yangtools/yang-parser-impl/${project.version}</bundle>
+
+ <!-- GSON-based JSON codec. Can be split out -->
+ <bundle>mvn:com.google.code.gson/gson/${gson.version}</bundle>
+ <bundle>mvn:org.opendaylight.yangtools/yang-data-codec-gson/${project.version}</bundle>
</feature>
<feature name='odl-yangtools-binding' version='${project.version}' description='OpenDaylight :: Yangtools :: Binding'>
*/
package org.opendaylight.yangtools.objcache;
+import com.google.common.base.Preconditions;
+
import javax.annotation.Nonnull;
+import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.yangtools.objcache.impl.StaticObjectCacheBinder;
import org.opendaylight.yangtools.objcache.spi.IObjectCacheFactory;
import org.opendaylight.yangtools.objcache.spi.NoopObjectCacheBinder;
-import com.google.common.base.Preconditions;
-
/**
* Point of entry for acquiring an {@link ObjectCache} instance.
*/
public final class ObjectCacheFactory {
- private static IObjectCacheFactory FACTORY;
+ private static volatile IObjectCacheFactory factory;
+ @GuardedBy("this")
private static synchronized IObjectCacheFactory initialize() {
// Double-check under lock
- if (FACTORY != null) {
- return FACTORY;
+ IObjectCacheFactory f = factory;
+ if (f != null) {
+ return f;
}
- IObjectCacheFactory f;
try {
f = StaticObjectCacheBinder.getInstance().getProductCacheFactory();
- FACTORY = f;
+ factory = f;
} catch (NoClassDefFoundError e) {
f = NoopObjectCacheBinder.INSTANCE.getProductCacheFactory();
}
}
public static synchronized void reset() {
- FACTORY = null;
+ factory = null;
}
/**
* @return Object cache instance.
*/
public static ObjectCache getObjectCache(@Nonnull final Class<?> objClass) {
- IObjectCacheFactory f = FACTORY;
+ IObjectCacheFactory f = factory;
if (f == null) {
f = initialize();
}
*/
package org.opendaylight.yangtools.objcache.spi;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.FinalizableReferenceQueue;
+import com.google.common.base.FinalizableSoftReference;
+import com.google.common.base.Preconditions;
+import com.google.common.cache.Cache;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
-
import org.opendaylight.yangtools.concepts.ProductAwareBuilder;
import org.opendaylight.yangtools.objcache.ObjectCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.FinalizableReferenceQueue;
-import com.google.common.base.FinalizableSoftReference;
-import com.google.common.base.Preconditions;
-import com.google.common.cache.Cache;
-
/**
* Abstract object cache implementation. This implementation takes care
* of interacting with the user and manages interaction with the Garbage
* to be on the lookout for WeakKeys, as we cannot pass them
* directly to productEquals().
*/
- if (obj != null && obj instanceof SoftKey) {
+ if (obj instanceof SoftKey) {
obj = ((SoftKey<?>)obj).get();
}
<ietf.topology.version>2013.10.21.2-SNAPSHOT</ietf.topology.version>
<ietf.inet.types.version>2010.09.24.4-SNAPSHOT</ietf.inet.types.version>
<ietf.yang.types.version>2010.09.24.4-SNAPSHOT</ietf.yang.types.version>
+ <ietf.yang.types.20130715.version>2013.07.15.1-SNAPSHOT</ietf.yang.types.20130715.version>
<ietf.restconf.version>2013.10.19.1-SNAPSHOT</ietf.restconf.version>
<karaf.version>3.0.1</karaf.version>
<nexusproxy>http://nexus.opendaylight.org/content</nexusproxy>
<artifactId>yang-data-impl</artifactId>
<version>0.6.2-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-codec-gson</artifactId>
+ <version>0.6.2-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-model-api</artifactId>
<artifactId>ietf-yang-types</artifactId>
<version>2010.09.24.4-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools.model</groupId>
+ <artifactId>ietf-yang-types-20130715</artifactId>
+ <version>2013.07.15.1-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools.model</groupId>
<artifactId>ietf-restconf</artifactId>
<version>${sonar-jacoco-listeners.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<extensions>true</extensions>
<configuration>
<instructions>
- <Export-Package>
- org.opendaylight.yangtools.util,
- org.opendaylight.yangtools.util.concurrent
- </Export-Package>
<Embed-Dependency>java-concurrent-hash-trie-map;inline=true</Embed-Dependency>
</instructions>
</configuration>
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util;
+
+import static java.util.concurrent.TimeUnit.MICROSECONDS;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.util.concurrent.AtomicDouble;
+
+/**
+ * Class that calculates and tracks time duration statistics.
+ *
+ * @author Thomas Pantelis
+ */
+public class DurationStatsTracker {
+
+ private final AtomicLong totalDurations = new AtomicLong();
+ private final AtomicLong longestDuration = new AtomicLong();
+ private volatile long timeOfLongestDuration;
+ private final AtomicLong shortestDuration = new AtomicLong(Long.MAX_VALUE);
+ private volatile long timeOfShortestDuration;
+ private final AtomicDouble averageDuration = new AtomicDouble();
+
+ /**
+ * Add a duration to track.
+ *
+ * @param duration the duration in nanoseconds.
+ */
+ public void addDuration(long duration) {
+
+ double currentAve = averageDuration.get();
+ long currentTotal = totalDurations.get();
+
+ long newTotal = currentTotal + 1;
+
+ // Calculate moving cumulative average.
+ double newAve = currentAve * currentTotal / newTotal + duration / newTotal;
+
+ averageDuration.compareAndSet(currentAve, newAve);
+ totalDurations.compareAndSet(currentTotal, newTotal);
+
+ long longest = longestDuration.get();
+ if( duration > longest ) {
+ if(longestDuration.compareAndSet( longest, duration )) {
+ timeOfLongestDuration = System.currentTimeMillis();
+ }
+ }
+
+ long shortest = shortestDuration.get();
+ if( duration < shortest ) {
+ if(shortestDuration.compareAndSet( shortest, duration )) {
+ timeOfShortestDuration = System.currentTimeMillis();
+ }
+ }
+ }
+
+ /**
+ * Returns the total number of tracked durations.
+ */
+ public long getTotalDurations() {
+ return totalDurations.get();
+ }
+
+ /**
+ * Returns the longest duration in nanoseconds.
+ */
+ public long getLongestDuration() {
+ return longestDuration.get();
+ }
+
+ /**
+ * Returns the shortest duration in nanoseconds.
+ */
+ public long getShortestDuration() {
+ long shortest = shortestDuration.get();
+ return shortest < Long.MAX_VALUE ? shortest : 0;
+ }
+
+ /**
+ * Returns the average duration in nanoseconds.
+ */
+ public double getAverageDuration() {
+ return averageDuration.get();
+ }
+
+ /**
+ * Returns the time stamp of the longest duration.
+ */
+ public long getTimeOfLongestDuration() {
+ return timeOfLongestDuration;
+ }
+
+ /**
+ * Returns the time stamp of the shortest duration.
+ */
+ public long getTimeOfShortestDuration() {
+ return timeOfShortestDuration;
+ }
+
+ /**
+ * Resets all statistics back to their defaults.
+ */
+ public void reset() {
+ totalDurations.set(0);
+ longestDuration.set(0);
+ timeOfLongestDuration = 0;
+ shortestDuration.set(Long.MAX_VALUE);
+ timeOfShortestDuration = 0;
+ averageDuration.set(0.0);
+ }
+
+ /**
+ * Returns the average duration as a displayable String with units, e.g. "12.34 ms".
+ */
+ public String getDisplayableAverageDuration() {
+ return formatDuration(getAverageDuration(), 0);
+ }
+
+ /**
+ * Returns the shortest duration as a displayable String with units and the date/time at
+ * which it occurred, e.g. "12.34 ms at 08/02/2014 12:30:24".
+ */
+ public String getDisplayableShortestDuration() {
+ return formatDuration(getShortestDuration(), getTimeOfShortestDuration());
+ }
+
+ /**
+ * Returns the longest duration as a displayable String with units and the date/time at
+ * which it occurred, e.g. "12.34 ms at 08/02/2014 12:30:24".
+ */
+ public String getDisplayableLongestDuration() {
+ return formatDuration(getLongestDuration(), getTimeOfLongestDuration());
+ }
+
+ private String formatDuration(double duration, long timeStamp) {
+ TimeUnit unit = chooseUnit((long)duration);
+ double value = duration / NANOSECONDS.convert(1, unit);
+ return timeStamp > 0 ?
+ String.format("%.4g %s at %3$tD %3$tT", value, abbreviate(unit), new Date(timeStamp)) :
+ String.format("%.4g %s", value, abbreviate(unit));
+ }
+
+ private static TimeUnit chooseUnit(long nanos) {
+ if(SECONDS.convert(nanos, NANOSECONDS) > 0) {
+ return SECONDS;
+ }
+
+ if(MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
+ return MILLISECONDS;
+ }
+
+ if(MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
+ return MICROSECONDS;
+ }
+
+ return NANOSECONDS;
+ }
+
+ private static String abbreviate(TimeUnit unit) {
+ switch(unit) {
+ case NANOSECONDS:
+ return "ns";
+ case MICROSECONDS:
+ return "\u03bcs"; // μs
+ case MILLISECONDS:
+ return "ms";
+ case SECONDS:
+ return "s";
+ default:
+ return "";
+ }
+ }
+}
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Preconditions;
private static final long IDLE_TIMEOUT_IN_SEC = 60L;
- private final AtomicLong largestBackingQueueSize = new AtomicLong( 0 );
-
private final ExecutorQueue executorQueue;
private final String threadPrefix;
executorQueue = (ExecutorQueue)super.getQueue();
rejectedTaskHandler = new RejectedTaskHandler(
- executorQueue.getBackingQueue(), largestBackingQueueSize );
+ executorQueue.getBackingQueue(), CountingRejectedExecutionHandler.newAbortPolicy() );
super.setRejectedExecutionHandler( rejectedTaskHandler );
}
@Override
public void setRejectedExecutionHandler( RejectedExecutionHandler handler ) {
+ Preconditions.checkNotNull( handler );
rejectedTaskHandler.setDelegateRejectedExecutionHandler( handler );
}
+ @Override
+ public RejectedExecutionHandler getRejectedExecutionHandler(){
+ return rejectedTaskHandler.getDelegateRejectedExecutionHandler();
+ }
+
@Override
public BlockingQueue<Runnable> getQueue(){
return executorQueue.getBackingQueue();
}
public long getLargestQueueSize() {
- return largestBackingQueueSize.get();
+ return ((TrackingLinkedBlockingQueue<?>)executorQueue.getBackingQueue()).getLargestQueueSize();
}
protected ToStringHelper addToStringAttributes( ToStringHelper toStringHelper ) {
private final LinkedBlockingQueue<Runnable> backingQueue;
ExecutorQueue( int maxBackingQueueSize ) {
- backingQueue = new LinkedBlockingQueue<>( maxBackingQueueSize );
+ backingQueue = new TrackingLinkedBlockingQueue<>( maxBackingQueueSize );
}
LinkedBlockingQueue<Runnable> getBackingQueue() {
private static class RejectedTaskHandler implements RejectedExecutionHandler {
private final LinkedBlockingQueue<Runnable> backingQueue;
- private final AtomicLong largestBackingQueueSize;
private volatile RejectedExecutionHandler delegateRejectedExecutionHandler;
RejectedTaskHandler( LinkedBlockingQueue<Runnable> backingQueue,
- AtomicLong largestBackingQueueSize ) {
+ RejectedExecutionHandler delegateRejectedExecutionHandler ) {
this.backingQueue = backingQueue;
- this.largestBackingQueueSize = largestBackingQueueSize;
+ this.delegateRejectedExecutionHandler = delegateRejectedExecutionHandler;
}
void setDelegateRejectedExecutionHandler(
- RejectedExecutionHandler delegateRejectedExecutionHandler ){
+ RejectedExecutionHandler delegateRejectedExecutionHandler ) {
this.delegateRejectedExecutionHandler = delegateRejectedExecutionHandler;
}
+ RejectedExecutionHandler getDelegateRejectedExecutionHandler(){
+ return delegateRejectedExecutionHandler;
+ }
+
@Override
public void rejectedExecution( Runnable task, ThreadPoolExecutor executor ) {
if( executor.isShutdown() ) {
}
if( !backingQueue.offer( task ) ) {
- if( delegateRejectedExecutionHandler != null ) {
- delegateRejectedExecutionHandler.rejectedExecution( task, executor );
- } else {
- throw new RejectedExecutionException(
- "All threads are in use and the queue is full" );
- }
- }
-
- largestBackingQueueSize.incrementAndGet();
- long size = backingQueue.size();
- long largest = largestBackingQueueSize.get();
- if( size > largest ) {
- largestBackingQueueSize.compareAndSet( largest, size );
+ delegateRejectedExecutionHandler.rejectedExecution( task, executor );
}
}
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util.concurrent;
+
+import java.util.concurrent.RejectedExecutionHandler;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.opendaylight.yangtools.util.ExecutorServiceUtil;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * A RejectedExecutionHandler that delegates to a backing RejectedExecutionHandler and counts the
+ * number of rejected tasks.
+ *
+ * @author Thomas Pantelis
+ */
+public class CountingRejectedExecutionHandler implements RejectedExecutionHandler {
+
+ private final RejectedExecutionHandler delegate;
+ private final AtomicLong rejectedTaskCounter = new AtomicLong();
+
+ /**
+ * Constructor.
+ *
+ * @param delegate the backing RejectedExecutionHandler.
+ */
+ public CountingRejectedExecutionHandler( RejectedExecutionHandler delegate ) {
+ this.delegate = Preconditions.checkNotNull( delegate );
+ }
+
+ @Override
+ public void rejectedExecution( Runnable task, ThreadPoolExecutor executor ) {
+ rejectedTaskCounter.incrementAndGet();
+ delegate.rejectedExecution( task, executor );
+ }
+
+ /**
+ * Returns the rejected task count.
+ */
+ public long getRejectedTaskCount(){
+ return rejectedTaskCounter.get();
+ }
+
+ /**
+ * Returns s counting handler for rejected tasks that runs the rejected task directly in the
+ * calling thread of the execute method, unless the executor has been shut down, in which case
+ * the task is discarded.
+ */
+ public static CountingRejectedExecutionHandler newCallerRunsPolicy() {
+ return new CountingRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() );
+ }
+
+ /**
+ * Returns a counting handler for rejected tasks that throws a RejectedExecutionException.
+ */
+ public static CountingRejectedExecutionHandler newAbortPolicy() {
+ return new CountingRejectedExecutionHandler( new ThreadPoolExecutor.AbortPolicy() );
+ }
+
+ /**
+ * Returns a counting handler for rejected tasks that that blocks on the
+ * {@link ThreadPoolExecutor}'s backing queue until it can add the task to the queue.
+ */
+ public static CountingRejectedExecutionHandler newCallerWaitsPolicy() {
+ return new CountingRejectedExecutionHandler( ExecutorServiceUtil.waitInQueueExecutionHandler() );
+ }
+}
package org.opendaylight.yangtools.util.concurrent;
-import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
// reached, subsequent tasks will be queued. If the queue is full, tasks will be rejected.
super( maximumPoolSize, maximumPoolSize, keepAliveTime, unit,
- new LinkedBlockingQueue<Runnable>( maximumQueueSize ) );
+ new TrackingLinkedBlockingQueue<Runnable>( maximumQueueSize ) );
this.threadPrefix = threadPrefix;
this.maximumQueueSize = maximumQueueSize;
// Need to specifically configure core threads to timeout.
allowCoreThreadTimeOut( true );
}
+
+ setRejectedExecutionHandler( CountingRejectedExecutionHandler.newAbortPolicy() );
+ }
+
+ public long getLargestQueueSize() {
+ return ((TrackingLinkedBlockingQueue<?>)getQueue()).getLargestQueueSize();
}
protected ToStringHelper addToStringAttributes( ToStringHelper toStringHelper ) {
.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() )
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util.concurrent;
+
+import java.beans.ConstructorProperties;
+
+/**
+ * Class used by the {@link QueuedNotificationManager} that contains a snapshot of notification
+ * queue statistics for a listener.
+ *
+ * @author Thomas Pantelis
+ * @see QueuedNotificationManager
+ */
+public class ListenerNotificationQueueStats {
+
+ private final String listenerClassName;
+ private final int currentQueueSize;
+
+ @ConstructorProperties({"listenerClassName","currentQueueSize"})
+ public ListenerNotificationQueueStats( String listenerClassName, int currentQueueSize ) {
+ this.listenerClassName = listenerClassName;
+ this.currentQueueSize = currentQueueSize;
+ }
+
+ /**
+ * Returns the name of the listener class.
+ */
+ public String getListenerClassName(){
+ return listenerClassName;
+ }
+
+ /**
+ * Returns the current notification queue size.
+ */
+ public int getCurrentQueueSize(){
+ return currentQueueSize;
+ }
+}
package org.opendaylight.yangtools.util.concurrent;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
}
}
+ /**
+ * Returns {@link ListenerNotificationQueueStats} instances for each current listener
+ * notification task in progress.
+ */
+ public List<ListenerNotificationQueueStats> getListenerNotificationQueueStats() {
+ List<ListenerNotificationQueueStats> statsList = new ArrayList<>( listenerCache.size() );
+ for( NotificationTask task: listenerCache.values() ) {
+ statsList.add( new ListenerNotificationQueueStats(
+ task.listenerKey.getListener().getClass().getName(),
+ task.notificationQueue.size() ) );
+ }
+
+ return statsList ;
+ }
+
+ /**
+ * Returns the maximum listener queue capacity.
+ */
+ public int getMaxQueueCapacity(){
+ return maxQueueCapacity;
+ }
+
+ /**
+ * Returns the {@link Executor} to used for notification tasks.
+ */
+ public Executor getExecutor(){
+ return executor;
+ }
+
/**
* Used as the listenerCache map key. We key by listener reference identity hashCode/equals.
* Since we don't know anything about the listener class implementations and we're mixing
package org.opendaylight.yangtools.util.concurrent;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
FastThreadPoolExecutor executor =
new FastThreadPoolExecutor( maximumPoolSize, maximumQueueSize, threadPrefix );
- executor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() );
+ executor.setRejectedExecutionHandler( CountingRejectedExecutionHandler.newCallerRunsPolicy() );
return executor;
}
CachedThreadPoolExecutor executor =
new CachedThreadPoolExecutor( maximumPoolSize, maximumQueueSize, threadPrefix );
- executor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() );
+ executor.setRejectedExecutionHandler( CountingRejectedExecutionHandler.newCallerRunsPolicy() );
return executor;
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util.concurrent;
+
+import java.util.Collection;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicLongFieldUpdater;
+
+/**
+ * A {@link LinkedBlockingQueue} that tracks the largest queue size for debugging.
+ *
+ * @author Thomas Pantelis
+ *
+ * @param <E> the element t.ype
+ */
+public class TrackingLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Holds largestQueueSize, this long field should be only accessed
+ * using {@value #LARGEST_QUEUE_SIZE_UPDATER}
+ */
+ private volatile long largestQueueSize = 0;
+
+ @SuppressWarnings("rawtypes")
+ private static AtomicLongFieldUpdater<TrackingLinkedBlockingQueue> LARGEST_QUEUE_SIZE_UPDATER = AtomicLongFieldUpdater.newUpdater(TrackingLinkedBlockingQueue.class, "largestQueueSize");
+
+ /**
+ * @see LinkedBlockingQueue#LinkedBlockingQueue
+ */
+ public TrackingLinkedBlockingQueue() {
+ super();
+ }
+
+ /**
+ * @see LinkedBlockingQueue#LinkedBlockingQueue(Collection)
+ */
+ public TrackingLinkedBlockingQueue( Collection<? extends E> c ) {
+ super(c);
+ }
+
+ /**
+ * @see LinkedBlockingQueue#LinkedBlockingQueue(int)
+ */
+ public TrackingLinkedBlockingQueue( int capacity ) {
+ super(capacity);
+ }
+
+ /**
+ * Returns the largest queue size.
+ */
+ public long getLargestQueueSize(){
+ return largestQueueSize;
+ }
+
+ @Override
+ public boolean offer( E e, long timeout, TimeUnit unit ) throws InterruptedException {
+ if( super.offer( e, timeout, unit ) ) {
+ updateLargestQueueSize();
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean offer( E e ) {
+ if( super.offer( e ) ) {
+ updateLargestQueueSize();
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public void put( E e ) throws InterruptedException {
+ super.put( e );
+ updateLargestQueueSize();
+ }
+
+ @Override
+ public boolean add( E e ) {
+ boolean result = super.add( e );
+ updateLargestQueueSize();
+ return result;
+ }
+
+ @Override
+ public boolean addAll( Collection<? extends E> c ) {
+ try {
+ return super.addAll( c );
+ } finally {
+ updateLargestQueueSize();
+ }
+ }
+
+ private void updateLargestQueueSize() {
+ long size = size();
+ long largest = largestQueueSize;
+ if( size > largest ) {
+ LARGEST_QUEUE_SIZE_UPDATER.compareAndSet(this, largest, size );
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ * Unit tests for DurationStatsTracker.
+ *
+ * @author Thomas Pantelis
+ */
+public class DurationStatsTrackerTest {
+
+ @Test
+ public void test() {
+
+ DurationStatsTracker tracker = new DurationStatsTracker();
+
+ tracker.addDuration(10000);
+ assertEquals("getTotalDurations", 1, tracker.getTotalDurations());
+ assertEquals("getAverageDuration", 10000.0, tracker.getAverageDuration(), 0.1);
+ assertEquals("getLongestDuration", 10000, tracker.getLongestDuration());
+ assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+
+ tracker.addDuration(30000);
+ assertEquals("getTotalDurations", 2, tracker.getTotalDurations());
+ assertEquals("getAverageDuration", 20000.0, tracker.getAverageDuration(), 0.1);
+ assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
+ assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+
+ verifyDisplayableString("getDisplayableAverageDuration",
+ tracker.getDisplayableAverageDuration(), "20.0");
+ verifyDisplayableString("getDisplayableLongestDuration",
+ tracker.getDisplayableLongestDuration(), "30.0");
+ verifyDisplayableString("getDisplayableShortestDuration",
+ tracker.getDisplayableShortestDuration(), "10.0");
+
+ tracker.addDuration(10000);
+ assertEquals("getTotalDurations", 3, tracker.getTotalDurations());
+ assertEquals("getAverageDuration", 16666.0, tracker.getAverageDuration(), 1.0);
+ assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
+ assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+
+ tracker.addDuration(5000);
+ assertEquals("getTotalDurations", 4, tracker.getTotalDurations());
+ assertEquals("getAverageDuration", 13750.0, tracker.getAverageDuration(), 1.0);
+ assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
+ assertEquals("getShortestDuration", 5000, tracker.getShortestDuration());
+
+ tracker.reset();
+ assertEquals("getTotalDurations", 0, tracker.getTotalDurations());
+ assertEquals("getAverageDuration", 0.0, tracker.getAverageDuration(), 0.1);
+ assertEquals("getLongestDuration", 0, tracker.getLongestDuration());
+ assertEquals("getShortestDuration", 0, tracker.getShortestDuration());
+
+ tracker.addDuration(10000);
+ assertEquals("getTotalDurations", 1, tracker.getTotalDurations());
+ assertEquals("getAverageDuration", 10000.0, tracker.getAverageDuration(), 0.1);
+ assertEquals("getLongestDuration", 10000, tracker.getLongestDuration());
+ assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+ }
+
+ private void verifyDisplayableString(String name, String actual, String expPrefix) {
+ assertEquals(name + " starts with " + expPrefix + ". Actual: " + actual,
+ true, actual.startsWith(expPrefix));
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util.concurrent;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.After;
+import org.junit.Test;
+import org.opendaylight.yangtools.util.ExecutorServiceUtil;
+import org.opendaylight.yangtools.util.concurrent.ThreadPoolExecutorTest.Task;
+
+/**
+ * Unit tests for CountingRejectedExecutionHandler.
+ *
+ * @author Thomas Pantelis
+ */
+public class CountingRejectedExecutionHandlerTest {
+
+ private ThreadPoolExecutor executor;
+
+ @After
+ public void tearDown() {
+ if( executor != null ) {
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testCallerRunsPolicyHandler() throws InterruptedException {
+
+ int nTasks = 5;
+ CountDownLatch tasksRunLatch = new CountDownLatch( 1 );
+ CountDownLatch blockLatch = new CountDownLatch( 1 );
+
+ executor = new ThreadPoolExecutor( 1, 1, 0, TimeUnit.SECONDS,
+ ExecutorServiceUtil.offerFailingBlockingQueue( new LinkedBlockingQueue<Runnable>() ) );
+
+ CountingRejectedExecutionHandler countingHandler =
+ CountingRejectedExecutionHandler.newCallerRunsPolicy();
+ executor.setRejectedExecutionHandler( countingHandler );
+
+ executor.execute( new Task( tasksRunLatch, blockLatch ) );
+
+ for( int i = 0; i < nTasks - 1; i++ ) {
+ executor.execute( new Task( null, null, null, null, 0 ) );
+ }
+
+ assertEquals( "getRejectedTaskCount", nTasks - 1, countingHandler.getRejectedTaskCount() );
+
+ blockLatch.countDown();
+
+ assertEquals( "Tasks complete", true, tasksRunLatch.await( 5, TimeUnit.SECONDS ) );
+ }
+
+ @Test
+ public void testAbortPolicyHandler() throws InterruptedException {
+
+ int nTasks = 5;
+ CountDownLatch tasksRunLatch = new CountDownLatch( 1 );
+ CountDownLatch blockLatch = new CountDownLatch( 1 );
+
+ executor = new ThreadPoolExecutor( 1, 1, 0, TimeUnit.SECONDS,
+ ExecutorServiceUtil.offerFailingBlockingQueue( new LinkedBlockingQueue<Runnable>() ) );
+
+ CountingRejectedExecutionHandler countingHandler =
+ CountingRejectedExecutionHandler.newAbortPolicy();
+ executor.setRejectedExecutionHandler( countingHandler );
+
+ executor.execute( new Task( tasksRunLatch, blockLatch ) );
+
+ for( int i = 0; i < nTasks - 1; i++ ) {
+ try {
+ executor.execute( new Task( null, null, null, null, 0 ) );
+ fail( "Expected RejectedExecutionException" );
+ } catch( RejectedExecutionException e ) {
+ // Expected
+ }
+ }
+
+ assertEquals( "getRejectedTaskCount", nTasks - 1, countingHandler.getRejectedTaskCount() );
+
+ blockLatch.countDown();
+
+ assertEquals( "Tasks complete", true, tasksRunLatch.await( 5, TimeUnit.SECONDS ) );
+ }
+}
System.out.println();
}
- private static class Task implements Runnable {
+ static class Task implements Runnable {
final CountDownLatch tasksRunLatch;
+ final CountDownLatch blockLatch;
final ConcurrentMap<Thread, AtomicLong> taskCountPerThread;
final AtomicReference<AssertionError> threadError;
final String expThreadPrefix;
this.threadError = threadError;
this.expThreadPrefix = expThreadPrefix;
this.delay = delay;
+ blockLatch = null;
+ }
+
+ Task( CountDownLatch tasksRunLatch, CountDownLatch blockLatch ) {
+ this.tasksRunLatch = tasksRunLatch;
+ this.blockLatch = blockLatch;
+ this.taskCountPerThread = null;
+ this.threadError = null;
+ this.expThreadPrefix = null;
+ this.delay = 0;
}
@Override
public void run() {
try {
- if( delay > 0 ) {
- try {
+ try {
+ if( delay > 0 ) {
TimeUnit.MICROSECONDS.sleep( delay );
- } catch( InterruptedException e ) {}
- }
+ } else if( blockLatch != null ) {
+ blockLatch.await();
+ }
+ } catch( InterruptedException e ) {}
if( expThreadPrefix != null ) {
assertEquals( "Thread name starts with " + expThreadPrefix, true,
--- /dev/null
+/*
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.util.concurrent;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Test;
+
+/**
+ * Unit tests for TrackingLinkedBlockingQueue.
+ *
+ * @author Thomas Pantelis
+ */
+public class TrackingLinkedBlockingQueueTest {
+
+ @Test
+ public void testOffer() throws InterruptedException {
+
+ TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>( 2 );
+
+ assertEquals( "offer", true, queue.offer( "1" ) );
+ assertEquals( "getLargestQueueSize", 1, queue.getLargestQueueSize() );
+ assertEquals( "size", 1, queue.size() );
+
+ assertEquals( "offer", true, queue.offer( "2", 1, TimeUnit.MILLISECONDS ) );
+ 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() );
+ }
+
+ @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( "2" );
+ assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
+ assertEquals( "size", 2, queue.size() );
+ }
+
+ @Test
+ public void testAdd() {
+
+ TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>( 2 );
+
+ 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() );
+
+ try {
+ queue.add( "3" );
+ fail( "Expected IllegalStateException" );
+ } catch( IllegalStateException e ) {
+ // Expected
+ assertEquals( "getLargestQueueSize", 2, queue.getLargestQueueSize() );
+ assertEquals( "size", 2, queue.size() );
+ }
+ }
+
+ @Test
+ public void testAddAll() {
+
+ TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>( 3 );
+
+ 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 ) {
+ // Expected
+ assertEquals( "getLargestQueueSize", 3, queue.getLargestQueueSize() );
+ assertEquals( "size", 3, queue.size() );
+ }
+ }
+}
}
try {
this.listenerCallbackMethod.invoke(message);
- } catch (IllegalAccessException e) {
- throw new IllegalStateException(e.getMessage());
- } catch (InvocationTargetException e) {
- throw new IllegalStateException(e.getMessage());
+ } catch (IllegalAccessException | InvocationTargetException e) {
+ throw new IllegalStateException("Failed to invoke callback", e);
}
}
@Path("restconf")
public interface RestRestconfService {
+ public static final String IDENTIFIER = "identifier";
+ public static final String INPUT = "input";
public static final String XML = "+xml";
public static final String JSON = "+json";
@Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String invokeRpc(@PathParam("identifier") String identifier, @QueryParam("input") CompositeNode payload);
+ public String invokeRpc(@PathParam(IDENTIFIER) String identifier, @QueryParam(INPUT) CompositeNode payload);
@POST
@Path("/operations/{identifier}")
@Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String invokeRpc(@PathParam("identifier") String identifier);
+ public String invokeRpc(@PathParam(IDENTIFIER) String identifier);
@GET
@Path("/config/{identifier:.+}")
@Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String readConfigurationData(@PathParam("identifier") String identifier);
+ public String readConfigurationData(@PathParam(IDENTIFIER) String identifier);
@GET
@Path("/operational/{identifier:.+}")
@Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public String readOperationalData(@PathParam("identifier") String identifier);
+ public String readOperationalData(@PathParam(IDENTIFIER) String identifier);
@PUT
@Path("/config/{identifier:.+}")
@Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response updateConfigurationData(@PathParam("identifier") String identifier,@QueryParam("input") CompositeNode payload);
+ public Response updateConfigurationData(@PathParam(IDENTIFIER) String identifier,@QueryParam(INPUT) CompositeNode payload);
@POST
@Path("/config/{identifier:.+}")
@Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response createConfigurationData(@PathParam("identifier") String identifier, @QueryParam("input") CompositeNode payload);
+ public Response createConfigurationData(@PathParam(IDENTIFIER) String identifier, @QueryParam(INPUT) CompositeNode payload);
@POST
@Path("/config")
@Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
- public Response createConfigurationData( @QueryParam("input") CompositeNode payload);
+ public Response createConfigurationData( @QueryParam(INPUT) CompositeNode payload);
@DELETE
@Path("/config/{identifier:.+}")
- public Response deleteConfigurationData(@PathParam("identifier") String identifier);
+ public Response deleteConfigurationData(@PathParam(IDENTIFIER) String identifier);
}
restModule.setName(eElement.getElementsByTagName("name").item(0).getTextContent());
restModule.setNamespace(eElement.getElementsByTagName("namespace").item(0).getTextContent());
restModule.setRevision(eElement.getElementsByTagName("revision").item(0).getTextContent());
- } catch (NullPointerException npe){
- throw new IllegalStateException("Incomplete module data in xml.");
+ } catch (NullPointerException e) {
+ throw new IllegalStateException("Incomplete module data in xml.", e);
}
return restModule;
}
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
+
import java.text.SimpleDateFormat;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
throw new UnsupportedOperationException("Utility class should not be instantiated");
}
- public static final String getRootPackageName(final QName module) {
+ public static String getRootPackageName(final QName module) {
return getRootPackageName(module.getModule());
}
- public static final String getRootPackageName(final QNameModule module) {
+ public static String getRootPackageName(final QNameModule module) {
checkArgument(module != null, "Module must not be null");
checkArgument(module.getRevision() != null, "Revision must not be null");
checkArgument(module.getNamespace() != null, "Namespace must not be null");
return builder.toString();
}
- public static final String getMethodName(final QName name) {
+ public static String getMethodName(final QName name) {
checkArgument(name != null, "Name should not be null.");
return getMethodName(name.getLocalName());
}
- public static final String getClassName(final String localName) {
+ public static String getClassName(final String localName) {
checkArgument(localName != null, "Name should not be null.");
return toFirstUpper(toCamelCase(localName));
}
- public static final String getMethodName(final String yangIdentifier) {
+ public static String getMethodName(final String yangIdentifier) {
checkArgument(yangIdentifier != null,"Identifier should not be null");
return toFirstLower(toCamelCase(yangIdentifier));
}
- public static final String getClassName(final QName name) {
+ public static String getClassName(final QName name) {
checkArgument(name != null, "Name should not be null.");
return toFirstUpper(toCamelCase(name.getLocalName()));
}
return potential;
}
- private static final String toCamelCase(final String rawString) {
+ private static String toCamelCase(final String rawString) {
checkArgument(rawString != null, "String should not be null");
Iterable<String> components = CAMEL_SPLITTER.split(rawString);
StringBuilder builder = new StringBuilder();
return checkNumericPrefix(builder.toString());
}
- private static final String checkNumericPrefix(final String rawString) {
+ private static String checkNumericPrefix(final String rawString) {
if (rawString == null || rawString.isEmpty()) {
return rawString;
}
@Deprecated
public interface NodeModificationBuilder {
- abstract Node<?> getMutableEquivalent(Node<?> originalNode);
+ Node<?> getMutableEquivalent(Node<?> originalNode);
- abstract CompositeNode buildDiffTree();
+ CompositeNode buildDiffTree();
- abstract void mergeNode(MutableCompositeNode alteredNode);
+ void mergeNode(MutableCompositeNode alteredNode);
- abstract void removeNode(MutableCompositeNode deadNode);
+ void removeNode(MutableCompositeNode deadNode);
- abstract void removeNode(MutableSimpleNode<?> deadNode);
+ void removeNode(MutableSimpleNode<?> deadNode);
- abstract void deleteNode(MutableSimpleNode<?> deadNode);
+ void deleteNode(MutableSimpleNode<?> deadNode);
- abstract void deleteNode(MutableCompositeNode deadNode);
+ void deleteNode(MutableCompositeNode deadNode);
- abstract void replaceNode(MutableCompositeNode replacementNode);
+ void replaceNode(MutableCompositeNode replacementNode);
- abstract void replaceNode(MutableSimpleNode<?> replacementNode);
+ void replaceNode(MutableSimpleNode<?> replacementNode);
- abstract void addNode(MutableCompositeNode newNode);
+ void addNode(MutableCompositeNode newNode);
- abstract void addNode(MutableSimpleNode<?> newNode);
+ void addNode(MutableSimpleNode<?> newNode);
}
import org.opendaylight.yangtools.concepts.Path;
import org.opendaylight.yangtools.util.HashCodeBuilder;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
/**
/**
* Path argument / component of InstanceIdentifier
*
- * Path argument uniquelly identifies node in data tree on particular
+ * Path argument uniquely identifies node in data tree on particular
* level.
* <p>
* This interface itself is used as common parent for actual
* @return Node type
*/
QName getNodeType();
+
+ /**
+ * Return the string representation of this object for use in context
+ * provided by a previous object. This method can be implemented in
+ * terms of {@link #toString()}, but implementations are encourage to
+ * reuse any context already emitted by the previous object.
+ *
+ * @param previous Previous path argument
+ * @return String representation
+ */
+ String toRelativeString(PathArgument previous);
}
private static abstract class AbstractPathArgument implements PathArgument {
public String toString() {
return getNodeType().toString();
}
+
+ @Override
+ public String toRelativeString(final PathArgument previous) {
+ if (previous instanceof AbstractPathArgument) {
+ final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
+ if (getNodeType().getModule().equals(mod)) {
+ return getNodeType().getLocalName();
+ }
+ }
+
+ return getNodeType().toString();
+ }
}
/**
public String toString() {
return super.toString() + '[' + keyValues + ']';
}
+
+ @Override
+ public String toRelativeString(final PathArgument previous) {
+ return super.toRelativeString(previous) + '[' + keyValues + ']';
+ }
}
/**
public String toString() {
return super.toString() + '[' + value + ']';
}
+
+ @Override
+ public String toRelativeString(final PathArgument previous) {
+ return super.toRelativeString(previous) + '[' + value + ']';
+ }
}
/**
}
/**
- *
* Returns set of all possible child nodes
*
* @return set of all possible child nodes.
return sb.toString();
}
+ @Override
+ public String toRelativeString(final PathArgument previous) {
+ return toString();
+ }
+
@Override
public boolean equals(final Object o) {
if (this == o) {
synchronized (this) {
ret = toStringCache;
if (ret == null) {
- final StringBuilder builder = new StringBuilder('/');
- boolean first = true;
+ final StringBuilder builder = new StringBuilder("/");
+ PathArgument prev = null;
for (PathArgument argument : getPathArguments()) {
- if (first) {
- first = false;
- } else {
+ if (prev != null) {
builder.append('/');
}
- builder.append(argument.toString());
+ builder.append(argument.toRelativeString(prev));
+ prev = argument;
}
ret = builder.toString();
package org.opendaylight.yangtools.yang.data.api.schema.stream;
import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
-import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.Deque;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+/**
+ * A {@link NormalizedNodeStreamWriter} which logs the events into a {@link Logger}.
+ */
@Beta
-public class LoggingNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
+public final class LoggingNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
private static final Logger LOG = LoggerFactory.getLogger(LoggingNormalizedNodeStreamWriter.class);
private static final int DEFAULT_INDENT_SIZE = 2;
- private final int indentSize = DEFAULT_INDENT_SIZE;
- private int currentIndent = 0;
+
+ private final Deque<String> indent = new ArrayDeque<>();
+ private final String indentStr;
+
+ public LoggingNormalizedNodeStreamWriter() {
+ this(DEFAULT_INDENT_SIZE);
+ }
+
+ public LoggingNormalizedNodeStreamWriter(final int indentSize) {
+ this.indentStr = Strings.repeat(" ", indentSize);
+ indent.push("");
+ }
private String ind() {
- return Strings.repeat(" ", currentIndent);
+ return indent.peek();
}
private void decIndent() {
- Preconditions.checkState(currentIndent >= 0, "Unexpected indentation %s", currentIndent);
- currentIndent -= indentSize;
+ indent.pop();
}
private void incIndent() {
- currentIndent += indentSize;
+ indent.push(ind() + indentStr);
}
@Override
- public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IllegalStateException {
+ public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) {
LOG.debug("{}{}[](no key)", ind(), name);
incIndent();
}
@Override
- public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
LOG.debug("{}{}(no key)", ind(), name);
incIndent();
}
@Override
- public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
}
@Override
- public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ public void startMapNode(final NodeIdentifier name, final int childSizeHint) {
LOG.debug("{}{}(key)", ind(), name);
incIndent();
}
@Override
- public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
- throws IllegalArgumentException {
+ public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) {
LOG.debug("{}{}[](key)", ind(), identifier);
incIndent();
}
@Override
- public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
LOG.debug("{}{}(leaf-list)", ind(), name);
incIndent();
}
@Override
- public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ public void startContainerNode(final NodeIdentifier name, final int childSizeHint) {
LOG.debug("{}{}(container)", ind(), name);
incIndent();
}
@Override
- public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
LOG.debug("{}{}(choice)", ind(), name);
incIndent();
}
@Override
- public void startAugmentationNode(final AugmentationIdentifier identifier) throws IllegalArgumentException {
+ public void startAugmentationNode(final AugmentationIdentifier identifier) {
LOG.debug("{}{}(augmentation)", ind(), identifier);
incIndent();
}
@Override
- public void leafSetEntryNode(final Object value) throws IllegalArgumentException {
+ public void leafSetEntryNode(final Object value) {
LOG.debug("{}{}({}) ", ind(), value, value.getClass().getSimpleName());
}
@Override
- public void leafNode(final NodeIdentifier name, final Object value) throws IllegalArgumentException {
+ public void leafNode(final NodeIdentifier name, final Object value) {
LOG.debug("{}{}(leaf({}))=", ind(), name, value.getClass().getSimpleName(), value);
}
}
@Override
- public void anyxmlNode(final NodeIdentifier name, final Object value) throws IllegalArgumentException {
+ public void anyxmlNode(final NodeIdentifier name, final Object value) {
LOG.debug("{}{}(anyxml)=", ind(), name, value);
}
@Override
- public void flush() throws IOException {
+ public void flush() {
LOG.trace("<<FLUSH>>");
}
@Override
- public void close() throws IOException {
+ public void close() {
LOG.debug("<<END-OF-STREAM>>");
}
}
\ No newline at end of file
import java.io.Flushable;
import java.io.IOException;
+import javax.xml.stream.XMLStreamReader;
+
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
/**
- * This is an experimental
+ * This is an experimental iterator over a {@link NormalizedNode}. This is essentially
+ * the opposite of a {@link XMLStreamReader} -- unlike instantiating an iterator over
+ * the backing data, this encapsulates a {@link NormalizedNodeStreamWriter} and allows
+ * us to write multiple nodes.
*/
@Beta
public final class NormalizedNodeWriter implements Closeable, Flushable {
this.writer = Preconditions.checkNotNull(writer);
}
+ /**
+ * Create a new writer backed by a {@link NormalizedNodeStreamWriter}.
+ *
+ * @param writer Backend writer
+ * @return A new instance.
+ */
public static NormalizedNodeWriter forStreamWriter(final NormalizedNodeStreamWriter writer) {
return new NormalizedNodeWriter(writer);
}
+ /**
+ * Iterate over the provided {@link NormalizedNode} and emit write
+ * events to the encapsulated {@link NormalizedNodeStreamWriter}.
+ *
+ * @param node Node
+ * @return
+ * @throws IOException when thrown from the backing writer.
+ */
public NormalizedNodeWriter write(final NormalizedNode<?, ?> node) throws IOException {
if (wasProcessedAsCompositeNode(node)) {
return this;
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+
import java.io.IOException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+/**
+ * Utility abstract class for tracking parser state, as needed by StAX-like parser.
+ */
+@Beta
abstract class AbstractNodeDataWithSchema {
-
private final DataSchemaNode schema;
- public AbstractNodeDataWithSchema(final DataSchemaNode schema) {
- this.schema = schema;
+ protected AbstractNodeDataWithSchema(final DataSchemaNode schema) {
+ this.schema = Preconditions.checkNotNull(schema);
}
+ /**
+ * Return the associated schema node.
+ * @return
+ */
public final DataSchemaNode getSchema() {
return schema;
}
- protected abstract void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException;
+ /**
+ * Emit this node's events into the specified writer.
+ *
+ * @param writer Target writer
+ * @throws IOException reported when thrown by the writer.
+ */
+ public abstract void write(final NormalizedNodeStreamWriter writer) throws IOException;
- protected NodeIdentifier provideNodeIdentifier() {
+ protected final NodeIdentifier provideNodeIdentifier() {
return new NodeIdentifier(schema.getQName());
}
if (getClass() != obj.getClass()) {
return false;
}
- AbstractNodeDataWithSchema other = (AbstractNodeDataWithSchema) obj;
- if (schema == null) {
- if (other.schema != null) {
- return false;
- }
- } else if (!schema.equals(other.schema)) {
- return false;
- }
-
- return true;
+ final AbstractNodeDataWithSchema other = (AbstractNodeDataWithSchema) obj;
+ return schema.equals(other.schema);
}
}
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
-// FIXME: should be changed according to format of value
- nnStreamWriter.anyxmlNode(provideNodeIdentifier(), getValue());
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ // FIXME: should be changed according to format of value
+ writer.anyxmlNode(provideNodeIdentifier(), getValue());
}
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-
-import java.io.IOException;
-
-import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
class CaseNodeDataWithSchema extends CompositeNodeDataWithSchema {
super(schema);
}
- @Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- super.writeToStream(nnStreamWriter);
- }
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
-
import java.io.IOException;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
}
@Override
- public CompositeNodeDataWithSchema addCompositeChild(final DataSchemaNode schema) {
+ protected CompositeNodeDataWithSchema addCompositeChild(final DataSchemaNode schema) {
CaseNodeDataWithSchema newChild = new CaseNodeDataWithSchema((ChoiceCaseNode) schema);
caseNodeDataWithSchema = newChild;
addCompositeChild(newChild);
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- nnStreamWriter.startChoiceNode(provideNodeIdentifier(), UNKNOWN_SIZE);
- super.writeToStream(nnStreamWriter);
- nnStreamWriter.endNode();
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ writer.startChoiceNode(provideNodeIdentifier(), childSizeHint());
+ super.write(writer);
+ writer.endNode();
}
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Multimap;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
+
+import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+/**
+ * A node which is composed of multiple simpler nodes.
+ */
class CompositeNodeDataWithSchema extends AbstractNodeDataWithSchema {
+ private static final Function<DataSchemaNode, QName> QNAME_FUNCTION = new Function<DataSchemaNode, QName>() {
+ @Override
+ public QName apply(@Nonnull final DataSchemaNode input) {
+ return input.getQName();
+ }
+ };
/**
* nodes which were added to schema via augmentation and are present in data input
*/
- protected Map<AugmentationSchema, List<AbstractNodeDataWithSchema>> augmentationsToChild = new HashMap<>();
+ private final Multimap<AugmentationSchema, AbstractNodeDataWithSchema> augmentationsToChild = ArrayListMultimap.create();
/**
- * remaining data nodes (which aren't added via augment). Every of them should have the same QName
+ * remaining data nodes (which aren't added via augment). Every of one them should have the same QName.
*/
- protected List<AbstractNodeDataWithSchema> childs = new ArrayList<>();
+ private final List<AbstractNodeDataWithSchema> children = new ArrayList<>();
public CompositeNodeDataWithSchema(final DataSchemaNode schema) {
super(schema);
}
- public AbstractNodeDataWithSchema addSimpleChild(final DataSchemaNode schema) {
- SimpleNodeDataWithSchema newChild = null;
- if (schema instanceof LeafSchemaNode) {
- newChild = new LeafNodeDataWithSchema(schema);
- } else if (schema instanceof AnyXmlSchemaNode) {
- newChild = new AnyXmlNodeDataWithSchema(schema);
+ public AbstractNodeDataWithSchema addChild(final Deque<DataSchemaNode> schemas) {
+ Preconditions.checkArgument(!schemas.isEmpty(), "Expecting at least one schema");
+
+ // Pop the first node...
+ final DataSchemaNode schema = schemas.pop();
+ if (schemas.isEmpty()) {
+ // Simple, direct node
+ return addChild(schema);
}
- if (newChild != null) {
+ // The choice/case mess, reuse what we already popped
+ final DataSchemaNode choiceCandidate = schema;
+ Preconditions.checkArgument(choiceCandidate instanceof ChoiceNode,
+ "Expected node of type ChoiceNode but was %s", choiceCandidate.getClass().getSimpleName());
+ final ChoiceNode choiceNode = (ChoiceNode) choiceCandidate;
- AugmentationSchema augSchema = null;
- if (schema.isAugmenting()) {
- augSchema = findCorrespondingAugment(getSchema(), schema);
- }
- if (augSchema != null) {
- addChildToAugmentation(augSchema, newChild);
- } else {
- addChild(newChild);
- }
- return newChild;
- }
- return null;
- }
+ final DataSchemaNode caseCandidate = schemas.pop();
+ Preconditions.checkArgument(caseCandidate instanceof ChoiceCaseNode,
+ "Expected node of type ChoiceCaseNode but was %s", caseCandidate.getClass().getSimpleName());
+ final ChoiceCaseNode caseNode = (ChoiceCaseNode) caseCandidate;
- private void addChildToAugmentation(final AugmentationSchema augSchema, final AbstractNodeDataWithSchema newChild) {
- List<AbstractNodeDataWithSchema> childsInAugment = augmentationsToChild.get(augSchema);
- if (childsInAugment == null) {
- childsInAugment = new ArrayList<>();
- augmentationsToChild.put(augSchema, childsInAugment);
+ AugmentationSchema augSchema = null;
+ if (choiceCandidate.isAugmenting()) {
+ augSchema = findCorrespondingAugment(getSchema(), choiceCandidate);
}
- childsInAugment.add(newChild);
- }
- public AbstractNodeDataWithSchema addChild(final Deque<DataSchemaNode> schemas) {
- if (schemas.size() == 1) {
- final DataSchemaNode childDataSchemaNode = schemas.pop();
- return addChild(childDataSchemaNode);
+ // looking for existing choice
+ final Collection<AbstractNodeDataWithSchema> childNodes;
+ if (augSchema != null) {
+ childNodes = augmentationsToChild.get(augSchema);
} else {
- DataSchemaNode choiceCandidate = schemas.pop();
- DataSchemaNode caseCandidate = schemas.pop();
- ChoiceNode choiceNode = null;
- ChoiceCaseNode caseNode = null;
- if (choiceCandidate instanceof ChoiceNode) {
- choiceNode = (ChoiceNode) choiceCandidate;
- } else {
- throw new IllegalArgumentException("Awaited node of type ChoiceNode but was "
- + choiceCandidate.getClass().getSimpleName());
- }
-
- if (caseCandidate instanceof ChoiceCaseNode) {
- caseNode = (ChoiceCaseNode) caseCandidate;
- } else {
- throw new IllegalArgumentException("Awaited node of type ChoiceCaseNode but was "
- + caseCandidate.getClass().getSimpleName());
- }
-
- AugmentationSchema augSchema = null;
- if (choiceCandidate.isAugmenting()) {
- augSchema = findCorrespondingAugment(getSchema(), choiceCandidate);
- }
+ childNodes = children;
+ }
- // looking for existing choice
- List<AbstractNodeDataWithSchema> childNodes = Collections.emptyList();
- if (augSchema != null) {
- childNodes = augmentationsToChild.get(augSchema);
- } else {
- childNodes = childs;
- }
+ CompositeNodeDataWithSchema caseNodeDataWithSchema = findChoice(childNodes, choiceCandidate, caseCandidate);
+ if (caseNodeDataWithSchema == null) {
+ ChoiceNodeDataWithSchema choiceNodeDataWithSchema = new ChoiceNodeDataWithSchema(choiceNode);
+ addChild(choiceNodeDataWithSchema);
+ caseNodeDataWithSchema = choiceNodeDataWithSchema.addCompositeChild(caseNode);
+ }
- CompositeNodeDataWithSchema caseNodeDataWithSchema = findChoice(childNodes, choiceCandidate, caseCandidate);
- if (caseNodeDataWithSchema == null) {
- ChoiceNodeDataWithSchema choiceNodeDataWithSchema = new ChoiceNodeDataWithSchema(choiceNode);
- addChild(choiceNodeDataWithSchema);
- caseNodeDataWithSchema = choiceNodeDataWithSchema.addCompositeChild(caseNode);
- }
+ return caseNodeDataWithSchema.addChild(schemas);
+ }
- return caseNodeDataWithSchema.addChild(schemas);
+ private AbstractNodeDataWithSchema addSimpleChild(final DataSchemaNode schema) {
+ SimpleNodeDataWithSchema newChild = null;
+ if (schema instanceof LeafSchemaNode) {
+ newChild = new LeafNodeDataWithSchema(schema);
+ } else if (schema instanceof AnyXmlSchemaNode) {
+ newChild = new AnyXmlNodeDataWithSchema(schema);
+ } else {
+ return null;
}
+ AugmentationSchema augSchema = null;
+ if (schema.isAugmenting()) {
+ augSchema = findCorrespondingAugment(getSchema(), schema);
+ }
+ if (augSchema != null) {
+ augmentationsToChild.put(augSchema, newChild);
+ } else {
+ addChild(newChild);
+ }
+ return newChild;
}
- private CaseNodeDataWithSchema findChoice(final List<AbstractNodeDataWithSchema> childNodes, final DataSchemaNode choiceCandidate,
+ private CaseNodeDataWithSchema findChoice(final Collection<AbstractNodeDataWithSchema> childNodes, final DataSchemaNode choiceCandidate,
final DataSchemaNode caseCandidate) {
- if (childNodes == null) {
- return null;
- }
- for (AbstractNodeDataWithSchema nodeDataWithSchema : childNodes) {
- if (nodeDataWithSchema instanceof ChoiceNodeDataWithSchema
- && nodeDataWithSchema.getSchema().getQName().equals(choiceCandidate.getQName())) {
- CaseNodeDataWithSchema casePrevious = ((ChoiceNodeDataWithSchema) nodeDataWithSchema).getCase();
- if (casePrevious.getSchema().getQName() != caseCandidate.getQName()) {
- throw new IllegalArgumentException("Data from case " + caseCandidate.getQName()
- + " are specified but other data from case " + casePrevious.getSchema().getQName()
- + " were specified erlier. Data aren't from the same case.");
+ if (childNodes != null) {
+ for (AbstractNodeDataWithSchema nodeDataWithSchema : childNodes) {
+ if (nodeDataWithSchema instanceof ChoiceNodeDataWithSchema
+ && nodeDataWithSchema.getSchema().getQName().equals(choiceCandidate.getQName())) {
+ CaseNodeDataWithSchema casePrevious = ((ChoiceNodeDataWithSchema) nodeDataWithSchema).getCase();
+
+ Preconditions.checkArgument(casePrevious.getSchema().getQName().equals(caseCandidate.getQName()),
+ "Data from case %s are specified but other data from case %s were specified erlier. Data aren't from the same case.",
+ caseCandidate.getQName(), casePrevious.getSchema().getQName());
+
+ return casePrevious;
}
- return casePrevious;
}
}
return null;
}
- public AbstractNodeDataWithSchema addCompositeChild(final DataSchemaNode schema) {
+ AbstractNodeDataWithSchema addCompositeChild(final DataSchemaNode schema) {
CompositeNodeDataWithSchema newChild;
if (schema instanceof ListSchemaNode) {
newChild = new ListNodeDataWithSchema(schema);
return newChild;
}
- public void addCompositeChild(final CompositeNodeDataWithSchema newChild) {
+ void addCompositeChild(final CompositeNodeDataWithSchema newChild) {
AugmentationSchema augSchema = findCorrespondingAugment(getSchema(), newChild.getSchema());
if (augSchema != null) {
- addChildToAugmentation(augSchema, newChild);
+ augmentationsToChild.put(augSchema, newChild);
} else {
addChild(newChild);
}
}
public void addChild(final AbstractNodeDataWithSchema newChild) {
- childs.add(newChild);
+ children.add(newChild);
+ }
+
+ /**
+ * Return a hint about how may children we are going to generate.
+ * @return Size of currently-present node list.
+ */
+ protected final int childSizeHint() {
+ return children.size();
}
/**
* Tries to find in {@code parent} which is dealed as augmentation target node with QName as {@code child}. If such
* node is found then it is returned, else null.
*/
- protected AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
+ AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
if (parent instanceof AugmentationTarget) {
for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- for (AbstractNodeDataWithSchema child : childs) {
- child.writeToStream(nnStreamWriter);
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ for (AbstractNodeDataWithSchema child : children) {
+ child.write(writer);
}
- for (Entry<AugmentationSchema, List<AbstractNodeDataWithSchema>> augmentationToChild : augmentationsToChild.entrySet()) {
-
- final List<AbstractNodeDataWithSchema> childsFromAgumentation = augmentationToChild.getValue();
-
+ for (Entry<AugmentationSchema, Collection<AbstractNodeDataWithSchema>> augmentationToChild : augmentationsToChild.asMap().entrySet()) {
+ final Collection<AbstractNodeDataWithSchema> childsFromAgumentation = augmentationToChild.getValue();
if (!childsFromAgumentation.isEmpty()) {
- nnStreamWriter.startAugmentationNode(toAugmentationIdentifier(augmentationToChild));
+ writer.startAugmentationNode(toAugmentationIdentifier(augmentationToChild.getKey()));
for (AbstractNodeDataWithSchema nodeDataWithSchema : childsFromAgumentation) {
- nodeDataWithSchema.writeToStream(nnStreamWriter);
+ nodeDataWithSchema.write(writer);
}
- nnStreamWriter.endNode();
+ writer.endNode();
}
}
}
- private static AugmentationIdentifier toAugmentationIdentifier(
- final Entry<AugmentationSchema, List<AbstractNodeDataWithSchema>> augmentationToChild) {
- Collection<DataSchemaNode> nodes = augmentationToChild.getKey().getChildNodes();
- Set<QName> nodesQNames = new HashSet<>();
- for (DataSchemaNode node : nodes) {
- nodesQNames.add(node.getQName());
- }
-
- return new AugmentationIdentifier(nodesQNames);
+ private static AugmentationIdentifier toAugmentationIdentifier(final AugmentationSchema schema) {
+ final Collection<QName> qnames = Collections2.transform(schema.getChildNodes(), QNAME_FUNCTION);
+ return new AugmentationIdentifier(ImmutableSet.copyOf(qnames));
}
-
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
-
import java.io.IOException;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- nnStreamWriter.startContainerNode(provideNodeIdentifier(), UNKNOWN_SIZE);
- super.writeToStream(nnStreamWriter);
- nnStreamWriter.endNode();
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ writer.startContainerNode(provideNodeIdentifier(), childSizeHint());
+ super.write(writer);
+ writer.endNode();
}
}
import java.util.ArrayDeque;
import java.util.Deque;
+import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.codec.gson.helpers.RestCodecFactory;
+import org.opendaylight.yangtools.yang.data.codec.gson.helpers.SchemaContextUtils;
+import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
private final Deque<TypeInfo> stack = new ArrayDeque<>();
private final SchemaContext schemaContext;
+ private final SchemaContextUtils utils;
+ private final RestCodecFactory codecs;
+ private final SchemaTracker tracker;
private final Writer writer;
private final String indent;
this.writer = Preconditions.checkNotNull(writer);
Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
-
if (indentSize != 0) {
indent = Strings.repeat(" ", indentSize);
} else {
indent = null;
}
+
+ this.utils = SchemaContextUtils.create(schemaContext);
+ this.codecs = RestCodecFactory.create(utils);
+ this.tracker = SchemaTracker.create(schemaContext);
}
/**
@Override
public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
+ final LeafSchemaNode schema = tracker.leafNode(name);
+ final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
+
separateElementFromPreviousElement();
writeJsonIdentifier(name);
currentNamespace = stack.peek().getNamespace();
- writeValue(value.toString());
+ writeValue(String.valueOf(codec.serialize(value)));
separateNextSiblingsWithComma();
}
@Override
public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ tracker.startLeafSet(name);
+
separateElementFromPreviousElement();
stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
writeJsonIdentifier(name);
@Override
public void leafSetEntryNode(final Object value) throws IOException {
+ final LeafListSchemaNode schema = tracker.leafSetEntryNode();
+ final Codec<Object, Object> codec = codecs.codecFor(schema.getType());
+
separateElementFromPreviousElement();
- writeValue(value.toString());
+ writeValue(String.valueOf(codec.serialize(value)));
separateNextSiblingsWithComma();
}
@Override
public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ tracker.startContainerNode(name);
+
separateElementFromPreviousElement();
stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
writeJsonIdentifier(name);
@Override
public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ tracker.startList(name);
+
separateElementFromPreviousElement();
stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
writeJsonIdentifier(name);
@Override
public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ tracker.startListItem(name);
+
stack.push(new TypeInfo(NodeType.OBJECT, name.getNodeType().getNamespace()));
separateElementFromPreviousElement();
writeStartObject();
@Override
public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ tracker.startList(name);
+
separateElementFromPreviousElement();
stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
writeJsonIdentifier(name);
@Override
public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
throws IOException {
+ tracker.startListItem(identifier);
+
stack.push(new TypeInfo(NodeType.OBJECT, identifier.getNodeType().getNamespace()));
separateElementFromPreviousElement();
writeStartObject();
@Override
public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ tracker.startListItem(name);
+
stack.push(new TypeInfo(NodeType.LIST, name.getNodeType().getNamespace()));
separateElementFromPreviousElement();
writeJsonIdentifier(name);
@Override
public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IllegalArgumentException {
+ tracker.startChoiceNode(name);
handleInvisibleNode(name.getNodeType().getNamespace());
}
@Override
public void startAugmentationNode(final AugmentationIdentifier identifier) throws IllegalArgumentException {
+ tracker.startAugmentationNode(identifier);
handleInvisibleNode(currentNamespace);
}
@Override
public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
+ final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
+ // FIXME: should have a codec based on this :)
+
separateElementFromPreviousElement();
writeJsonIdentifier(name);
currentNamespace = stack.peek().getNamespace();
@Override
public void endNode() throws IOException {
- switch (stack.peek().getType()) {
+ tracker.endNode();
+
+ final TypeInfo t = stack.pop();
+ switch (t.getType()) {
case LIST:
indentLeft();
newLine();
default:
break;
}
- stack.pop();
+
currentNamespace = stack.isEmpty() ? null : stack.peek().getNamespace();
separateNextSiblingsWithComma();
}
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Iterators;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
import com.google.gson.stream.MalformedJsonException;
import java.io.Closeable;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
-import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.codec.gson.helpers.IdentityValuesDTO;
*/
@Beta
public final class JsonParserStream implements Closeable, Flushable {
- private static final Splitter COLON_SPLITTER = Splitter.on(':');
-
private final Deque<URI> namespaces = new ArrayDeque<>();
private final NormalizedNodeStreamWriter writer;
private final SchemaContextUtils utils;
isEmpty = false;
CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(schema);
read(reader, compositeNodeDataWithSchema);
- compositeNodeDataWithSchema.writeToStream(writer);
+ compositeNodeDataWithSchema.write(writer);
return this;
// return read(reader);
}
}
- public void read(final JsonReader in, final AbstractNodeDataWithSchema parent) throws IOException {
+ private final void setValue(final AbstractNodeDataWithSchema parent, final String value) {
+ Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type", parent);
- final JsonToken peek = in.peek();
- Optional<String> value = Optional.absent();
- switch (peek) {
+ final Object translatedValue = translateValueByType(value, parent.getSchema());
+ ((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
+ }
+
+ public void read(final JsonReader in, final AbstractNodeDataWithSchema parent) throws IOException {
+ switch (in.peek()) {
case STRING:
case NUMBER:
- value = Optional.of(in.nextString());
+ setValue(parent, in.nextString());
break;
case BOOLEAN:
- value = Optional.of(Boolean.toString(in.nextBoolean()));
+ setValue(parent, Boolean.toString(in.nextBoolean()));
break;
case NULL:
in.nextNull();
- value = Optional.of((String) null);
+ setValue(parent, null);
break;
- default:
- break;
- }
- if (value.isPresent()) {
- final Object translatedValue = translateValueByType(value.get(), parent.getSchema());
- ((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
- }
-
- switch (peek) {
case BEGIN_ARRAY:
in.beginArray();
while (in.hasNext()) {
case NAME:
case END_OBJECT:
case END_ARRAY:
+ break;
}
}
inputValue = value;
}
- // FIXME: extract this as a cacheable context?
- final Codec<Object, Object> codec = codecs.codecFor(typeDefinition);
- if (codec == null) {
- return null;
- }
- return codec.deserialize(inputValue);
+ return codecs.codecFor(typeDefinition).deserialize(inputValue);
}
private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
}
private static URI getNamespaceFor(final String jsonElementName) {
- final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
-
// The string needs to me in form "moduleName:localName"
- if (it.hasNext()) {
- final String maybeURI = it.next();
- if (Iterators.size(it) == 1) {
- return URI.create(maybeURI);
- }
+ final int idx = jsonElementName.indexOf(':');
+ if (idx == -1 || jsonElementName.indexOf(':', idx + 1) != -1) {
+ return null;
}
- return null;
+ // FIXME: is this correct? This should be looking up module name instead
+ return URI.create(jsonElementName.substring(0, idx));
}
private static String getLocalNameFor(final String jsonElementName) {
- final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
-
// The string needs to me in form "moduleName:localName"
- final String ret = Iterators.get(it, 1, null);
- return ret != null && !it.hasNext() ? ret : jsonElementName;
+ final int idx = jsonElementName.indexOf(':');
+ if (idx == -1 || jsonElementName.indexOf(':', idx + 1) != -1) {
+ return jsonElementName;
+ }
+
+ return jsonElementName.substring(idx + 1);
}
private void removeNamespace() {
}
private NamespaceAndName resolveNamespace(final String childName) {
- int lastIndexOfColon = childName.lastIndexOf(":");
+ int lastIndexOfColon = childName.lastIndexOf(':');
String moduleNamePart = null;
String nodeNamePart = null;
URI namespace = null;
}
/**
- * Returns stack of schema nodes via which it was necessary to prass to get schema node with specified
+ * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
* {@code childName} and {@code namespace}
*
* @param dataSchemaNode
* @param childName
* @param namespace
- * @return stack of schema nodes via which it was passed through. If found schema node is dirrect child then stack
- * contains only one node. If it is found under choice and case then stack should conains 2*n+1 element
+ * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
+ * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
* (where n is number of choices through it was passed)
*/
private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- nnStreamWriter.leafSetEntryNode(getValue());
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ writer.leafSetEntryNode(getValue());
}
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
-
import java.io.IOException;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- nnStreamWriter.startLeafSet(provideNodeIdentifier(), UNKNOWN_SIZE);
- super.writeToStream(nnStreamWriter);
- nnStreamWriter.endNode();
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ writer.startLeafSet(provideNodeIdentifier(), childSizeHint());
+ super.write(writer);
+ writer.endNode();
}
}
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- nnStreamWriter.leafNode(provideNodeIdentifier(), getValue());
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ writer.leafNode(provideNodeIdentifier(), getValue());
}
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import javax.annotation.Nonnull;
+
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
class ListEntryNodeDataWithSchema extends CompositeNodeDataWithSchema {
+ private static final Function<SimpleNodeDataWithSchema, Object> VALUE_FUNCTION = new Function<SimpleNodeDataWithSchema, Object>() {
+ @Override
+ public Object apply(@Nonnull final SimpleNodeDataWithSchema input) {
+ return input.getValue();
+ }
+ };
private final Map<QName, SimpleNodeDataWithSchema> qNameToKeys = new HashMap<>();
@Override
public void addChild(final AbstractNodeDataWithSchema newChild) {
- DataSchemaNode childSchema = newChild.getSchema();
+ final DataSchemaNode childSchema = newChild.getSchema();
if (childSchema instanceof LeafSchemaNode && isPartOfKey((LeafSchemaNode) childSchema)) {
qNameToKeys.put(childSchema.getQName(), (SimpleNodeDataWithSchema)newChild);
}
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- int keyCount = ((ListSchemaNode) getSchema()).getKeyDefinition().size();
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ final int keyCount = ((ListSchemaNode) getSchema()).getKeyDefinition().size();
if (keyCount == 0) {
- nnStreamWriter.startUnkeyedListItem(provideNodeIdentifier(), UNKNOWN_SIZE);
- super.writeToStream(nnStreamWriter);
- nnStreamWriter.endNode();
- } else if (keyCount == qNameToKeys.size()) {
- nnStreamWriter.startMapEntryNode(provideNodeIdentifierWithPredicates(), UNKNOWN_SIZE);
- super.writeToStream(nnStreamWriter);
- nnStreamWriter.endNode();
- } else {
- throw new IllegalStateException("Some of keys of " + getSchema().getQName() + " are missing in input.");
+ writer.startUnkeyedListItem(provideNodeIdentifier(), childSizeHint());
+ super.write(writer);
+ writer.endNode();
+ return;
}
- }
-
- private NodeIdentifierWithPredicates provideNodeIdentifierWithPredicates() {
- Map<QName, Object> qNameToPredicateValues = new HashMap<>();
- for (SimpleNodeDataWithSchema simpleNodeDataWithSchema : qNameToKeys.values()) {
- qNameToPredicateValues.put(simpleNodeDataWithSchema.getSchema().getQName(), simpleNodeDataWithSchema.getValue());
- }
-
- return new NodeIdentifierWithPredicates(getSchema().getQName(), qNameToPredicateValues);
+ Preconditions.checkState(keyCount == qNameToKeys.size(), "Input is missing some of the keys of %s", getSchema().getQName());
+ writer.startMapEntryNode(
+ new NodeIdentifierWithPredicates(getSchema().getQName(), Maps.transformValues(qNameToKeys, VALUE_FUNCTION)),
+ childSizeHint());
+ super.write(writer);
+ writer.endNode();
}
-
}
*/
package org.opendaylight.yangtools.yang.data.codec.gson;
-import static org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.UNKNOWN_SIZE;
-
import java.io.IOException;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
}
@Override
- protected void writeToStream(final NormalizedNodeStreamWriter nnStreamWriter) throws IOException {
- if (!((ListSchemaNode) getSchema()).getKeyDefinition().isEmpty()) {
- nnStreamWriter.startMapNode(provideNodeIdentifier(), UNKNOWN_SIZE);
+ public void write(final NormalizedNodeStreamWriter writer) throws IOException {
+ if (((ListSchemaNode) getSchema()).getKeyDefinition().isEmpty()) {
+ writer.startUnkeyedList(provideNodeIdentifier(), childSizeHint());
} else {
- nnStreamWriter.startUnkeyedList(provideNodeIdentifier(), UNKNOWN_SIZE);
+ writer.startMapNode(provideNodeIdentifier(), childSizeHint());
}
- super.writeToStream(nnStreamWriter);
- nnStreamWriter.endNode();
+ super.write(writer);
+ writer.endNode();
}
}
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
import org.opendaylight.yangtools.concepts.Codec;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
*/
@Beta
public final class RestCodecFactory {
+ private final LoadingCache<TypeDefinition<?>, Codec<Object, Object>> codecs =
+ CacheBuilder.newBuilder().softValues().build(new CacheLoader<TypeDefinition<?>, Codec<Object, Object>>() {
+ @Override
+ public Codec<Object, Object> load(final TypeDefinition<?> key) throws Exception {
+ return new ObjectCodec(utils, key);
+ }
+ });
private final SchemaContextUtils utils;
private RestCodecFactory(final SchemaContextUtils utils) {
}
public final Codec<Object, Object> codecFor(final TypeDefinition<?> typeDefinition) {
- // FIXME: implement loadingcache
- return new ObjectCodec(utils, typeDefinition);
+ return codecs.getUnchecked(typeDefinition);
}
}
import java.util.List;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.stream.LoggingNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
*
* @throws IOException
*/
+ @Ignore
@Test
public void immutableNormalizedNodeStreamWriterDemonstration() throws IOException {
/*
* This is the serialization part.
*/
// We want to write the first child out
- final DataContainerChild<? extends PathArgument, ?> firstChild = ((ContainerNode) parsedData).getValue().iterator().next();
+ final DataContainerChild<? extends PathArgument, ?> firstChild = (DataContainerChild<? extends PathArgument, ?>) parsedData;
LOG.debug("Serializing first child: {}", firstChild);
// String holder
"anyxml-in-data":"foo"
}
],
-
+
"lf13-any":{
"anyxml-in-data":"foo"
},
-
+
"lf14-any":"anyxml data",
-
+
"lflst11":["lflst11 value1","lflst11 value2"],
-
+
"lst11":[
- {
+ {
"key111":"key111 value",
"lf112":"/complexjson:cont1/complexjson:lflst11",
"lf113":"lf113 value",
"lf111":"lf111 value"
}
- ],
+ ],
"lf11" : "453",
"lf12_1" : "lf12 value",
- "lf13" : "lf13 value",
+ "lf13" : "lf13 value",
"complexjson-augmentation:lf15_11" : "lf15_11 value from augmentation",
"complexjson-augmentation:lf15_12" : "lf15_12 value from augmentation",
"lf15_11" : "one two",
"lf15_12" : "complexjson:lf11",
"lf15_21" : "lf15_21 value",
- "lf17" : "lf17 value",
-
+ "lf17" : "lf17 value",
+
"lst12":[
{
"lf121":"lf121 value"
}
]
}
-}
\ No newline at end of file
+}
namespace "ns:complex:json";
prefix cj;
- revision "2014-08-11" {
+ revision "2014-08-11" {
}
-
-
+
+
identity ident;
-
+
container cont1 {
-
+
anyxml lf12-any;
anyxml lf13-any;
anyxml lf14-any;
-
+
leaf lf11 {
type int32;
}
-
+
leaf-list lflst11 {
type string;
}
-
+
list lst11 {
key "key111 lf111";
leaf key111 {
type string;
}
}
-
+
list lst12 {
leaf lf121 {
type string;
type string;
}
}
-
-
+
+
choice choc11 {
case c11A {
leaf lf13 {
}
}
}
-
-
+
augment "/cont1/choc12" {
case c12B {
leaf lf17 {
type string;
}
}
- }
-
-
+ }
+
augment "/cont1" {
container cont11 {
leaf lf111 {
type string;
}
- }
+ }
}
-
+
augment "/cont1" {
leaf lf12_1 {
- type string;
- }
+ type string;
+ }
leaf lf12_2 {
type string;
}
}
-
+
augment "/cont1" {
leaf lf12_3 {
- type string;
- }
+ type string;
+ }
}
-
-
+
augment "/cont1/choc11" {
case c11B {
leaf lf14_1 {
- type string;
- }
+ type string;
+ }
}
}
-
+
augment "/cont1/choc11" {
case c11C {
leaf lf14_2 {
- type string;
- }
+ type string;
+ }
}
}
-
+
augment "/cont1/choc11/c11A" {
leaf lf15_11 {
- type bits {
- bit one;
- bit two;
- bit three;
- }
- }
+ type bits {
+ bit one;
+ bit two;
+ bit three;
+ }
+ }
leaf lf15_12 {
- type identityref {
- base ident;
- }
- }
-
+ type identityref {
+ base ident;
+ }
+ }
+
}
-
+
augment "/cont1/choc11/c11A" {
leaf lf15_21 {
- type string;
- }
+ type string;
+ }
}
}
import org.opendaylight.yangtools.yang.binding.BindingCodec;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-public interface InstanceIdentifierCodec extends BindingCodec<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,InstanceIdentifier<?>> {
-
+public interface InstanceIdentifierCodec extends BindingCodec<YangInstanceIdentifier, InstanceIdentifier<?>> {
@Override
- org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier serialize(InstanceIdentifier<?> input);
+ YangInstanceIdentifier serialize(InstanceIdentifier<?> input);
@Override
- InstanceIdentifier<?> deserialize(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier input);
+ InstanceIdentifier<?> deserialize(YangInstanceIdentifier input);
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.codec;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import javax.xml.stream.XMLStreamWriter;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Utility class for tracking the underlying state of the underlying
+ * schema node.
+ */
+@Beta
+public final class SchemaTracker {
+ private static final Logger LOG = LoggerFactory.getLogger(SchemaTracker.class);
+ private final Deque<Object> schemaStack = new ArrayDeque<>();
+ private final DataNodeContainer root;
+
+ private SchemaTracker(final SchemaContext context, final SchemaPath path) {
+ DataNodeContainer current = Preconditions.checkNotNull(context);
+ for (QName qname : path.getPathFromRoot()) {
+ final DataSchemaNode child = current.getDataChildByName(qname);
+ Preconditions.checkArgument(child instanceof DataNodeContainer);
+ current = (DataNodeContainer) child;
+ }
+
+ this.root = current;
+ }
+
+ /**
+ * Create a new writer with the specified context as its root.
+ *
+ * @param writer Output {@link XMLStreamWriter}
+ * @param context Associated {@link SchemaContext}.
+ * @return A new {@link NormalizedNodeStreamWriter}
+ */
+ public static SchemaTracker create(final SchemaContext context) {
+ return create(context, SchemaPath.ROOT);
+ }
+
+ /**
+ * Create a new writer with the specified context and rooted in the specified schema path
+ *
+ * @param writer Output {@link XMLStreamWriter}
+ * @param context Associated {@link SchemaContext}.
+ *
+ * @return A new {@link NormalizedNodeStreamWriter}
+ */
+ public static SchemaTracker create(final SchemaContext context, final SchemaPath path) {
+ return new SchemaTracker(context, path);
+ }
+
+ public Object getParent() {
+ if (schemaStack.isEmpty()) {
+ return root;
+ }
+ return schemaStack.peek();
+ }
+
+ private SchemaNode getSchema(final PathArgument name) {
+ final Object parent = getParent();
+ Preconditions.checkState(parent instanceof DataNodeContainer);
+
+ final QName qname = name.getNodeType();
+ final SchemaNode schema = ((DataNodeContainer)parent).getDataChildByName(qname);
+ Preconditions.checkArgument(schema != null, "Could not find schema for node %s in %s", qname, parent);
+ return schema;
+ }
+
+ public void startList(final NodeIdentifier name) {
+ final SchemaNode schema = getSchema(name);
+ Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
+ schemaStack.push(schema);
+ }
+
+ public void startListItem(final PathArgument name) throws IOException {
+ final Object schema = getParent();
+ Preconditions.checkArgument(schema instanceof ListSchemaNode, "List item is not appropriate");
+ schemaStack.push(schema);
+ }
+
+ public LeafSchemaNode leafNode(final NodeIdentifier name) throws IOException {
+ final SchemaNode schema = getSchema(name);
+
+ Preconditions.checkArgument(schema instanceof LeafSchemaNode, "Node %s is not a leaf", schema.getPath());
+ return (LeafSchemaNode) schema;
+ }
+
+ public SchemaNode startLeafSet(final NodeIdentifier name) {
+ final SchemaNode schema = getSchema(name);
+
+ Preconditions.checkArgument(schema instanceof LeafListSchemaNode, "Node %s is not a leaf-list", schema.getPath());
+ schemaStack.push(schema);
+ return schema;
+ }
+
+ public LeafListSchemaNode leafSetEntryNode() {
+ final Object parent = getParent();
+
+ Preconditions.checkArgument(parent instanceof LeafListSchemaNode, "Not currently in a leaf-list");
+ return (LeafListSchemaNode) parent;
+ }
+
+ public SchemaNode startChoiceNode(final NodeIdentifier name) {
+ LOG.debug("Enter choice {}", name);
+ final SchemaNode schema = getSchema(name);
+
+ Preconditions.checkArgument(schema instanceof ChoiceNode, "Node %s is not a choice", schema.getPath());
+ schemaStack.push(schema);
+ return schema;
+ }
+
+ public SchemaNode startContainerNode(final NodeIdentifier name) {
+ LOG.debug("Enter container {}", name);
+ final SchemaNode schema = getSchema(name);
+
+ Preconditions.checkArgument(schema instanceof ContainerSchemaNode, "Node %s is not a container", schema.getPath());
+ schemaStack.push(schema);
+ return schema;
+ }
+
+ public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
+ LOG.debug("Enter augmentation {}", identifier);
+ final Object parent = getParent();
+
+ Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
+ final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
+ schemaStack.push(schema);
+ return schema;
+ }
+
+ public AnyXmlSchemaNode anyxmlNode(final NodeIdentifier name) {
+ final SchemaNode schema = getSchema(name);
+
+ Preconditions.checkArgument(schema instanceof AnyXmlSchemaNode, "Node %s is not anyxml", schema.getPath());
+ return (AnyXmlSchemaNode)schema;
+ }
+
+ public Object endNode() {
+ return schemaStack.pop();
+ }
+}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.io.BaseEncoding;
-
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.xml.bind.DatatypeConverter;
-
import org.opendaylight.yangtools.yang.data.api.codec.BinaryCodec;
import org.opendaylight.yangtools.yang.data.api.codec.BitsCodec;
import org.opendaylight.yangtools.yang.data.api.codec.BooleanCodec;
return 8;
} else {
String formatedMessage = String.format("Incorrect lexical representation of integer value: %s."
- + "\nAn integer value can be defined as: "
- + "\n - a decimal number,"
- + "\n - a hexadecimal number (prefix 0x),"
- + "\n - an octal number (prefix 0)."
- + "\nSigned values are allowed. Spaces between digits are NOT allowed.", integer);
+ + "%nAn integer value can be defined as: "
+ + "%n - a decimal number,"
+ + "%n - a hexadecimal number (prefix 0x),"
+ + "%n - an octal number (prefix 0)."
+ + "%nSigned values are allowed. Spaces between digits are NOT allowed.", integer);
throw new NumberFormatException(formatedMessage);
}
}
@Override
public String deserialize(final String stringRepresentation) {
- return stringRepresentation == null ? "" :stringRepresentation;
+ return stringRepresentation == null ? "" : stringRepresentation;
}
@Override
public String serialize(final String data) {
- return data == null ? "" : data.toString();
+ return data == null ? "" : data;
}
};
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.codec.xml;
+
+import com.google.common.base.Preconditions;
+
+import java.io.IOException;
+
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+
+/**
+ * A {@link NormalizedNodeStreamWriter} which translates the events into an
+ * {@link XMLStreamWriter}, resulting in a RFC 6020 XML encoding.
+ */
+public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
+ private static final XmlStreamUtils UTILS = XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER);
+
+ private final XMLStreamWriter writer;
+ private final SchemaTracker tracker;
+
+ private XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
+ this.writer = Preconditions.checkNotNull(writer);
+ this.tracker = SchemaTracker.create(context, path);
+ }
+
+ /**
+ * Create a new writer with the specified context as its root.
+ *
+ * @param writer Output {@link XMLStreamWriter}
+ * @param context Associated {@link SchemaContext}.
+ * @return A new {@link NormalizedNodeStreamWriter}
+ */
+ public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context) {
+ return create( writer, context, SchemaPath.ROOT);
+ }
+
+ /**
+ * Create a new writer with the specified context and rooted in the specified schema path
+ *
+ * @param writer Output {@link XMLStreamWriter}
+ * @param context Associated {@link SchemaContext}.
+ *
+ * @return A new {@link NormalizedNodeStreamWriter}
+ */
+ public static NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
+ final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
+ Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
+ return new XMLStreamNormalizedNodeStreamWriter(writer, context, path);
+ }
+
+ private void writeElement(final QName qname, final TypeDefinition<?> type, final Object value) throws IOException {
+ final String ns = qname.getNamespace().toString();
+
+ try {
+ if (value != null) {
+ writer.writeStartElement(ns, qname.getLocalName());
+ UTILS.writeValue(writer, type, value);
+ writer.writeEndElement();
+ } else {
+ writer.writeEmptyElement(ns, qname.getLocalName());
+ }
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to emit element", e);
+ }
+ }
+
+ private void startElement(final QName qname) throws IOException {
+ try {
+ writer.writeStartElement(qname.getNamespace().toString(), qname.getLocalName());
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to start element", e);
+ }
+ }
+
+ private void startList(final NodeIdentifier name) {
+ tracker.startList(name);
+ }
+
+ private void startListItem(final PathArgument name) throws IOException {
+ tracker.startListItem(name);
+ startElement(name.getNodeType());
+ }
+
+ @Override
+ public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
+ final LeafSchemaNode schema = tracker.leafNode(name);
+
+ writeElement(schema.getQName(), schema.getType(), value);
+ }
+
+ @Override
+ public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
+ tracker.startLeafSet(name);
+ }
+
+ @Override
+ public void leafSetEntryNode(final Object value) throws IOException {
+ final LeafListSchemaNode schema = tracker.leafSetEntryNode();
+ writeElement(schema.getQName(), schema.getType(), value);
+ }
+
+ @Override
+ public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ final SchemaNode schema = tracker.startContainerNode(name);
+ startElement(schema.getQName());
+ }
+
+ @Override
+ public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
+ startList(name);
+ }
+
+ @Override
+ public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
+ startListItem(name);
+ }
+
+ @Override
+ public void startMapNode(final NodeIdentifier name, final int childSizeHint) {
+ startList(name);
+ }
+
+ @Override
+ public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) throws IOException {
+ startListItem(identifier);
+ }
+
+ @Override
+ public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
+ startList(name);
+ }
+
+ @Override
+ public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) {
+ tracker.startChoiceNode(name);
+ }
+
+ @Override
+ public void startAugmentationNode(final AugmentationIdentifier identifier) {
+ tracker.startAugmentationNode(identifier);
+ }
+
+ @Override
+ public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
+ final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
+ final QName qname = schema.getQName();
+ final String ns = qname.getNamespace().toString();
+
+ try {
+ if (value != null) {
+ writer.writeStartElement(ns, qname.getLocalName());
+ UTILS.writeValue(writer, (Node<?>)value, schema);
+ writer.writeEndElement();
+ } else {
+ writer.writeEmptyElement(ns, qname.getLocalName());
+ }
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to emit element", e);
+ }
+ }
+
+ @Override
+ public void endNode() throws IOException {
+ final Object schema = tracker.endNode();
+
+ try {
+ if (schema instanceof ListSchemaNode) {
+ // For lists, we only emit end element on the inner frame
+ final Object parent = tracker.getParent();
+ if (parent == schema) {
+ writer.writeEndElement();
+ }
+ } else if (schema instanceof ContainerSchemaNode) {
+ // Emit container end element
+ writer.writeEndElement();
+ }
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to end element", e);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ writer.close();
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to close writer", e);
+ }
+ }
+
+ @Override
+ public void flush() throws IOException {
+ try {
+ writer.flush();
+ } catch (XMLStreamException e) {
+ throw new IOException("Failed to flush writer", e);
+ }
+ }
+}
package org.opendaylight.yangtools.yang.data.impl.codec.xml;
import java.util.Map;
-
import javax.annotation.Nonnull;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
if (pathArgument instanceof NodeIdentifierWithPredicates) {
Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
- for (QName keyValue : predicates.keySet()) {
- String predicateValue = String.valueOf(predicates.get(keyValue));
+ for (Map.Entry<QName, Object> entry : predicates.entrySet()) {
+ String predicateValue = String.valueOf(entry.getValue());
textContent.append('[');
- textContent.append(prefixes.encodeQName(keyValue));
+ textContent.append(prefixes.encodeQName(entry.getKey()));
textContent.append("='");
textContent.append(predicateValue);
textContent.append("']");
throw new UnsupportedOperationException("Utilities class should not be instantiated");
}
- public static final CollectionNodeBuilder<MapEntryNode, MapNode> mapNodeBuilder() {
+ public static CollectionNodeBuilder<MapEntryNode, MapNode> mapNodeBuilder() {
return ImmutableMapNodeBuilder.create();
}
- public static final CollectionNodeBuilder<MapEntryNode, MapNode> mapNodeBuilder(final QName name) {
+ public static CollectionNodeBuilder<MapEntryNode, MapNode> mapNodeBuilder(final QName name) {
return ImmutableMapNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(name));
}
* @param value Value of leaf node
* @return Leaf node with supplied identifier and value
*/
- public static final <T> LeafNode<T> leafNode(final NodeIdentifier name,final T value) {
+ public static <T> LeafNode<T> leafNode(final NodeIdentifier name,final T value) {
return ImmutableLeafNodeBuilder.<T>create()
.withNodeIdentifier(name)
.withValue(value)
}
/**
- *
* Construct immutable leaf node
*
* @param name QName which will be used as node identifier
* @param value Value of leaf node.
* @return Leaf node with supplied identifier and value
*/
- public static final <T> LeafNode<T> leafNode(final QName name,final T value) {
+ public static <T> LeafNode<T> leafNode(final QName name,final T value) {
return leafNode(new NodeIdentifier(name), value);
}
import java.util.Map;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final DataNodeContainer schema,
final Set<QName> childNodes, final Set<YangInstanceIdentifier.AugmentationIdentifier> augments) {
- if (isLegal == false) {
+ if (!isLegal) {
throw new IllegalChildException(child, schema, childNodes, augments);
}
}
public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final DataSchemaNode schema,
final Set<QName> childNodes) {
- if (isLegal == false) {
+ if (!isLegal) {
throw new IllegalChildException(child, schema, childNodes);
}
}
public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final ChoiceNode schema) {
- if (isLegal == false) {
+ if (!isLegal) {
throw new IllegalChildException(child, schema);
}
}
public static void checkLegalData(final boolean isLegal, final String messageTemplate, final Object... messageAttrs) {
- if (isLegal == false) {
+ if (!isLegal) {
throw new DataValidationException(String.format(messageTemplate, messageAttrs));
}
}
Object expectedValue = nodeId.getKeyValues().get(keyQName);
Object actualValue = childNode.getValue();
- if (childNode == null) {
- throw new IllegalListKeyException(keyQName, nodeId, actualValue, expectedValue);
- }
}
public static void checkListKey(final DataContainerChild<?, ?> childNode, final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeId) {
private final MavenProject project;
private final boolean inspectDependencies;
private final BuildContext buildContext;
- private YangProvider yangProvider;
+ private final YangProvider yangProvider;
@VisibleForTesting
YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
static class YangProvider {
-
-
void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
throws MojoFailureException {
// copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
+
File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
+ addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
+
+ // Also copy to the actual build output dir if different than "target". When running in
+ // Eclipse this can differ (eg "target-ide").
+
+ File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
+ CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
+ if(!actualGeneratedYangDir.equals(generatedYangDir)) {
+ addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
+ }
+ }
+
+ private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
+ File[] excludedFiles, File generatedYangDir)
+ throws MojoFailureException {
File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
withMetaInf.mkdirs();
org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
}
} catch (IOException e) {
- String message = "Unable to list yang files into resource folder";
- log.warn(message, e);
- throw new MojoFailureException(message, e);
+ log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
+ throw new MojoFailureException("Unable to list yang files into resource folder", e);
}
setResource(generatedYangDir, project);
* Cached legacy path, filled-in when {@link #getPath()} or {@link #getPathTowardsRoot()}
* is invoked.
*/
- private ImmutableList<QName> legacyPath;
+ private volatile ImmutableList<QName> legacyPath;
private ImmutableList<QName> getLegacyPath() {
- if (legacyPath == null) {
- legacyPath = ImmutableList.copyOf(getPathTowardsRoot()).reverse();
+ ImmutableList<QName> ret = legacyPath;
+ if (ret == null) {
+ synchronized (this) {
+ ret = legacyPath;
+ if (ret == null) {
+ ret = ImmutableList.copyOf(getPathTowardsRoot()).reverse();
+ legacyPath = ret;
+ }
+ }
}
- return legacyPath;
+ return ret;
}
/**
}
if (m.isEmpty()) {
- sources.remove(m);
+ sources.remove(source.getSourceIdentifier());
}
}
}
public static final int MAX_VALUE = 65535;
private static final String DESCRIPTION = "uint16 represents integer values between 0 and 65535, inclusively.";
- private static Uint16 INSTANCE = new Uint16();
+ private static final Uint16 INSTANCE = new Uint16();
private Uint16() {
super(BaseTypes.UINT16_QNAME, DESCRIPTION, MAX_VALUE, "");
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((types == null) ? 0 : types.hashCode());
+ result = prime * result + types.hashCode();
return result;
}
builder.append(BaseTypes.UNION_QNAME);
builder.append(" (types=[");
for (TypeDefinition<?> td : types) {
- builder.append(", " + td.getQName().getLocalName());
+ builder.append(", " ).append(td.getQName().getLocalName());
}
- builder.append("]");
+ builder.append(']');
return builder.toString();
}
} else if (!mustConstraints.equals(other.mustConstraints)) {
return false;
}
- if (mandatory != other.mandatory) {
+ if (!mandatory.equals(other.mandatory)) {
return false;
}
if (minElements == null) {
* all loaded modules
* @param module
* current module
- * @return grouping with given name if found, null otherwise
+ * @return grouping with given name, never null
+ * @throws YangParseException
+ * if no grouping found
*/
public static GroupingBuilder getTargetGroupingFromModules(final UsesNodeBuilder usesBuilder,
final Map<URI, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
if (targetModule == null) {
Module result = findModuleFromContext(context, module, prefix, 0);
targetModule = new ModuleBuilder(result);
- TreeMap<Date, ModuleBuilder> map = modules.get(prefix);
+ TreeMap<Date, ModuleBuilder> map = modules.get(targetModule.getNamespace());
if (map == null) {
map = new TreeMap<>();
map.put(targetModule.getRevision(), targetModule);
ModuleBuilder module = BuilderUtils.getParentModule(usesNode);
final GroupingBuilder targetGroupingBuilder = GroupingUtils.getTargetGroupingFromModules(usesNode, modules,
module);
- if (targetGroupingBuilder == null) {
- throw new YangParseException(module.getName(), usesNode.getLine(), "Referenced grouping '"
- + usesNode.getGroupingPath() + "' not found.");
- }
usesNode.setGrouping(targetGroupingBuilder);
}
}
private static final Function<Node, Module> TOPOLOGY_FUNCTION = new Function<TopologicalSort.Node, Module>() {
@Override
public Module apply(final TopologicalSort.Node input) {
+ if (input == null) {
+ return null;
+ }
ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
return moduleOrModuleBuilder.getModule();
}
@Override
public ModuleBuilder apply(final TopologicalSort.Node input) {
// Cast to ModuleBuilder from Node and return
+ if (input == null) {
+ return null;
+ }
ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
return moduleOrModuleBuilder.getModuleBuilder();
}
@Override
public ModuleBuilder apply(final TopologicalSort.Node input) {
+ if (input == null) {
+ return null;
+ }
ModuleOrModuleBuilder moduleOrModuleBuilder = ((ModuleNodeImpl) input).getReference();
if (moduleOrModuleBuilder.isModuleBuilder()) {
return moduleOrModuleBuilder.getModuleBuilder();