Merge "Bug 1113 - ietf-restconf needs to specify the version of ietf-yangtypes that...
authorTony Tkacik <ttkacik@cisco.com>
Fri, 30 May 2014 13:39:50 +0000 (13:39 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Fri, 30 May 2014 13:39:50 +0000 (13:39 +0000)
132 files changed:
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingGeneratorImpl.xtend
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/RuntimeGeneratedMappingServiceImpl.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TransformerGenerator.xtend
code-generator/binding-generator-impl/src/test/java/org/opendaylight/yangtools/sal/binding/generator/impl/RefineTest.java
code-generator/binding-generator-util/src/main/java/org/opendaylight/yangtools/binding/generator/util/BindingGeneratorUtil.java
common/checkstyle-logging/pom.xml [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/CheckLoggingUtil.java [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LogMessageConcatenationCheck.java [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LogMessagePlaceholderCountCheck.java [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerFactoryClassParameterCheck.java [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerMustBeSlf4jCheck.java [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerVariableModifiersCheck.java [new file with mode: 0644]
common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerVariableNameCheck.java [new file with mode: 0644]
common/checkstyle-logging/src/main/resources/checkstyle-logging.xml [new file with mode: 0644]
common/checkstyle-logging/src/test/java/org/opendaylight/yangtools/checkstyle/CheckLoggingTestClass.java [new file with mode: 0644]
common/checkstyle-logging/src/test/java/org/opendaylight/yangtools/checkstyle/CheckstyleTest.java [new file with mode: 0644]
common/pom.xml
common/util/pom.xml [new file with mode: 0644]
common/util/src/main/java/org/opendaylight/yangtools/util/MapAdaptor.java [new file with mode: 0644]
common/util/src/main/java/org/opendaylight/yangtools/util/ReadOnlyTrieMap.java [new file with mode: 0644]
common/util/src/main/java/org/opendaylight/yangtools/util/ReadWriteTrieMap.java [new file with mode: 0644]
common/util/src/test/java/org/opendaylight/yangtools/util/MapAdaptorTest.java [new file with mode: 0644]
integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/Bug466EmptyAugmentationCodecs.java
pom.xml
restconf/restconf-client-impl/src/test/java/org/opendaylight/yangtools/restconf/client/RestconfClientImplTest.java
restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug527Test.java
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/BindingMapping.java
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/QName.java
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/RpcError.java
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/RpcResult.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/CompositeNode.java
yang/yang-data-impl/pom.xml
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMap.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeFactory.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImpl.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlDocumentUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableLeafNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableLeafSetEntryNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableLeafSetNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableMapNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableOrderedLeafSetNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableOrderedMapNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableUnkeyedListNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableDataContainerNode.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableNormalizedNode.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableNormalizedValueAttrNode.java [moved from yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableNormalizedAttrNode.java with 87% similarity]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableNormalizedValueNode.java [new file with mode: 0644]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMapTest.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/MyNodeBuilder.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeFactoryTest.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeHelper.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeUtilsTest.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilderTest.java
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/ChoiceNode.java
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/DataSchemaNode.java
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/Module.java
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/SchemaPath.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/AbstractSignedInteger.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/AbstractUnsignedInteger.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/BaseConstraints.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/BaseTypes.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/BinaryType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/BitsType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/BooleanType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/DataNodeIterator.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Decimal64.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/EmptyType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/EnumerationType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/ExtendedType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/IdentityrefType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/InstanceIdentifier.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Int16.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Int32.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Int64.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Int8.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Leafref.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/LengthConstraintImpl.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/PatternConstraintImpl.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/RangeConstraintImpl.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/RevisionAwareXPathImpl.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/SchemaContextUtil.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/StringType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Uint16.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Uint32.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Uint64.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/Uint8.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/UnionType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/UnknownType.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/YangTypesConverter.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/package-info.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/AbstractCachingSchemaSourceProvider.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/AdvancedSchemaSourceProvider.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/FilesystemSchemaCachingProvider.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SchemaService.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SchemaSourceProvider.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SchemaSourceProviders.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SchemaSourceTransformation.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SourceIdentifier.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/TransformingSourceProvider.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/package-info.java [new file with mode: 0644]
yang/yang-parser-api/src/main/java/org/opendaylight/yangtools/yang/model/parser/api/YangContextParser.java
yang/yang-parser-api/src/main/java/org/opendaylight/yangtools/yang/model/parser/api/YangModelParser.java
yang/yang-parser-api/src/main/java/org/opendaylight/yangtools/yang/model/parser/api/YangSyntaxErrorException.java [new file with mode: 0644]
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/AugmentationSchemaBuilderImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/ModuleBuilder.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/UnionTypeBuilder.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/SchemaContextImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/YangErrorListener.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/YangParserImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/YangParserListenerImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/URLSchemaContextResolver.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceContext.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceContextResolver.java [new file with mode: 0644]
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceFromCapabilitiesResolver.java [new file with mode: 0644]
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceFromDependencyInfoResolver.java [new file with mode: 0644]
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/util/CopyUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/util/ModuleDependencySort.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/util/NamedByteArrayInputStream.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/util/ParserListenerUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/util/ParserUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/validator/BasicValidations.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/validator/YangModelBasicValidationListener.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/AugmentTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/TestUtils.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/UsesAugmentTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/YangParserSimpleTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/YangParserTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/YangParserWithContextTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/util/BitImplTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/util/RefineHolderTest.java

index 366868d29d8e32c8f13d9eae51a6ffeb4baabe6a..ec1ec8fc6af0bed3c0ffb33ddae6fad66656ac92 100644 (file)
@@ -1490,7 +1490,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
     private def Type createReturnTypeForUnion(GeneratedTOBuilder genTOBuilder, TypeDefinition<?> typeDef,
         GeneratedTypeBuilder typeBuilder, Module parentModule) {
-        val Type returnType = new ReferencedTypeImpl(genTOBuilder.packageName, genTOBuilder.name);
+        val GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.packageName, genTOBuilder.name)
         genTOBuilder.setTypedef(true);
         genTOBuilder.setIsUnion(true);
         (typeProvider as TypeProviderImpl).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
@@ -1512,7 +1512,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         } else {
             types.add(unionBuilder.toInstance)
         }
-        return returnType
+        return returnType.toInstance
     }
 
     private def GeneratedTypeBuilder addDefaultInterfaceDefinition(String packageName, SchemaNode schemaNode) {
index e6dc334e3ea566f48979d4a696b23a2ef403bb22..08308163ed392a15fac36ce80f0601495133fab0 100644 (file)
@@ -89,10 +89,9 @@ public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMap
 
     private final ClassLoadingStrategy classLoadingStrategy;
 
-    // FIXME: will become final
-    private ClassPool pool;
-    private AbstractTransformerGenerator binding;
-    private LazyGeneratedCodecRegistry registry;
+    private final AbstractTransformerGenerator binding;
+    private final LazyGeneratedCodecRegistry registry;
+    private final ClassPool pool;
 
     /*
      * FIXME: updated here, access from AbstractTransformer
@@ -106,16 +105,6 @@ public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMap
     private final ConcurrentMap<Type, Type> typeDefinitions = new ConcurrentHashMap<>();
     private SchemaContext schemaContext;
 
-    @Deprecated
-    public RuntimeGeneratedMappingServiceImpl() {
-        this(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
-    }
-
-    @Deprecated
-    public RuntimeGeneratedMappingServiceImpl(final ClassLoadingStrategy strat) {
-        classLoadingStrategy = strat;
-    }
-
     public RuntimeGeneratedMappingServiceImpl(final ClassPool pool) {
         this(pool, GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
     }
@@ -124,11 +113,6 @@ public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMap
         this.pool = Preconditions.checkNotNull(pool);
         this.classLoadingStrategy = Preconditions.checkNotNull(strat);
 
-        // FIXME: merge into constructor once legacy init() is removed
-        doInit();
-    }
-
-    private void doInit() {
         binding = new TransformerGenerator(this, pool);
         registry = new LazyGeneratedCodecRegistry(this, binding, classLoadingStrategy);
         binding.setListener(registry);
@@ -139,11 +123,6 @@ public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMap
         // }
     }
 
-    @Deprecated
-    public void setPool(final ClassPool pool) {
-        this.pool = pool;
-    }
-
     @Override
     public synchronized SchemaContext getSchemaContext() {
         return schemaContext;
@@ -261,7 +240,7 @@ public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMap
             for (Map.Entry<QName, Object> predicate : predicates.getKeyValues().entrySet()) {
                 newNodes.add(new SimpleNodeTOImpl<Object>(predicate.getKey(), null, predicate.getValue()));
             }
-            newNodes.addAll(ret.getChildren());
+            newNodes.addAll(ret.getValue());
             return new CompositeNodeTOImpl(last.getNodeType(), null, newNodes);
         }
         return ret;
@@ -352,10 +331,6 @@ public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMap
         }
     }
 
-    @Deprecated
-    public void init() {
-        doInit();
-    }
 
     @Override
     public Set<QName> getRpcQNamesFor(final Class<? extends RpcService> service) {
index 81f39e4e5de9c877c2badba835b02507f2fceac8..8821411022763d504a06e3fd9f1078005b898ee0 100644 (file)
@@ -1223,7 +1223,7 @@ class TransformerGenerator extends AbstractTransformerGenerator {
         return null;
     }
 
-    private def Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec, TypeDefinition<?> type) {
+    private def dispatch Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec, TypeDefinition<?> type) {
         var EnumerationType enumSchemaType
         if (type instanceof EnumerationType) {
             enumSchemaType = type as EnumerationType
index e02fe3a93eb2f0101f60912e11f2aaba97ee950e..daf7f97f0e9d0f69ef91f0064a368de330eea4b0 100644 (file)
@@ -12,8 +12,6 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -28,6 +26,7 @@ import java.util.GregorianCalendar;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -46,6 +45,9 @@ import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
 import org.opendaylight.yangtools.yang.parser.util.RefineHolder;
 import org.opendaylight.yangtools.yang.parser.util.RefineUtils;
 
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
 //Test for class RefineUtils
 public class RefineTest {
 
@@ -56,7 +58,7 @@ public class RefineTest {
         testModels.add(listModelFile);
     }
 
-    private void findUnknownNode(DataSchemaNodeBuilder childNode, String unknownNodeValue, String unknownNodeName) {
+    private void findUnknownNode(final DataSchemaNodeBuilder childNode, final String unknownNodeValue, final String unknownNodeName) {
         List<UnknownSchemaNodeBuilder> unknownSchemaNodesBuilder = childNode.getUnknownNodes();
         boolean refinedUnknownNodeLflstFound = false;
 
@@ -70,7 +72,7 @@ public class RefineTest {
                 refinedUnknownNodeLflstFound);
     }
 
-    private void findMustConstraint(ConstraintsBuilder conDef, String mustValue) {
+    private void findMustConstraint(final ConstraintsBuilder conDef, final String mustValue) {
         boolean mustLflstFound = false;
         for (MustDefinition mustDef : conDef.getMustDefinitions()) {
             if (mustDef.toString().equals(mustValue)) {
@@ -150,8 +152,8 @@ public class RefineTest {
         return moduleBuilder;
     }
 
-    private void checkAnyXmlRefineHolderAndSchemaNodeBuilder(String string, List<RefineHolder> refineHolders,
-            Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+    private void checkAnyXmlRefineHolderAndSchemaNodeBuilder(final String string, final List<RefineHolder> refineHolders,
+            final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
         RefineHolder refHolderData = getRefineHolder("data", refineHolders);
 
         QName qname = createQname();
@@ -171,13 +173,13 @@ public class RefineTest {
 
     }
 
-    private void checkChc2RefineHolderAndSchemaNodeBuilder(String nodeName, List<RefineHolder> refineHolders,
-            Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+    private void checkChc2RefineHolderAndSchemaNodeBuilder(final String nodeName, final List<RefineHolder> refineHolders,
+            final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
         RefineHolder refHolderChc2 = getRefineHolder("chc2", refineHolders);
 
         QName qname = createQname();
         List<QName> path = Lists.newArrayList(qname);
-        DataSchemaNodeBuilder builderChc2 = new ChoiceBuilder("module", 4, qname, new SchemaPath(path, true));
+        DataSchemaNodeBuilder builderChc2 = new ChoiceBuilder("module", 4, qname, SchemaPath.create(path, true));
         assertNotNull("Refine holder chc2 wasn't initialized.", refHolderChc2);
 
         RefineUtils.refineChoice((ChoiceBuilder) builderChc2, refHolderChc2);
@@ -187,13 +189,13 @@ public class RefineTest {
         assertFalse("'chc2' has incorrect value for 'mandatory'", conDefChc2.isMandatory());
     }
 
-    private void checkChcRefineHolderAndSchemaNodeBuilder(String nodeName, List<RefineHolder> refineHolders,
-            Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+    private void checkChcRefineHolderAndSchemaNodeBuilder(final String nodeName, final List<RefineHolder> refineHolders,
+            final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
         RefineHolder refHolderChc = getRefineHolder("chc", refineHolders);
 
         QName qname = createQname();
         List<QName> path = Lists.newArrayList(qname);
-        DataSchemaNodeBuilder builderChc = new ChoiceBuilder("module", 4, qname, new SchemaPath(path, true));
+        DataSchemaNodeBuilder builderChc = new ChoiceBuilder("module", 4, qname, SchemaPath.create(path, true));
 
         assertNotNull("Refine holder chc wasn't initialized.", refHolderChc);
         assertNotNull("Data schema node builder chc wasn't initialized.", builderChc);
@@ -210,8 +212,8 @@ public class RefineTest {
         findUnknownNode(choiceBuilder, unknownNodeChcValue, unknownNodeChcName);
     }
 
-    private void checkLflstRefineHolderAndSchemaNodeBuilder(String nodeName, List<RefineHolder> refineHolders,
-            Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+    private void checkLflstRefineHolderAndSchemaNodeBuilder(final String nodeName, final List<RefineHolder> refineHolders,
+            final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
         RefineHolder refHolderLflst = getRefineHolder(nodeName, refineHolders);
 
         QName qname = createQname();
@@ -243,7 +245,7 @@ public class RefineTest {
 
     }
 
-    private RefineHolder getRefineHolder(String refHolderName, List<RefineHolder> refineHolders) {
+    private RefineHolder getRefineHolder(final String refHolderName, final List<RefineHolder> refineHolders) {
         for (RefineHolder refineHolder : refineHolders) {
             if (refineHolder.getName().equals(refHolderName)) {
                 return refineHolder;
@@ -264,10 +266,10 @@ public class RefineTest {
         return qname;
     }
 
-    private SchemaPath createSchemaPath(QName qname) {
+    private SchemaPath createSchemaPath(final QName qname) {
         List<QName> qnames = new ArrayList<>();
         qnames.add(createQname());
-        return new SchemaPath(qnames, true);
+        return SchemaPath.create(qnames, true);
     }
 
 }
index 34d1760d8bc71def84a4eda235a06d9262c1315c..b420ed80d1289148fe2f3fb2df1acbc26a109d42 100644 (file)
@@ -14,12 +14,11 @@ import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
@@ -41,6 +40,8 @@ import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
 
+import com.google.common.base.Splitter;
+
 /**
  * Contains the methods for converting strings to valid JAVA language strings
  * (package names, class names, attribute names).
@@ -57,22 +58,11 @@ public final class BindingGeneratorUtil {
         }
 
         @Override
-        public void set(SimpleDateFormat value) {
+        public void set(final SimpleDateFormat value) {
             throw new UnsupportedOperationException();
         }
     };
 
-    /**
-     * Array of strings values which represents JAVA reserved words.
-     */
-    @Deprecated
-    private static final String[] SET_VALUES = new String[] { "abstract", "assert", "boolean", "break", "byte", "case",
-            "catch", "char", "class", "const", "continue", "default", "double", "do", "else", "enum", "extends",
-            "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int",
-            "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return",
-            "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient",
-            "true", "try", "void", "volatile", "while" };
-
     /**
      * Impossible to instantiate this class. All of the methods or attributes
      * are static.
@@ -81,10 +71,11 @@ public final class BindingGeneratorUtil {
     }
 
     /**
-     * Hash set of words which are reserved in JAVA language.
+     * Pre-compiled replacement pattern.
      */
-    @Deprecated
-    private static final Set<String> JAVA_RESERVED_WORDS = new HashSet<String>(Arrays.asList(SET_VALUES));
+    private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
+    private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
+    private static final Splitter DOT = Splitter.on('.');
 
     /**
      * Converts string <code>packageName</code> to valid JAVA package name.
@@ -97,26 +88,27 @@ public final class BindingGeneratorUtil {
      * @return package name which contains words separated by point.
      */
     private static String validateJavaPackage(final String packageName) {
-        if (packageName != null) {
-            final String[] packNameParts = packageName.toLowerCase().split("\\.");
-            if (packNameParts != null) {
-                final StringBuilder builder = new StringBuilder();
-                for (int i = 0; i < packNameParts.length; ++i) {
-                    final String packNamePart = packNameParts[i];
-                    if (Character.isDigit(packNamePart.charAt(0))) {
-                        packNameParts[i] = "_" + packNamePart;
-                    } else if (JAVA_RESERVED_WORDS.contains(packNamePart)) {
-                        packNameParts[i] = "_" + packNamePart;
-                    }
-                    if (i > 0) {
-                        builder.append(".");
-                    }
-                    builder.append(packNameParts[i]);
-                }
-                return builder.toString();
+        if (packageName == null) {
+            return null;
+        }
+
+        final StringBuilder builder = new StringBuilder();
+        boolean first = true;
+
+        for (String p : DOT.split(packageName.toLowerCase())) {
+            if (first) {
+                first = false;
+            } else {
+                builder.append('.');
+            }
+
+            if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
+                builder.append('_');
             }
+            builder.append(p);
         }
-        return packageName;
+
+        return builder.toString();
     }
 
     /**
@@ -130,7 +122,7 @@ public final class BindingGeneratorUtil {
      * @return string with the admissible parameter name
      */
     public static String resolveJavaReservedWordEquivalency(final String parameterName) {
-        if (parameterName != null && JAVA_RESERVED_WORDS.contains(parameterName)) {
+        if (parameterName != null && BindingMapping.JAVA_RESERVED_WORDS.contains(parameterName)) {
             return "_" + parameterName;
         }
         return parameterName;
@@ -161,26 +153,32 @@ public final class BindingGeneratorUtil {
         if (module.getRevision() == null) {
             throw new IllegalArgumentException("Module " + module.getName() + " does not specify revision date!");
         }
-        packageNameBuilder.append("org.opendaylight.yang.gen.v");
-        packageNameBuilder.append(module.getYangVersion());
-        packageNameBuilder.append(".");
+        packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
+        packageNameBuilder.append('.');
 
         String namespace = module.getNamespace().toString();
-        namespace = namespace.replace("://", ".");
-        namespace = namespace.replace("/", ".");
-        namespace = namespace.replace(":", ".");
-        namespace = namespace.replace("-", ".");
-        namespace = namespace.replace("@", ".");
-        namespace = namespace.replace("$", ".");
-        namespace = namespace.replace("#", ".");
-        namespace = namespace.replace("'", ".");
-        namespace = namespace.replace("*", ".");
-        namespace = namespace.replace("+", ".");
-        namespace = namespace.replace(",", ".");
-        namespace = namespace.replace(";", ".");
-        namespace = namespace.replace("=", ".");
-
-        packageNameBuilder.append(namespace);
+        namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
+
+        final char[] chars = namespace.toCharArray();
+        for (int i = 0; i < chars.length; ++i) {
+            switch (chars[i]) {
+            case '/':
+            case ':':
+            case '-':
+            case '@':
+            case '$':
+            case '#':
+            case '\'':
+            case '*':
+            case '+':
+            case ',':
+            case ';':
+            case '=':
+                chars[i] = '.';
+            }
+        }
+
+        packageNameBuilder.append(chars);
         packageNameBuilder.append(".rev");
         packageNameBuilder.append(DATE_FORMAT.get().format(module.getRevision()));
 
@@ -207,7 +205,7 @@ public final class BindingGeneratorUtil {
      * @return string with valid JAVA package name
      */
     public static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath,
-            boolean isUsesAugment) {
+            final boolean isUsesAugment) {
         if (basePackageName == null) {
             throw new IllegalArgumentException("Base Package Name cannot be NULL!");
         }
@@ -225,11 +223,11 @@ public final class BindingGeneratorUtil {
             traversalSteps = (pathToNode.size() - 1);
         }
         for (int i = 0; i < traversalSteps; ++i) {
-            builder.append(".");
+            builder.append('.');
             String nodeLocalName = pathToNode.get(i).getLocalName();
 
-            nodeLocalName = nodeLocalName.replace(":", ".");
-            nodeLocalName = nodeLocalName.replace("-", ".");
+            nodeLocalName = nodeLocalName.replace(':', '.');
+            nodeLocalName = nodeLocalName.replace('-', '.');
             builder.append(nodeLocalName);
         }
         return validateJavaPackage(builder.toString());
@@ -277,7 +275,7 @@ public final class BindingGeneratorUtil {
      * @deprecated Use {@link BindingMapping#getClassName(QName)} instead.
      */
     @Deprecated
-    public static String parseToClassName(String token) {
+    public static String parseToClassName(final String token) {
         return parseToCamelCase(token, true);
     }
 
@@ -328,19 +326,14 @@ public final class BindingGeneratorUtil {
         correctStr = replaceWithCamelCase(correctStr, '-');
         correctStr = replaceWithCamelCase(correctStr, '_');
 
-        String firstChar = correctStr.substring(0, 1);
-        if (uppercase) {
-            firstChar = firstChar.toUpperCase();
-        } else {
-            firstChar = firstChar.toLowerCase();
-        }
+        char firstChar = correctStr.charAt(0);
+        firstChar = uppercase ? Character.toUpperCase(firstChar) : Character.toLowerCase(firstChar);
 
-        if (firstChar.matches("[0-9]")) {
-            correctStr = "_" + correctStr;
+        if (firstChar >= '0' && firstChar <= '9') {
+            return correctStr = '_' + correctStr;
         } else {
-            correctStr = firstChar + correctStr.substring(1);
+            return correctStr = firstChar + correctStr.substring(1);
         }
-        return correctStr;
     }
 
     /**
@@ -357,7 +350,7 @@ public final class BindingGeneratorUtil {
      * @throws IllegalArgumentException
      *             if the length of the returning string has length 0
      */
-    private static String replaceWithCamelCase(String text, char removalChar) {
+    private static String replaceWithCamelCase(final String text, final char removalChar) {
         StringBuilder sb = new StringBuilder(text);
         String toBeRemoved = String.valueOf(removalChar);
 
@@ -376,7 +369,7 @@ public final class BindingGeneratorUtil {
         return sb.toString();
     }
 
-    public static long computeDefaultSUID(GeneratedTOBuilderImpl to) {
+    public static long computeDefaultSUID(final GeneratedTOBuilderImpl to) {
         try {
             ByteArrayOutputStream bout = new ByteArrayOutputStream();
             DataOutputStream dout = new DataOutputStream(bout);
@@ -387,7 +380,7 @@ public final class BindingGeneratorUtil {
             List<Type> impl = to.getImplementsTypes();
             Collections.sort(impl, new Comparator<Type>() {
                 @Override
-                public int compare(Type o1, Type o2) {
+                public int compare(final Type o1, final Type o2) {
                     return o1.getFullyQualifiedName().compareTo(o2.getFullyQualifiedName());
                 }
             });
@@ -397,7 +390,7 @@ public final class BindingGeneratorUtil {
 
             Comparator<TypeMemberBuilder<?>> comparator = new Comparator<TypeMemberBuilder<?>>() {
                 @Override
-                public int compare(TypeMemberBuilder<?> o1, TypeMemberBuilder<?> o2) {
+                public int compare(final TypeMemberBuilder<?> o1, final TypeMemberBuilder<?> o2) {
                     return o1.getName().compareTo(o2.getName());
                 }
             };
@@ -433,7 +426,7 @@ public final class BindingGeneratorUtil {
         }
     }
 
-    public static Restrictions getRestrictions(TypeDefinition<?> type) {
+    public static Restrictions getRestrictions(final TypeDefinition<?> type) {
         final List<LengthConstraint> length = new ArrayList<>();
         final List<PatternConstraint> pattern = new ArrayList<>();
         final List<RangeConstraint> range = new ArrayList<>();
diff --git a/common/checkstyle-logging/pom.xml b/common/checkstyle-logging/pom.xml
new file mode 100644 (file)
index 0000000..775c15a
--- /dev/null
@@ -0,0 +1,26 @@
+<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>common-parent</artifactId>
+    <version>0.6.2-SNAPSHOT</version>
+  </parent>
+  <artifactId>checkstyle-logging</artifactId>
+
+  <dependencies>
+    <dependency>
+      <groupId>com.puppycrawl.tools</groupId>
+      <artifactId>checkstyle</artifactId>
+      <version>5.6</version>
+    </dependency>
+    <dependency>
+        <groupId>org.slf4j</groupId>
+        <artifactId>slf4j-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+</project>
\ No newline at end of file
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/CheckLoggingUtil.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/CheckLoggingUtil.java
new file mode 100644 (file)
index 0000000..37d203c
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * 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.checkstyle;
+
+import java.util.List;
+
+import org.slf4j.Logger;
+
+import com.google.common.collect.Lists;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.FullIdent;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
+
+public class CheckLoggingUtil {
+
+    public static final String LOGGER_TYPE_NAME = Logger.class.getSimpleName();
+    public static final String LOGGER_TYPE_FULL_NAME = Logger.class.getName();
+    public static final String LOGGER_VAR_NAME = "LOG";
+    private static final List<String> LOG_METHODS = Lists.newArrayList("debug", "info", "error", "warn", "trace");
+
+    private CheckLoggingUtil() {}
+
+    public static String getTypeName(final DetailAST aAST) {
+        final FullIdent ident = CheckUtils.createFullType(aAST.findFirstToken(TokenTypes.TYPE));
+        return ident.getText();
+    }
+
+    public static boolean isLoggerType(final DetailAST aAST) {
+        final String typeName = getTypeName(aAST);
+        if(typeName.equals(LOGGER_TYPE_FULL_NAME) || typeName.equals(LOGGER_TYPE_NAME)) {
+            return true;
+        }
+        return false;
+    }
+
+    public static String getVariableName(final DetailAST aAST) {
+        DetailAST identifier = aAST.findFirstToken(TokenTypes.IDENT);
+        return identifier.getText();
+    }
+
+    public static boolean itsAFieldVariable(final DetailAST aAST) {
+        return aAST.getParent().getType() == TokenTypes.OBJBLOCK;
+    }
+
+    public static String getMethodName(final DetailAST aAST) {
+        if(aAST.getFirstChild().getLastChild() != null) {
+            return aAST.getFirstChild().getLastChild().getText();
+        }
+        return aAST.getFirstChild().getText();
+    }
+
+    public static boolean isLogMethod(final String methodName) {
+        return LOG_METHODS.contains(methodName);
+    }
+
+}
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LogMessageConcatenationCheck.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LogMessageConcatenationCheck.java
new file mode 100644 (file)
index 0000000..d725c45
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * 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.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LogMessageConcatenationCheck extends Check {
+
+    private static final String LOG_MESSAGE = "Log message contains string concatenation.";
+
+    @Override
+    public int[] getDefaultTokens() {
+        return new int[]{TokenTypes.METHOD_CALL};
+    }
+
+    @Override
+    public void visitToken(DetailAST aAST) {
+        final String methodName = CheckLoggingUtil.getMethodName(aAST);
+        if(CheckLoggingUtil.isLogMethod(methodName)) {
+            final String logMessage = aAST.findFirstToken(TokenTypes.ELIST).getFirstChild().getFirstChild().getText();
+            if(logMessage.contains("+")) {
+                log(aAST.getLineNo(), LOG_MESSAGE);
+            }
+        }
+    }
+}
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LogMessagePlaceholderCountCheck.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LogMessagePlaceholderCountCheck.java
new file mode 100644 (file)
index 0000000..bb28bcc
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * 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.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LogMessagePlaceholderCountCheck extends Check {
+
+    private static final String LOG_MESSAGE = "Log message placeholders count is incorrect.";
+    private static final String PLACEHOLDER = "{}";
+    private static final String EXCEPTION_TYPE = "Exception";
+
+    @Override
+    public int[] getDefaultTokens() {
+        return new int[]{TokenTypes.METHOD_CALL};
+    }
+
+    @Override
+    public void visitToken(DetailAST aAST) {
+        final String methodName = CheckLoggingUtil.getMethodName(aAST);
+        if(CheckLoggingUtil.isLogMethod(methodName)) {
+            final String logMessage = aAST.findFirstToken(TokenTypes.ELIST).getFirstChild().getFirstChild().getText();
+            int placeholdersCount = placeholdersCount(logMessage);
+            int argumentsCount = aAST.findFirstToken(TokenTypes.ELIST).getChildCount(TokenTypes.EXPR) - 1;
+            final String lastArg = aAST.findFirstToken(TokenTypes.ELIST).getLastChild().getFirstChild().getText();
+            if(hasCatchBlockParentWithArgument(lastArg, aAST) || hasMethodDefinitionWithExceptionArgument(lastArg, aAST)) {
+                argumentsCount--;
+            }
+            if(placeholdersCount > argumentsCount) {
+                log(aAST.getLineNo(), LOG_MESSAGE);
+            }
+        }
+    }
+
+    private int placeholdersCount(final String message) {
+        return (message.length() - message.replace(PLACEHOLDER, "").length()) / PLACEHOLDER.length();
+    }
+
+    private boolean hasCatchBlockParentWithArgument(final String argumentName, final DetailAST aAST) {
+        DetailAST parent = aAST.getParent();
+        while(parent != null && parent.getType() != TokenTypes.LITERAL_CATCH) {
+            parent = parent.getParent();
+        }
+        if(parent != null) {
+            if(parent.findFirstToken(TokenTypes.PARAMETER_DEF) != null &&
+                    parent.findFirstToken(TokenTypes.PARAMETER_DEF).findFirstToken(TokenTypes.IDENT).getText().equals(argumentName)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private boolean hasMethodDefinitionWithExceptionArgument(final String argumentName, final DetailAST aAST) {
+        DetailAST parent = aAST.getParent();
+        while(parent != null && parent.getType() != TokenTypes.METHOD_DEF) {
+            parent = parent.getParent();
+        }
+        if(parent != null) {
+            if(parent.findFirstToken(TokenTypes.PARAMETERS).findFirstToken(TokenTypes.PARAMETER_DEF) != null) {
+                DetailAST paramDef = parent.findFirstToken(TokenTypes.PARAMETERS).getFirstChild();
+                while(paramDef != null) {
+                    if(paramDef.getType() == TokenTypes.PARAMETER_DEF) {
+                        final String paramName = paramDef.findFirstToken(TokenTypes.IDENT).getText();
+                        if(paramName.equals(argumentName) && isExceptionType(paramDef)) {
+                            return true;
+                        }
+                    }
+                    paramDef = paramDef.getNextSibling();
+                }
+            }
+        }
+        return false;
+    }
+
+    private boolean isExceptionType(final DetailAST parameterDef) {
+        if(parameterDef != null) {
+            final DetailAST type = parameterDef.findFirstToken(TokenTypes.TYPE);
+            if(type != null && type.findFirstToken(TokenTypes.IDENT) != null) {
+                final String argumentType = type.findFirstToken(TokenTypes.IDENT).getText();
+                if(argumentType.contains(EXCEPTION_TYPE)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+}
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerFactoryClassParameterCheck.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerFactoryClassParameterCheck.java
new file mode 100644 (file)
index 0000000..5975b8e
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerFactoryClassParameterCheck extends Check {
+
+    private static final String LOG_MESSAGE = "LoggerFactory.getLogger Class argument is incorrect.";
+    private static final String METHOD_NAME = "getLogger";
+
+    @Override
+    public int[] getDefaultTokens() {
+        return new int[]{TokenTypes.METHOD_CALL};
+    }
+
+    @Override
+    public void visitToken(DetailAST aAST) {
+        final String methodName = CheckLoggingUtil.getMethodName(aAST);
+        if(methodName.equals(METHOD_NAME)) {
+            final String className = getClassName(aAST);
+            final String parameter = aAST.findFirstToken(TokenTypes.ELIST).getFirstChild().getFirstChild().getFirstChild().getText();
+            if(!parameter.equals(className)) {
+                log(aAST.getLineNo(), LOG_MESSAGE);
+            }
+        }
+    }
+
+    private String getClassName(final DetailAST aAST) {
+        DetailAST parent = aAST.getParent();
+        while(parent.getType() != TokenTypes.CLASS_DEF && parent.getType() != TokenTypes.ENUM_DEF) {
+            parent = parent.getParent();
+        }
+        return parent.findFirstToken(TokenTypes.IDENT).getText();
+    }
+
+}
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerMustBeSlf4jCheck.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerMustBeSlf4jCheck.java
new file mode 100644 (file)
index 0000000..2871403
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * 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.checkstyle;
+
+import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_TYPE_FULL_NAME;
+import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_TYPE_NAME;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerMustBeSlf4jCheck extends Check {
+
+    private static final String LOG_MESSAGE = "Logger must be slf4j.";
+    private static final String SLF4J = "slf4j";
+
+    @Override
+    public int[] getDefaultTokens() {
+        return new int[]{TokenTypes.VARIABLE_DEF, TokenTypes.IMPORT};
+    }
+
+    @Override
+    public void visitToken(DetailAST aAST) {
+        if(aAST.getType() == TokenTypes.VARIABLE_DEF) {
+            final String typeName = CheckLoggingUtil.getTypeName(aAST);
+            if (CheckLoggingUtil.itsAFieldVariable(aAST) && typeName.contains("." + LOGGER_TYPE_NAME)) {
+                if(!typeName.equals(LOGGER_TYPE_FULL_NAME)) {
+                    log(aAST.getLineNo(), LOG_MESSAGE);
+                }
+            }
+        } else if(aAST.getType() == TokenTypes.IMPORT) {
+            final String importType = aAST.getFirstChild().findFirstToken(TokenTypes.IDENT).getText();
+            if(importType.equals(CheckLoggingUtil.LOGGER_TYPE_NAME)) {
+               final String importIdent = aAST.getFirstChild().getFirstChild().getLastChild().getText();
+                if(!importIdent.equals(SLF4J)) {
+                   log(aAST.getLineNo(), LOG_MESSAGE);
+               }
+            }
+        }
+    }
+}
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerVariableModifiersCheck.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerVariableModifiersCheck.java
new file mode 100644 (file)
index 0000000..e3ef112
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * 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.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerVariableModifiersCheck extends Check {
+
+    private static final String LOG_MESSAGE = "Logger must be declared as private static final.";
+
+    @Override
+    public int[] getDefaultTokens() {
+        return new int[]{TokenTypes.VARIABLE_DEF};
+    }
+
+    @Override
+    public void visitToken(DetailAST aAST) {
+        if (CheckLoggingUtil.itsAFieldVariable(aAST) && CheckLoggingUtil.isLoggerType(aAST) && !hasPrivatStaticFinalModifier(aAST)) {
+            log(aAST.getLineNo(), LOG_MESSAGE);
+        }
+    }
+
+    private boolean hasPrivatStaticFinalModifier(DetailAST aAST) {
+        DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS);
+        if(modifiers != null) {
+            if(modifiers.branchContains(TokenTypes.LITERAL_PRIVATE) && modifiers.branchContains(TokenTypes.LITERAL_STATIC)
+                    && modifiers.branchContains(TokenTypes.FINAL)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+}
diff --git a/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerVariableNameCheck.java b/common/checkstyle-logging/src/main/java/org/opendaylight/yangtools/checkstyle/LoggerVariableNameCheck.java
new file mode 100644 (file)
index 0000000..7569f14
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * 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.checkstyle;
+
+import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_VAR_NAME;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerVariableNameCheck extends Check {
+
+    private static final String LOG_MESSAGE = "Logger name should be LOG.";
+
+    @Override
+    public int[] getDefaultTokens() {
+        return new int[]{TokenTypes.VARIABLE_DEF};
+    }
+
+    @Override
+    public void visitToken(DetailAST aAST) {
+        final String variableName = CheckLoggingUtil.getVariableName(aAST);
+        if (CheckLoggingUtil.itsAFieldVariable(aAST) && CheckLoggingUtil.isLoggerType(aAST) && !variableName.equals(LOGGER_VAR_NAME)) {
+            log(aAST.getLineNo(), LOG_MESSAGE);
+        }
+    }
+
+}
diff --git a/common/checkstyle-logging/src/main/resources/checkstyle-logging.xml b/common/checkstyle-logging/src/main/resources/checkstyle-logging.xml
new file mode 100644 (file)
index 0000000..6d7bc62
--- /dev/null
@@ -0,0 +1,48 @@
+<?xml version="1.0"?>
+<!DOCTYPE module PUBLIC
+    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
+    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
+
+<module name="Checker">
+
+    <module name="RegexpMultiline">
+        <property name="format" value="System\.(out)|(err)\.print(ln)?\("/>
+        <property name="message" value="Line contains console output."/>
+    </module>
+
+    <module name="RegexpMultiline">
+        <property name="format" value="\.printStackTrace?\("/>
+        <property name="message" value="Line contains printStacktrace()."/>
+    </module>
+
+    <module name="TreeWalker">
+        <module name="org.opendaylight.yangtools.checkstyle.LoggerVariableNameCheck" />
+    </module>
+
+    <module name="TreeWalker">
+      <module name="org.opendaylight.yangtools.checkstyle.LoggerVariableModifiersCheck" />
+    </module>
+
+     <module name="TreeWalker">
+      <module name="org.opendaylight.yangtools.checkstyle.LoggerMustBeSlf4jCheck" />
+    </module>
+
+    <module name="TreeWalker">
+      <module name="org.opendaylight.yangtools.checkstyle.LoggerFactoryClassParameterCheck" />
+    </module>
+
+   <module name="TreeWalker">
+      <module name="org.opendaylight.yangtools.checkstyle.LogMessageConcatenationCheck" />
+    </module>
+
+    <module name="TreeWalker">
+      <module name="org.opendaylight.yangtools.checkstyle.LogMessagePlaceholderCountCheck" />
+    </module>
+
+    <module name="RegexpSingleline">
+        <property name="format" value="(\.|\b)Logger "/>
+        <property name="message" value="Logger might be declared only once."/>
+        <property name="minimum" value="0"/>
+        <property name="maximum" value="1"/>
+    </module>
+</module>
\ No newline at end of file
diff --git a/common/checkstyle-logging/src/test/java/org/opendaylight/yangtools/checkstyle/CheckLoggingTestClass.java b/common/checkstyle-logging/src/test/java/org/opendaylight/yangtools/checkstyle/CheckLoggingTestClass.java
new file mode 100644 (file)
index 0000000..6a2b170
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * 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.checkstyle;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CheckLoggingTestClass {
+    final Logger logger = LoggerFactory.getLogger(CheckstyleTest.class);
+    private static final java.util.logging.Logger LOG2 = java.util.logging.Logger.getGlobal();
+    private static final Logger LOG = LoggerFactory.getLogger(CheckLoggingTestClass.class);
+    public void foo() {
+        try {
+            logger.debug("foo + bar {}", "foo");
+        } catch(Exception e) {
+            e.printStackTrace();
+            System.out.println(e.getMessage());
+            System.err.print(e.getMessage());
+            logger.debug("foo {}", "bar", e);
+            LOG.info("foo {} {}", e.getMessage(), e);
+        }
+    }
+
+    public void bar(String string, IllegalArgumentException e) {
+        LOG.warn("foo", e);
+        LOG.warn("foo {}", e);
+        LOG.warn("foo", string);
+        LOG.warn("foo {}", string);
+        LOG.warn("foo {}", string, e);
+    }
+}
\ No newline at end of file
diff --git a/common/checkstyle-logging/src/test/java/org/opendaylight/yangtools/checkstyle/CheckstyleTest.java b/common/checkstyle-logging/src/test/java/org/opendaylight/yangtools/checkstyle/CheckstyleTest.java
new file mode 100644 (file)
index 0000000..a12daf9
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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.checkstyle;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.xml.sax.InputSource;
+
+import com.google.common.collect.Lists;
+import com.puppycrawl.tools.checkstyle.Checker;
+import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
+import com.puppycrawl.tools.checkstyle.DefaultLogger;
+import com.puppycrawl.tools.checkstyle.PropertiesExpander;
+import com.puppycrawl.tools.checkstyle.api.AuditListener;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
+import com.puppycrawl.tools.checkstyle.api.Configuration;
+
+public class CheckstyleTest {
+
+    private Checker checker;
+    private ByteArrayOutputStream baos;
+
+    @Before
+    public void setup() throws CheckstyleException {
+        baos = new ByteArrayOutputStream();
+        AuditListener listener = new DefaultLogger(baos, false);
+
+        InputSource inputSource = new InputSource(CheckstyleTest.class.getClassLoader().getResourceAsStream(
+                "checkstyle-logging.xml"));
+        Configuration configuration = ConfigurationLoader.loadConfiguration(inputSource,
+                new PropertiesExpander(System.getProperties()), false);
+
+        checker = new Checker();
+        checker.setModuleClassLoader(Checker.class.getClassLoader());
+        checker.configure(configuration);
+        checker.addListener(listener);
+    }
+
+    @After
+    public void destroy() {
+        checker.destroy();
+    }
+
+    @Test
+    public void testLoggerChecks() throws Exception {
+        verify(CheckLoggingTestClass.class, "15: Logger must be declared as private static final.", "15: Logger name should be LOG.",
+                "16: Logger might be declared only once.", "16: Logger must be slf4j.", "22: Line contains printStacktrace", 
+                "23: Line contains console output", "24: Line contains console output",
+                "15: LoggerFactory.getLogger Class argument is incorrect.", "20: Log message contains string concatenation.",
+                "26: Log message placeholders count is incorrect.", "32: Log message placeholders count is incorrect");
+    }
+
+    private void verify(final Class<?> testClass, final String... expectedMessages) {
+        final String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + testClass.getName().replaceAll("\\.", "/") + ".java";
+        final File testFile = new File(filePath);
+        checker.process(Lists.newArrayList(testFile));
+        final String output = baos.toString();
+        for(final String message : expectedMessages) {
+            assertTrue("Expected message not found: " + message, output.contains(message));
+        }
+    }
+}
index 6c9162810a45a33876cc1e427e69a72d70fab086..cfaf16e46c117908001352ead8f76481a0334404 100644 (file)
     <packaging>pom</packaging>
 
     <modules>
+        <module>checkstyle-logging</module>
         <module>concepts</module>
         <module>feature</module>
         <module>mockito-configuration</module>
         <module>object-cache-api</module>
         <module>object-cache-guava</module>
         <module>object-cache-noop</module>
+        <module>util</module>
     </modules>
 
     <dependencyManagement>
diff --git a/common/util/pom.xml b/common/util/pom.xml
new file mode 100644 (file)
index 0000000..146b009
--- /dev/null
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
+<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">
+
+    <parent>
+        <groupId>org.opendaylight.yangtools</groupId>
+        <artifactId>common-parent</artifactId>
+        <version>0.6.2-SNAPSHOT</version>
+    </parent>
+    <packaging>bundle</packaging>
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>util</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.github.romix</groupId>
+            <artifactId>java-concurrent-hash-trie-map</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Export-Package>org.opendaylight.yangtools.util</Export-Package>
+                        <Embed-Dependency>java-concurrent-hash-trie-map;inline=true</Embed-Dependency>
+                    </instructions>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/common/util/src/main/java/org/opendaylight/yangtools/util/MapAdaptor.java b/common/util/src/main/java/org/opendaylight/yangtools/util/MapAdaptor.java
new file mode 100644 (file)
index 0000000..2ef038b
--- /dev/null
@@ -0,0 +1,182 @@
+/*
+ * 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.util;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import com.romix.scala.collection.concurrent.TrieMap;
+
+/*
+ * A simple layer on top of maps, which performs snapshot mediation and optimization of
+ * what the underlying implementation is.
+ */
+public final class MapAdaptor {
+    public static final int DEFAULT_COPY_MAX_ITEMS = 100;
+    public static final String COPY_MAX_ITEMS_MAX_PROP = "org.opendaylight.yangtools.util.mapadaptor.maxcopy";
+
+    public static final int DEFAULT_PERSIST_MIN_ITEMS = 50;
+    public static final String PERSIST_MIN_ITEMS_PROP = "org.opendaylight.yangtools.util.mapadaptor.minpersist";
+
+    private static final Logger LOG = LoggerFactory.getLogger(MapAdaptor.class);
+    private static final MapAdaptor DEFAULT_INSTANCE;
+
+    private final boolean useSingleton;
+    private final int persistMinItems;
+    private final int copyMaxItems;
+
+    static {
+        DEFAULT_INSTANCE = new MapAdaptor(true,
+                getProperty(COPY_MAX_ITEMS_MAX_PROP, DEFAULT_COPY_MAX_ITEMS),
+                getProperty(PERSIST_MIN_ITEMS_PROP, DEFAULT_PERSIST_MIN_ITEMS));
+        LOG.debug("Configured HashMap/TrieMap cutoff at {}/{} entries",
+                DEFAULT_INSTANCE.persistMinItems, DEFAULT_INSTANCE.copyMaxItems);
+    }
+
+    private static final int getProperty(final String name, final int defaultValue) {
+        try {
+            final String p = System.getProperty(name);
+            if (p != null) {
+                try {
+                    int pi = Integer.valueOf(p);
+                    if (pi <= 0) {
+                        LOG.warn("Ignoring illegal value of {}: has to be a positive number", name);
+                    } else {
+                        return pi;
+                    }
+                } catch (NumberFormatException e) {
+                    LOG.warn("Ignoring non-numerical value of {}", name, e);
+                }
+            }
+        } catch (Exception e) {
+            LOG.debug("Failed to get {}", name, e);
+        }
+        return defaultValue;
+    }
+
+    private MapAdaptor(final boolean useSingleton, final int copyMaxItems, final int persistMinItems) {
+        this.useSingleton = useSingleton;
+        this.copyMaxItems = copyMaxItems;
+        this.persistMinItems = persistMinItems;
+    }
+
+    /**
+     * Return the default-configured instance.
+     *
+     * @return the singleton global instance
+     */
+    public static MapAdaptor getDefaultInstance() {
+        return DEFAULT_INSTANCE;
+    }
+
+    public static MapAdaptor getInstance(final boolean useSingleton, final int copyMaxItems, final int persistMinItems) {
+        Preconditions.checkArgument(copyMaxItems >= 0, "copyMaxItems has to be a non-negative integer");
+        Preconditions.checkArgument(persistMinItems >= 0, "persistMinItems has to be a positive integer");
+        Preconditions.checkArgument(persistMinItems <= copyMaxItems, "persistMinItems must be less than or equal to copyMaxItems");
+        return new MapAdaptor(useSingleton, copyMaxItems, persistMinItems);
+    }
+
+    /**
+     * Input is treated is supposed to be left unmodified, result must be mutable.
+     *
+     * @param input
+     * @return
+     */
+    public <K, V> Map<K, V> takeSnapshot(final Map<K, V> input) {
+        if (input instanceof ReadOnlyTrieMap) {
+            return ((ReadOnlyTrieMap<K, V>)input).toReadWrite();
+        }
+
+        LOG.trace("Converting input {} to a HashMap", input);
+
+        // FIXME: be a bit smart about allocation based on observed size
+
+        final Map<K, V> ret = new HashMap<>(input);
+        LOG.trace("Read-write HashMap is {}", ret);
+        return ret;
+    }
+
+    /**
+     * Input will be thrown away, result will be retained for read-only access or
+     * {@link #takeSnapshot(Map)} purposes.
+     *
+     * @param input
+     * @return
+     */
+    public <K, V> Map<K, V> optimize(final Map<K, V> input) {
+        if (input instanceof ReadOnlyTrieMap) {
+            LOG.warn("Optimizing read-only map {}", input);
+        }
+
+        final int size = input.size();
+
+        /*
+         * No-brainer :)
+         */
+        if (size == 0) {
+            LOG.trace("Reducing input {} to an empty map", input);
+            return Collections.<K, V>emptyMap();
+        }
+
+        /*
+         * We retain the persistent map as long as it holds at least
+         * persistMinItems
+         */
+        if (input instanceof ReadWriteTrieMap && size >= persistMinItems) {
+            return ((ReadWriteTrieMap<K, V>)input).toReadOnly();
+        }
+
+        /*
+         * If the user opted to use singleton maps, use them. Except for the case
+         * when persistMinItems dictates we should not move off of the persistent
+         * map.
+         */
+        if (useSingleton && size == 1) {
+            final Entry<K, V> e = Iterables.getOnlyElement(input.entrySet());
+            final Map<K, V> ret = Collections.singletonMap(e.getKey(), e.getValue());
+            LOG.trace("Reducing input () to singleton map {}", input, ret);
+            return ret;
+        }
+
+        if (size <= copyMaxItems) {
+            /*
+             * Favor access speed: use a HashMap and copy it on modification.
+             */
+            if (input instanceof HashMap) {
+                return input;
+            }
+
+            LOG.trace("Copying input {} to a HashMap ({} entries)", input, size);
+            final Map<K, V> ret = new HashMap<>(input);
+            LOG.trace("Read-only HashMap is {}", ret);
+            return ret;
+        }
+
+        /*
+         * Favor isolation speed: use a TrieMap and perform snapshots
+         *
+         * This one is a bit tricky, as the TrieMap is concurrent and does not
+         * keep an uptodate size. Updating it requires a full walk -- which is
+         * O(N) and we want to avoid that. So we wrap it in an interceptor,
+         * which will maintain the size for us.
+         */
+        LOG.trace("Copying input {} to a TrieMap ({} entries)", input, size);
+        final TrieMap<K, V> map = TrieMap.empty();
+        map.putAll(input);
+        final Map<K, V> ret = new ReadOnlyTrieMap<>(map, size);
+        LOG.trace("Read-only TrieMap is {}", ret);
+        return ret;
+    }
+}
diff --git a/common/util/src/main/java/org/opendaylight/yangtools/util/ReadOnlyTrieMap.java b/common/util/src/main/java/org/opendaylight/yangtools/util/ReadOnlyTrieMap.java
new file mode 100644 (file)
index 0000000..88da121
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * 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.util;
+
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ForwardingMap;
+import com.romix.scala.collection.concurrent.TrieMap;
+
+/**
+ * A read-only facade in front of a TrieMap. This is what we give out from
+ * MapAdaptor.optimize(). The idea is that we want our read-only users to
+ * share a single snapshot. That snapshot is instantiated lazily either on
+ * first access. Since we never leak the TrieMap and track its size as it
+ * changes, we can cache it for future reference.
+ */
+final class ReadOnlyTrieMap<K, V> extends ForwardingMap<K, V> {
+    private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
+    private final TrieMap<K, V> readWrite;
+    private final int size;
+    private TrieMap<K, V> readOnly;
+
+    ReadOnlyTrieMap(final TrieMap<K, V> map, final int size) {
+        super();
+        this.readWrite = Preconditions.checkNotNull(map);
+        this.size = size;
+    }
+
+    Map<K, V> toReadWrite() {
+        final Map<K, V> ret = new ReadWriteTrieMap<>(readWrite.snapshot(), size);
+        LOG.trace("Converted read-only TrieMap {} to read-write {}", this, ret);
+        return ret;
+    }
+
+    @Override
+    protected Map<K, V> delegate() {
+        if (readOnly == null) {
+            synchronized (this) {
+                if (readOnly == null) {
+                    readOnly = readWrite.readOnlySnapshot();
+                }
+            }
+        }
+
+        return readOnly;
+    }
+
+    @Override
+    public int size() {
+        return size;
+    }
+}
diff --git a/common/util/src/main/java/org/opendaylight/yangtools/util/ReadWriteTrieMap.java b/common/util/src/main/java/org/opendaylight/yangtools/util/ReadWriteTrieMap.java
new file mode 100644 (file)
index 0000000..039e734
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * 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.util;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.romix.scala.collection.concurrent.TrieMap;
+
+/**
+ * A TrieMap facade tracking modifications. Since we change structures based on
+ * their size, and determining the size of a TrieMap is expensive, we make sure
+ * to update it as we go.
+ *
+ * FIXME: this map does not support modification view the keySet()/values()/entrySet()
+ *        methods.
+ *
+ * @param <K> Key type
+ * @param <V> Value type
+ */
+final class ReadWriteTrieMap<K, V> implements Map<K, V> {
+    private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
+    private final TrieMap<K, V> delegate;
+    private int size;
+
+    ReadWriteTrieMap(final TrieMap<K, V> delegate, final int size) {
+        this.delegate = Preconditions.checkNotNull(delegate);
+        this.size = size;
+    }
+
+    Map<K, V> toReadOnly() {
+        final Map<K, V> ret = new ReadOnlyTrieMap<>(delegate, size);
+        LOG.trace("Converted read-write TrieMap {} to read-only {}", this, ret);
+        return ret;
+    }
+
+    @Override
+    public int size() {
+        return size;
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return size == 0;
+    }
+
+    @Override
+    public boolean containsKey(final Object key) {
+        return delegate.containsKey(key);
+    }
+
+    @Override
+    public boolean containsValue(final Object value) {
+        return delegate.containsValue(value);
+    }
+
+    @Override
+    public V get(final Object key) {
+        return delegate.get(key);
+    }
+
+    @Override
+    public V put(final K key, final V value) {
+        final V ret = delegate.put(key, value);
+        if (ret == null) {
+            size++;
+        }
+        return ret;
+    }
+
+    @Override
+    public V remove(final Object key) {
+        final V ret = delegate.remove(key);
+        if (ret != null) {
+            size--;
+        }
+        return ret;
+    }
+
+    @Override
+    public void putAll(final Map<? extends K, ? extends V> m) {
+        for (Entry<? extends K, ? extends V> e : m.entrySet()) {
+            put(e.getKey(), e.getValue());
+        }
+    }
+
+    @Override
+    public void clear() {
+        delegate.clear();
+        size = 0;
+    }
+
+    @Override
+    public Set<K> keySet() {
+        return Collections.unmodifiableSet(delegate.keySet());
+    }
+
+    @Override
+    public Collection<V> values() {
+        return Collections.unmodifiableCollection(delegate.values());
+    }
+
+    @Override
+    public Set<Entry<K, V>> entrySet() {
+        return Collections.unmodifiableSet(delegate.entrySet());
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        return delegate.equals(o);
+    }
+
+    @Override
+    public int hashCode() {
+        return delegate.hashCode();
+    }
+}
diff --git a/common/util/src/test/java/org/opendaylight/yangtools/util/MapAdaptorTest.java b/common/util/src/test/java/org/opendaylight/yangtools/util/MapAdaptorTest.java
new file mode 100644 (file)
index 0000000..e4ae622
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * 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.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class MapAdaptorTest {
+    private MapAdaptor adaptor;
+
+    @Before
+    public void setUp() {
+        adaptor = MapAdaptor.getInstance(true, 10, 5);
+    }
+
+    @Test
+    public void testTreeToEmpty() {
+        final Map<String, String> input = new TreeMap<>();
+
+        // Converts the input into a hashmap;
+        final Map<?, ?> snap = adaptor.takeSnapshot(input);
+        assertNotSame(input, snap);
+        assertTrue(snap instanceof HashMap);
+
+        final Map<?, ?> opt1 = adaptor.optimize(input);
+        assertSame(Collections.EMPTY_MAP, opt1);
+
+        final Map<?, ?> opt2 = adaptor.optimize(snap);
+        assertSame(Collections.EMPTY_MAP, opt2);
+    }
+
+    @Test
+    public void testTreeToSingleton() {
+        final Map<String, String> input = new TreeMap<>();
+        input.put("a", "b");
+
+        final Map<?, ?> snap = adaptor.takeSnapshot(input);
+        assertNotSame(input, snap);
+        assertTrue(snap instanceof HashMap);
+        assertEquals(input, snap);
+
+        final Map<?, ?> opt1 = adaptor.optimize(input);
+        assertNotSame(input, opt1);
+        assertEquals(input, opt1);
+        assertEquals(Collections.singletonMap(null, null).getClass(), opt1.getClass());
+        final Map<?, ?> snap1 = adaptor.takeSnapshot(opt1);
+        assertTrue(snap1 instanceof HashMap);
+        assertEquals(input, snap1);
+
+        final Map<?, ?> opt2 = adaptor.optimize(snap);
+        assertNotSame(snap, opt2);
+        assertEquals(input, opt2);
+        assertEquals(Collections.singletonMap(null, null).getClass(), opt2.getClass());
+
+        final Map<?, ?> snap2 = adaptor.takeSnapshot(opt2);
+        assertNotSame(opt2, snap2);
+        assertTrue(snap2 instanceof HashMap);
+        assertEquals(input, snap2);
+    }
+
+    @Test
+    public void testTreeToTrie() {
+        final Map<String, String> input = new TreeMap<>();
+        for (char c = 'a'; c <= 'z'; ++c) {
+            final String s = String.valueOf(c);
+            input.put(s, s);
+        }
+
+        final Map<String, String> snap = adaptor.takeSnapshot(input);
+        assertTrue(snap instanceof HashMap);
+        assertEquals(input, snap);
+
+        final Map<String, String> opt1 = adaptor.optimize(input);
+        assertEquals(input, opt1);
+        assertEquals(ReadOnlyTrieMap.class, opt1.getClass());
+
+        final Map<String, String> snap2 = adaptor.takeSnapshot(opt1);
+        assertTrue(snap2 instanceof ReadWriteTrieMap);
+        assertEquals(opt1, snap2);
+        assertEquals(26, snap2.size());
+
+        // snap2 and snap3 are independent
+        final Map<String, String> snap3 = adaptor.takeSnapshot(opt1);
+
+        snap2.remove("a");
+        assertEquals(25, snap2.size());
+        assertEquals(26, snap3.size());
+
+        snap3.remove("b");
+        snap3.remove("c");
+        assertEquals(25, snap2.size());
+        assertEquals(24, snap3.size());
+
+        snap2.put("foo", "foo");
+        snap2.put("bar", "baz");
+        snap3.put("bar", "baz");
+        assertEquals(27, snap2.size());
+        assertEquals(25, snap3.size());
+    }
+
+    @Test
+    public void testTrieToHash() {
+        final Map<String, String> input = new TreeMap<>();
+        for (char c = 'a'; c <= 'k'; ++c) {
+            final String s = String.valueOf(c);
+            input.put(s, s);
+        }
+
+        // Translated to read-only
+        final Map<String, String> opt1 = adaptor.optimize(input);
+        assertEquals(input, opt1);
+        assertEquals(ReadOnlyTrieMap.class, opt1.getClass());
+        assertEquals(11, opt1.size());
+
+        // 11 elements -- should retain TrieMap
+        final Map<String, String> snap1 = adaptor.takeSnapshot(opt1);
+        assertEquals(ReadWriteTrieMap.class, snap1.getClass());
+        assertEquals(11, snap1.size());
+
+        for (char c = 'e'; c <= 'k'; ++c) {
+            final String s = String.valueOf(c);
+            snap1.remove(s);
+        }
+
+        // 4 elements: should revert to HashMap
+        assertEquals(4, snap1.size());
+
+        final Map<String, String> opt2 = adaptor.optimize(snap1);
+        assertEquals(snap1, opt2);
+        assertEquals(HashMap.class, opt2.getClass());
+        assertEquals(4, opt2.size());
+    }
+}
index d364a70f1c552f7be7fd596d78762528fa40faa1..31890256c009262e472217ba2b7ba8b8001974d8 100644 (file)
@@ -40,9 +40,7 @@ public class Bug466EmptyAugmentationCodecs {
         assertNotNull(schemaContext);
         assertTrue(schemaContext.isPresent());
 
-        mappingService = new RuntimeGeneratedMappingServiceImpl(moduleInfoContext);
-        mappingService.setPool(ClassPool.getDefault());
-        mappingService.init();
+        mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(), moduleInfoContext);
         mappingService.onGlobalContextUpdated(schemaContext.get());
 
     }
diff --git a/pom.xml b/pom.xml
index 9ccb93b27e8d0e3ff3b3165c4161a3c1d9a36cc4..de8b4e1722e1f0ecf50a2a7b057aa6a4d6e91bf4 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -44,6 +44,7 @@
         <groovy.version>2.1.6</groovy.version>
         <mockito.version>1.9.5</mockito.version>
         <javassist.version>3.17.1-GA</javassist.version>
+        <ctrie.version>0.2.0</ctrie.version>
     </properties>
 
     <scm>
                 <artifactId>jsr305</artifactId>
                 <version>2.0.3</version>
             </dependency>
+            <dependency>
+                <groupId>com.github.romix</groupId>
+                <artifactId>java-concurrent-hash-trie-map</artifactId>
+                <version>${ctrie.version}</version>
+            </dependency>
 
             <!-- Plugin integration -->
             <dependency>
                 <artifactId>object-cache-noop</artifactId>
                 <version>${project.version}</version>
             </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>util</artifactId>
+                <version>${project.version}</version>
+            </dependency>
         </dependencies>
     </dependencyManagement>
 
index ce3c61eaf0acd8d8d46494a729492e6edbc40788..174c26ccb9ba1d58da4fb49dd0e7930bcd8dd4c0 100644 (file)
@@ -43,9 +43,7 @@ public class RestconfClientImplTest {
 
     @Before
     public void setupRestconfClientContext() throws MalformedURLException, UnsupportedProtocolException {
-        mappingService = new RuntimeGeneratedMappingServiceImpl();
-        mappingService.setPool(new ClassPool());
-        mappingService.init();
+        mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
 
         final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
         moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
index e4c794dcb7c478255476c63bafbb36870947f9e5..1bbbe8d6fd65333f9877959a39676c661ec06c1d 100644 (file)
@@ -46,9 +46,7 @@ public class Bug527Test {
 
     @Before
     public void setup() {
-        this.mappingService = new RuntimeGeneratedMappingServiceImpl();
-        this.mappingService.setPool(new ClassPool());
-        this.mappingService.init();
+        this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
 
         final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
         moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
index 7abb03b7841935f9f272c5f4cbe8791a50559048..30048130443b483f323698c020b9a1d85f360a4c 100644 (file)
@@ -33,7 +33,7 @@ public final class BindingMapping {
     public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
     public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
 
-    private static final Splitter SPACE_SPLITTER = Splitter.on(" ").omitEmptyStrings().trimResults();
+    private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
 
     public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
     public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
index 09a2625697526410a40daac992aeca7f9f06768c..e31239dd8fbd49a0069a64602fb94c01c3c722b4 100644 (file)
@@ -30,14 +30,18 @@ import org.opendaylight.yangtools.concepts.Immutable;
  * same local name, but from different schemas.
  *
  * <ul>
- * <li><b>XMLNamespace</b> - the namespace assigned to the YANG module which
+ * <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
  * defined element, type, procedure or notification.</li>
- * <li><b>Revision</b> - the revision of the YANG module which describes the
+ * <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
  * element</li>
- * <li><b>LocalName</b> - the YANG schema identifier which were defined for this
+ * <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
  * node in the YANG module</li>
  * </ul>
  *
+ * QName may also have <code>prefix</code> assigned, but prefix does not
+ * affect equality and identity of two QNames and carry only information
+ * which may be useful for serializers / deserializers.
+ *
  *
  */
 public final class QName implements Immutable, Serializable, Comparable<QName> {
@@ -47,22 +51,26 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
     static final String QNAME_LEFT_PARENTHESIS = "(";
     static final String QNAME_RIGHT_PARENTHESIS = ")";
 
-    private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(
-            "^\\((.+)\\" + QNAME_REVISION_DELIMITER + "(.+)\\)(.+)$");
-    private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(
-           "^\\((.+)\\)(.+)$");
-    private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile(
-            "^(.+)$");
+    private static final Pattern QNAME_PATTERN_FULL = Pattern.compile("^\\((.+)\\" + QNAME_REVISION_DELIMITER
+            + "(.+)\\)(.+)$");
+    private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile("^\\((.+)\\)(.+)$");
+    private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
 
-    private static final char[] ILLEGAL_CHARACTERS = new char[] {'?', '(', ')', '&'};
+    private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
 
-    //Mandatory
+    // Mandatory
     private final QNameModule module;
-    //Mandatory
+    // Mandatory
     private final String localName;
-    //Nullable
+    // Nullable
     private final String prefix;
 
+    private QName(final QNameModule module, final String prefix, final String localName) {
+        this.localName = checkLocalName(localName);
+        this.prefix = prefix;
+        this.module = module;
+    }
+
     /**
      * QName Constructor.
      *
@@ -74,11 +82,10 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
      *            locally defined prefix assigned to local name
      * @param localName
      *            YANG schema identifier
+     *
      */
     public QName(final URI namespace, final Date revision, final String prefix, final String localName) {
-        this.localName = checkLocalName(localName);
-        this.prefix = prefix;
-        this.module = QNameModule.create(namespace, revision);
+        this(QNameModule.create(namespace, revision), prefix, localName);
     }
 
     /**
@@ -101,11 +108,10 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
             throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
         }
 
-        for (char c: ILLEGAL_CHARACTERS) {
+        for (char c : ILLEGAL_CHARACTERS) {
             if (localName.indexOf(c) != -1) {
                 throw new IllegalArgumentException(String.format(
-                        "Parameter 'localName':'%s' contains illegal character '%s'",
-                        localName, c));
+                        "Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
             }
         }
         return localName;
@@ -120,18 +126,30 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
      *            the revision of the YANG module
      * @param localName
      *            YANG schema identifier
+     *
+     * @deprecated Use {@link #create(URI, Date, String)} instead.
      */
+    @Deprecated
     public QName(final URI namespace, final Date revision, final String localName) {
-        this(namespace, revision, null, localName);
+        this(QNameModule.create(namespace, revision), null, localName);
     }
 
+    /**
+     * Construct new QName which reuses namespace, revision and prefix from
+     * base.
+     *
+     * @param base
+     * @param localName
+     * @deprecated Use {@link #create(QName, String)} instead.
+     */
+    @Deprecated
     public QName(final QName base, final String localName) {
         this(base.getNamespace(), base.getRevision(), base.getPrefix(), localName);
     }
 
     /**
-     * @deprecated Use {@link #create(String)} instead.
-     * This implementation is broken.
+     * @deprecated Use {@link #create(String)} instead. This implementation is
+     *             broken.
      */
     @Deprecated
     public QName(final String input) throws ParseException {
@@ -169,7 +187,7 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
         matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
         if (matcher.matches()) {
             String localName = matcher.group(1);
-            return new QName((URI)null, localName);
+            return new QName((URI) null, localName);
         }
         throw new IllegalArgumentException("Invalid input:" + input);
     }
@@ -224,6 +242,17 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
         return result;
     }
 
+    /**
+     *
+     * Compares the specified object with this list for equality.  Returns
+     * <tt>true</tt> if and only if the specified object is also instance of
+     * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
+     * {@link #getRevision()} are equals to same properties of this instance.
+     *
+     * @param o the object to be compared for equality with this QName
+     * @return <tt>true</tt> if the specified object is equal to this QName
+     *
+     */
     @Override
     public boolean equals(final Object obj) {
         if (this == obj) {
@@ -257,20 +286,48 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
         return true;
     }
 
-    public static QName create(final QName base, final String localName){
+    public static QName create(final QName base, final String localName) {
         return new QName(base, localName);
     }
 
-    public static QName create(final URI namespace, final Date revision, final String localName){
-        return new QName(namespace, revision, localName);
+    /**
+     *
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName or null if namespace is undefined.
+     * @param revision Revision of namespace or null if revision is unspecified.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return Instance of QName
+     */
+    public static QName create(final URI namespace, final Date revision, final String localName) {
+        return new QName(QNameModule.create(namespace, revision), null,localName);
     }
 
-
-    public static QName create(final String namespace, final String revision, final String localName) throws IllegalArgumentException{
+    /**
+     *
+     * Creates new QName.
+     *
+     * @param namespace
+     *            Namespace of QName, MUST NOT BE Null.
+     * @param revision
+     *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
+     *            in format <code>YYYY-mm-dd</code>.
+     * @param localName
+     *            Local name part of QName. MUST NOT BE null.
+     * @return
+     * @throws NullPointerException
+     *             If any of paramaters is null.
+     * @throws IllegalArgumentException
+     *             If <code>namespace</code> is not valid URI or
+     *             <code>revision</code> is not according to format
+     *             <code>YYYY-mm-dd</code>.
+     */
+    public static QName create(final String namespace, final String revision, final String localName)
+            throws IllegalArgumentException {
         final URI namespaceUri;
         try {
             namespaceUri = new URI(namespace);
-        }  catch (URISyntaxException ue) {
+        } catch (URISyntaxException ue) {
             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
         }
 
@@ -293,10 +350,26 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
         return sb.toString();
     }
 
+    /**
+     * Return string representation of revision in format
+     * <code>YYYY-mm-dd</code>
+     *
+     * YANG Specification defines format for <code>revision</code> as
+     * YYYY-mm-dd. This format for revision is reused accross multiple places
+     * such as capabilities URI, YANG modules, etc.
+     *
+     * @return String representation of revision or null, if revision is not
+     *         set.
+     */
     public String getFormattedRevision() {
         return module.getFormattedRevision();
     }
 
+    /**
+     * Creates copy of this with revision and prefix unset.
+     *
+     * @return copy of this QName with revision and prefix unset.
+     */
     public QName withoutRevision() {
         return QName.create(getNamespace(), null, localName);
     }
@@ -304,18 +377,46 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
     public static Date parseRevision(final String formatedDate) {
         try {
             return getRevisionFormat().parse(formatedDate);
-        } catch (ParseException| RuntimeException e) {
-            throw new IllegalArgumentException(String.format("Revision '%s'is not in a supported format", formatedDate), e);
+        } catch (ParseException | RuntimeException e) {
+            throw new IllegalArgumentException(
+                    String.format("Revision '%s'is not in a supported format", formatedDate), e);
         }
     }
 
+    /**
+     * Formats {@link Date} representing revision to format
+     * <code>YYYY-mm-dd</code>
+     *
+     * YANG Specification defines format for <code>revision</code> as
+     * YYYY-mm-dd. This format for revision is reused accross multiple places
+     * such as capabilities URI, YANG modules, etc.
+     *
+     * @param revision
+     *            Date object to format or null
+     * @return String representation or null if the input was null.
+     */
     public static String formattedRevision(final Date revision) {
-        if(revision == null) {
+        if (revision == null) {
             return null;
         }
         return getRevisionFormat().format(revision);
     }
 
+    /**
+     *
+     * Compares this QName to other, without comparing revision.
+     *
+     * Compares instance of this to other instance of QName and returns true if
+     * both instances have equal <code>localName</code> ({@link #getLocalName()}
+     * ) and <code>namespace</code> ({@link #getNamespace()}).
+     *
+     * @param other
+     *            Other QName. Must not be null.
+     * @return true if this instance and other have equals localName and
+     *         namespace.
+     * @throws NullPointerException
+     *             if <code>other</code> is null.
+     */
     public boolean isEqualWithoutRevision(final QName other) {
         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
     }
index ba76a274118a19d96d3e460a291b7aa592ddeff6..d207791f2a64a68ff2aca14a5f4660427f3ed0ef 100644 (file)
@@ -7,19 +7,87 @@
  */
 package org.opendaylight.yangtools.yang.common;
 
+/**
+ *
+ * Representation of Error in YANG enabled system.
+ *
+ * Which may be send / received by YANG modeled / enabled systems.
+ *
+ */
 public interface RpcError {
+
+    /**
+     *
+     * Returns error severity, as determined by component reporting the error.
+     *
+     * @return error severity
+     */
     ErrorSeverity getSeverity();
 
+    /**
+     *
+     * Returns a string identifying the error condition.
+     *
+     * @return string identifying the error condition.
+     */
     String getTag();
 
+    /**
+     *
+     * Returns a string identifying the data-model-specific or
+     * implementation-specific error condition, if one exists. This element will
+     * not be present if no appropriate application error-tag can be associated
+     * with a particular error condition. If a data-model-specific and an
+     * implementation-specific error-app-tag both exist, then the
+     * data-model-specific value MUST be used by the reporter.
+     *
+     * @return Returns a string identifying the data-model-specific or
+     *         implementation-specific error condition, or null if does not
+     *         exists.
+     */
     String getApplicationTag();
 
+    /**
+     *
+     * Returns a string suitable for human display that describes the error
+     * condition. This element will not be present if no appropriate message is
+     * provided for a particular error condition.
+     *
+     * @return returns an error description for human display.
+     */
     String getMessage();
 
+    /**
+     *
+     * Contains protocol- or data-model-specific error content. This value may
+     * be not be present if no such error content is provided for a particular
+     * error condition.
+     *
+     * The list in Appendix A defines any mandatory error-info content for each
+     * error. After any protocol-mandated content, a data model definition MAY
+     * mandate that certain application-layer error information be included in
+     * the error-info container.
+     *
+     * An implementation MAY include additional information to provide extended
+     * and/or implementation- specific debugging information.
+     *
+     * @return
+     */
     String getInfo();
-    
+
+    /**
+     *
+     * Return a cause if available.
+     *
+     * @return cause of this error, if error was triggered by exception.
+     */
     Throwable getCause();
-    
+
+    /**
+     * Returns the conceptual layer that on which the error occurred.
+     *
+     * @return the conceptual layer that on which the error occurred.
+     */
     ErrorType getErrorType();
 
     public enum ErrorSeverity {
index dc697f517802e7e06263af4931d63c5c66ce245e..4cc40822336ac7c50bb64de9edffc64e70984458 100644 (file)
@@ -9,10 +9,37 @@ package org.opendaylight.yangtools.yang.common;
 
 import java.util.Collection;
 
+/**
+ *
+ * Result of call to YANG enabled system.
+ *
+ *
+ * @param <T> Return type
+ */
 public interface RpcResult<T> {
+
+    /**
+     * True if processing of request was successful
+     *
+     * @return true if processing was successful.
+     */
     boolean isSuccessful();
 
+    /**
+     *
+     * Returns result of call or null if no result is available.
+     *
+     * @return result of call or null if no result is available.
+     *
+     */
     T getResult();
 
+    /**
+     *
+     * Returns set of errors and warnings which occured during processing
+     * the request.
+     *
+     * @return
+     */
     Collection<RpcError> getErrors();
 }
index e951009ad5128ddcf741e10f247c3a4e7c98036e..21e9d52917b79a9730a193aef6119af5305614fe 100644 (file)
@@ -39,8 +39,9 @@ public interface CompositeNode extends //
      * Returns a list of children as seens in resulting XML serialization
      * defined by YANG specification.
      *
-     *
      * @return
+     *
+     * @deprecated Use {@link #getValue()} instead.
      */
     @Deprecated
     List<Node<?>> getChildren();
index 013bbcc357a2b9974c5915c0705c698172c88b9b..538195109bda19c52cc31fe90d9441269cdf1bae 100644 (file)
     </build>
 
     <dependencies>
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>util</artifactId>
+        </dependency>
         <dependency>
             <groupId>${project.groupId}</groupId>
             <artifactId>yang-common</artifactId>
index 2d761980a6f2066eeceaff851754400c19476cbb..0282cae6021104c28daa774ae659239abf3f0163 100644 (file)
@@ -27,7 +27,7 @@ import org.opendaylight.yangtools.yang.data.api.SimpleNode;
  */
 public class LazyNodeToNodeMap {
 
-    private Map<Node<?>, Node<?>> node2node = new HashMap<>();
+    private final Map<Node<?>, Node<?>> node2node = new HashMap<>();
     private CompositeNode originalRoot;
     private MutableCompositeNode mutableRoot;
 
@@ -35,7 +35,7 @@ public class LazyNodeToNodeMap {
      * @param originalNode
      * @return mutable twin
      */
-    public Node<?> getMutableEquivalent(Node<?> originalNode) {
+    public Node<?> getMutableEquivalent(final Node<?> originalNode) {
         Node<?> mutableNode = node2node.get(originalNode);
         if (mutableNode == null) {
             addPathMembers(originalNode);
@@ -48,7 +48,7 @@ public class LazyNodeToNodeMap {
     /**
      * @param originalNode
      */
-    private void addPathMembers(Node<?> originalNode) {
+    private void addPathMembers(final Node<?> originalNode) {
         Stack<Node<?>> jobQueue = new Stack<>();
         jobQueue.push(originalNode);
         while (!jobQueue.isEmpty()) {
@@ -84,15 +84,15 @@ public class LazyNodeToNodeMap {
                 mutableEquivalent = nodeMutant;
 
                 // tidy up children
-                if (nodeMutant.getChildren() == null) {
+                if (nodeMutant.getValue() == null) {
                     nodeMutant.setValue(new ArrayList<Node<?>>());
                 }
-                for (Node<?> originalChildNode : ((CompositeNode) node2add).getChildren()) {
+                for (Node<?> originalChildNode : ((CompositeNode) node2add).getValue()) {
                     MutableNode<?> mutableChild = (MutableNode<?>) node2node.get(originalChildNode);
                     fixChildrenRef(nodeMutant, mutableChild);
                 }
 
-                if (nodeMutant.getChildren() != null && !nodeMutant.getChildren().isEmpty()) {
+                if (nodeMutant.getValue() != null && !nodeMutant.getValue().isEmpty()) {
                     nodeMutant.init();
                 }
 
@@ -122,11 +122,11 @@ public class LazyNodeToNodeMap {
      * @param nodeMutant
      * @param mutableChild
      */
-    private static void fixChildrenRef(MutableCompositeNode nodeMutant,
-            MutableNode<?> mutableChild) {
+    private static void fixChildrenRef(final MutableCompositeNode nodeMutant,
+            final MutableNode<?> mutableChild) {
         if (mutableChild != null) {
-            if (!nodeMutant.getChildren().contains(mutableChild)) {
-                nodeMutant.getChildren().add(mutableChild);
+            if (!nodeMutant.getValue().contains(mutableChild)) {
+                nodeMutant.getValue().add(mutableChild);
             }
             CompositeNode parentOfChild = mutableChild.getParent();
             if (parentOfChild == null) {
index c764cdb36c2e850390565a6e62f5419aac39739a..735ff27c44957cfd154fc49a30c421fcd5d8e7e2 100644 (file)
@@ -36,8 +36,8 @@ public abstract class NodeFactory {
      * @param value
      * @return simple node modification, based on given qname, value and parent
      */
-    public static <T> SimpleNode<T> createImmutableSimpleNode(QName qName,
-            CompositeNode parent, T value) {
+    public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
+            final CompositeNode parent, final T value) {
         return createImmutableSimpleNode(qName, parent, value, null);
     }
 
@@ -49,8 +49,8 @@ public abstract class NodeFactory {
      * @param original originating node, if available
      * @return simple node modification, based on given qname, value and parent
      */
-    public static <T> MutableSimpleNode<T> createMutableSimpleNode(QName qName,
-            CompositeNode parent, Object value, ModifyAction modifyAction, SimpleNode<T> original) {
+    public static <T> MutableSimpleNode<T> createMutableSimpleNode(final QName qName,
+            final CompositeNode parent, final Object value, final ModifyAction modifyAction, final SimpleNode<T> original) {
         @SuppressWarnings("unchecked")
         MutableSimpleNodeTOImpl<T> simpleNodeTOImpl =
                 new MutableSimpleNodeTOImpl<T>(qName, parent, (T) value, modifyAction);
@@ -64,8 +64,8 @@ public abstract class NodeFactory {
      * @param value
      * @return composite node modification, based on given qname, value (children), parent and modifyAction
      */
-    public static CompositeNode createImmutableCompositeNode(QName qName,
-            CompositeNode parent, List<Node<?>> value) {
+    public static CompositeNode createImmutableCompositeNode(final QName qName,
+            final CompositeNode parent, final List<Node<?>> value) {
         return createImmutableCompositeNode(qName, parent, value, null);
     }
 
@@ -77,8 +77,8 @@ public abstract class NodeFactory {
      * @param original originating node, if available
      * @return composite node modification, based on given qName, value (children), parent and modifyAction
      */
-    public static MutableCompositeNode createMutableCompositeNode(QName qName,
-            CompositeNode parent, List<Node<?>> valueArg, ModifyAction modifyAction, CompositeNode original) {
+    public static MutableCompositeNode createMutableCompositeNode(final QName qName,
+            final CompositeNode parent, final List<Node<?>> valueArg, final ModifyAction modifyAction, final CompositeNode original) {
         List<Node<?>> value = valueArg;
         if (value == null) {
             value = new ArrayList<>();
@@ -97,8 +97,8 @@ public abstract class NodeFactory {
      * @param modifyAction
      * @return simple node modification, based on given qname, value, parent and modifyAction
      */
-    public static <T> SimpleNode<T> createImmutableSimpleNode(QName qName,
-            CompositeNode parent, T value, ModifyAction modifyAction) {
+    public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
+            final CompositeNode parent, final T value, final ModifyAction modifyAction) {
         SimpleNodeTOImpl<T> simpleNodeModTOImpl =
                 new SimpleNodeTOImpl<T>(qName, parent, value, modifyAction);
         return simpleNodeModTOImpl;
@@ -111,8 +111,8 @@ public abstract class NodeFactory {
      * @param modifyAction
      * @return composite node modification, based on given qname, value (children), parent and modifyAction
      */
-    public static CompositeNode createImmutableCompositeNode(QName qName,
-            CompositeNode parent, List<Node<?>> value, ModifyAction modifyAction) {
+    public static CompositeNode createImmutableCompositeNode(final QName qName,
+            final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
         CompositeNodeTOImpl compositeNodeModTOImpl =
                 new CompositeNodeTOImpl(qName, parent, value, modifyAction);
         return compositeNodeModTOImpl;
@@ -123,7 +123,7 @@ public abstract class NodeFactory {
      * @return copy of given node, parent and value are the same, but parent
      * has no reference to this copy
      */
-    public static <T> SimpleNode<T> copyNode(SimpleNode<T> node) {
+    public static <T> SimpleNode<T> copyNode(final SimpleNode<T> node) {
         SimpleNode<T> twinNode = createImmutableSimpleNode(
                     node.getNodeType(), node.getParent(), node.getValue());
         return twinNode;
@@ -134,7 +134,7 @@ public abstract class NodeFactory {
      * @return copy of given node, parent and value are the same, but parent
      * has no reference to this copy
      */
-    public static <T> MutableSimpleNode<T> copyNodeAsMutable(SimpleNode<T> node) {
+    public static <T> MutableSimpleNode<T> copyNodeAsMutable(final SimpleNode<T> node) {
         MutableSimpleNode<T> twinNode = createMutableSimpleNode(
                     node.getNodeType(), node.getParent(), node.getValue(),
                     node.getModificationAction(), null);
@@ -147,7 +147,7 @@ public abstract class NodeFactory {
      * @return copy of given node, parent and children are the same, but parent and children
      * have no reference to this copy
      */
-    public static CompositeNode copyNode(CompositeNode node, Node<?>... children) {
+    public static CompositeNode copyNode(final CompositeNode node, final Node<?>... children) {
         CompositeNode twinNode = createImmutableCompositeNode(
                 node.getNodeType(), node.getParent(), Arrays.asList(children), node.getModificationAction());
         return twinNode;
@@ -158,8 +158,8 @@ public abstract class NodeFactory {
      * @return copy of given node, parent and children are the same, but parent and children
      * have no reference to this copy
      */
-    public static CompositeNode copyNode(CompositeNode node) {
-       return copyNode(node, node.getChildren().toArray(new Node<?>[0]));
+    public static CompositeNode copyNode(final CompositeNode node) {
+       return copyNode(node, node.getValue().toArray(new Node<?>[0]));
     }
 
     /**
@@ -168,8 +168,8 @@ public abstract class NodeFactory {
      * will be stored
      * @return copy of given node and all subnodes recursively
      */
-    public static MutableCompositeNode copyDeepAsMutable(CompositeNode node,
-            Map<Node<?>, Node<?>> originalToCopyArg) {
+    public static MutableCompositeNode copyDeepAsMutable(final CompositeNode node,
+            final Map<Node<?>, Node<?>> originalToCopyArg) {
 
         Map<Node<?>, Node<?>> originalToCopy = originalToCopyArg;
         if (originalToCopy == null) {
@@ -188,7 +188,7 @@ public abstract class NodeFactory {
             MutableCompositeNode mutableNode = job.getValue();
             mutableNode.setValue(new ArrayList<Node<?>>());
 
-            for (Node<?> child : originalNode.getChildren()) {
+            for (Node<?> child : originalNode.getValue()) {
                 Node<?> mutableAscendant = null;
                 if (child instanceof CompositeNode) {
                     MutableCompositeNode newMutable =
@@ -207,7 +207,7 @@ public abstract class NodeFactory {
                             +child.getClass().getName());
                 }
 
-                mutableNode.getChildren().add(mutableAscendant);
+                mutableNode.getValue().add(mutableAscendant);
                 originalToCopy.put(child, mutableAscendant);
             }
             mutableNode.init();
@@ -222,8 +222,8 @@ public abstract class NodeFactory {
      * will be stored
      * @return copy of given node and all subnodes recursively
      */
-    public static CompositeNode copyDeepAsImmutable(CompositeNode node,
-            Map<Node<?>, Node<?>> originalToCopyArg) {
+    public static CompositeNode copyDeepAsImmutable(final CompositeNode node,
+            final Map<Node<?>, Node<?>> originalToCopyArg) {
         Stack<CompositeNode> jobQueue = new Stack<>();
         jobQueue.push(node);
 
@@ -235,15 +235,15 @@ public abstract class NodeFactory {
         while (!jobQueue.isEmpty()) {
             CompositeNode jobNode = jobQueue.peek();
             if (!originalToCopy.isEmpty()
-                    && originalToCopy.keySet().containsAll(jobNode.getChildren())) {
+                    && originalToCopy.keySet().containsAll(jobNode.getValue())) {
                 jobQueue.pop();
-                List<Node<?>> newChildren = NodeUtils.collectMapValues(jobNode.getChildren(), originalToCopy);
+                List<Node<?>> newChildren = NodeUtils.collectMapValues(jobNode.getValue(), originalToCopy);
                 CompositeNode nodeCopy = createImmutableCompositeNode(jobNode.getNodeType(), null,
                         newChildren, jobNode.getModificationAction());
                 NodeUtils.fixChildrenRelation(nodeCopy);
                 originalToCopy.put(jobNode, nodeCopy);
             } else {
-                for (Node<?> child : jobNode.getChildren()) {
+                for (Node<?> child : jobNode.getValue()) {
                     if (child instanceof SimpleNode<?>) {
                         originalToCopy.put(child, createImmutableSimpleNode(
                                 child.getNodeType(), null, child.getValue(),
index f1c2a44a03373ee0126595802740b54cff6beb18..65b7608c166a167d05b6fa1e802db9eb7ef2e07c 100644 (file)
@@ -25,19 +25,19 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
 /**
  * @author michal.rehak
- * 
+ *
  */
 public class NodeModificationBuilderImpl implements NodeModificationBuilder {
 
-    private SchemaContext context;
+    private final SchemaContext context;
 
-    private Set<MutableNode<?>> changeLog;
-    private LazyNodeToNodeMap originalToMutable;
+    private final Set<MutableNode<?>> changeLog;
+    private final LazyNodeToNodeMap originalToMutable;
 
     /**
      * @param context
      */
-    public NodeModificationBuilderImpl(SchemaContext context) {
+    public NodeModificationBuilderImpl(final SchemaContext context) {
         this.context = context;
         originalToMutable = new LazyNodeToNodeMap();
         changeLog = new HashSet<>();
@@ -47,55 +47,55 @@ public class NodeModificationBuilderImpl implements NodeModificationBuilder {
      * @param modNode
      * @param action
      */
-    private void addModificationToLog(MutableNode<?> modNode, ModifyAction action) {
+    private void addModificationToLog(final MutableNode<?> modNode, final ModifyAction action) {
         modNode.setModifyAction(action);
         changeLog.add(modNode);
     }
 
     @Override
-    public void addNode(MutableSimpleNode<?> newNode) {
+    public void addNode(final MutableSimpleNode<?> newNode) {
         NodeUtils.fixParentRelation(newNode);
         addModificationToLog(newNode, ModifyAction.CREATE);
     }
 
     @Override
-    public void addNode(MutableCompositeNode newNode) {
+    public void addNode(final MutableCompositeNode newNode) {
         NodeUtils.fixParentRelation(newNode);
         addModificationToLog(newNode, ModifyAction.CREATE);
     }
 
     @Override
-    public void replaceNode(MutableSimpleNode<?> replacementNode) {
+    public void replaceNode(final MutableSimpleNode<?> replacementNode) {
         addModificationToLog(replacementNode, ModifyAction.REPLACE);
     }
 
     @Override
-    public void replaceNode(MutableCompositeNode replacementNode) {
+    public void replaceNode(final MutableCompositeNode replacementNode) {
         addModificationToLog(replacementNode, ModifyAction.REPLACE);
     }
 
     @Override
-    public void deleteNode(MutableCompositeNode deadNode) {
+    public void deleteNode(final MutableCompositeNode deadNode) {
         addModificationToLog(deadNode, ModifyAction.DELETE);
     }
 
     @Override
-    public void deleteNode(MutableSimpleNode<?> deadNode) {
+    public void deleteNode(final MutableSimpleNode<?> deadNode) {
         addModificationToLog(deadNode, ModifyAction.DELETE);
     }
 
     @Override
-    public void removeNode(MutableSimpleNode<?> deadNode) {
+    public void removeNode(final MutableSimpleNode<?> deadNode) {
         addModificationToLog(deadNode, ModifyAction.REMOVE);
     }
 
     @Override
-    public void removeNode(MutableCompositeNode deadNode) {
+    public void removeNode(final MutableCompositeNode deadNode) {
         addModificationToLog(deadNode, ModifyAction.REMOVE);
     }
 
     @Override
-    public void mergeNode(MutableCompositeNode alteredNode) {
+    public void mergeNode(final MutableCompositeNode alteredNode) {
         addModificationToLog(alteredNode, ModifyAction.MERGE);
     }
 
@@ -122,7 +122,7 @@ public class NodeModificationBuilderImpl implements NodeModificationBuilder {
                         // try to add key subnode to wanted list
                         List<QName> supportedKeys = listSchema.getKeyDefinition();
                         CompositeNode outlawOriginal = ((MutableCompositeNode) outlaw).getOriginal();
-                        for (Node<?> outlawOriginalChild : outlawOriginal.getChildren()) {
+                        for (Node<?> outlawOriginalChild : outlawOriginal.getValue()) {
                             if (supportedKeys.contains(outlawOriginalChild.getNodeType())) {
                                 originalToMutable.getMutableEquivalent(outlawOriginalChild);
                             }
@@ -139,7 +139,7 @@ public class NodeModificationBuilderImpl implements NodeModificationBuilder {
      * @param focusedDescendant
      * @return set of parents and focusedAncestor itself
      */
-    private static Set<Node<?>> collectSelfAndAllParents(Node<?> focusedDescendant) {
+    private static Set<Node<?>> collectSelfAndAllParents(final Node<?> focusedDescendant) {
         Set<Node<?>> family = new HashSet<>();
         Node<?> tmpNode = focusedDescendant;
         while (tmpNode != null) {
@@ -154,7 +154,7 @@ public class NodeModificationBuilderImpl implements NodeModificationBuilder {
      * @return mutable version of given node
      */
     @Override
-    public Node<?> getMutableEquivalent(Node<?> originalNode) {
+    public Node<?> getMutableEquivalent(final Node<?> originalNode) {
         return originalToMutable.getMutableEquivalent(originalNode);
     }
 
index 56c814bfde79844310d11fa7b278d00be54a1029..31ab5fdbb2b0f42e822fc7080add4b2f83b404e3 100644 (file)
@@ -23,7 +23,6 @@ import javax.xml.xpath.XPathExpression;
 import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
 
-import com.google.common.collect.Maps;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
@@ -40,6 +39,7 @@ import org.w3c.dom.Element;
 
 import com.google.common.base.Joiner;
 import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
 
 /**
  * @author michal.rehak
@@ -58,7 +58,7 @@ public abstract class NodeUtils {
      * @param node
      * @return node path up till root node
      */
-    public static String buildPath(Node<?> node) {
+    public static String buildPath(final Node<?> node) {
         List<String> breadCrumbs = new ArrayList<>();
         Node<?> tmpNode = node;
         while (tmpNode != null) {
@@ -74,7 +74,7 @@ public abstract class NodeUtils {
      * @return dom tree, containing same node structure, yang nodes are
      *         associated to dom nodes as user data
      */
-    public static org.w3c.dom.Document buildShadowDomTree(CompositeNode treeRootNode) {
+    public static org.w3c.dom.Document buildShadowDomTree(final CompositeNode treeRootNode) {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         org.w3c.dom.Document doc = null;
         try {
@@ -111,7 +111,7 @@ public abstract class NodeUtils {
             jointPlace.appendChild(itemEl);
 
             if (item instanceof CompositeNode) {
-                for (Node<?> child : ((CompositeNode) item).getChildren()) {
+                for (Node<?> child : ((CompositeNode) item).getValue()) {
                     jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(itemEl, child));
                 }
             }
@@ -127,7 +127,7 @@ public abstract class NodeUtils {
      * @throws XPathExpressionException
      */
     @SuppressWarnings("unchecked")
-    public static <T> T findNodeByXpath(org.w3c.dom.Document doc, String xpathEx) throws XPathExpressionException {
+    public static <T> T findNodeByXpath(final org.w3c.dom.Document doc, final String xpathEx) throws XPathExpressionException {
         T userNode = null;
         XPathFactory xPathfactory = XPathFactory.newInstance();
         XPath xpath = xPathfactory.newXPath();
@@ -148,7 +148,7 @@ public abstract class NodeUtils {
      * @return map of children, where key = qName and value is list of children
      *         groupped by qName
      */
-    public static Map<QName, List<Node<?>>> buildNodeMap(List<Node<?>> value) {
+    public static Map<QName, List<Node<?>>> buildNodeMap(final List<Node<?>> value) {
         Map<QName, List<Node<?>>> nodeMapTmp = Maps.newLinkedHashMap();
         if (value == null) {
             throw new IllegalStateException("nodeList should not be null or empty");
@@ -168,7 +168,7 @@ public abstract class NodeUtils {
      * @param context
      * @return map of lists, where key = path; value = {@link DataSchemaNode}
      */
-    public static Map<String, ListSchemaNode> buildMapOfListNodes(SchemaContext context) {
+    public static Map<String, ListSchemaNode> buildMapOfListNodes(final SchemaContext context) {
         Map<String, ListSchemaNode> mapOfLists = new HashMap<>();
 
         Stack<DataSchemaNode> jobQueue = new Stack<>();
@@ -192,7 +192,7 @@ public abstract class NodeUtils {
      * @param qNamesPath
      * @return path
      */
-    private static String schemaPathToPath(List<QName> qNamesPath) {
+    private static String schemaPathToPath(final List<QName> qNamesPath) {
         List<String> pathSeed = new ArrayList<>();
         for (QName qNameItem : qNamesPath) {
             pathSeed.add(qNameItem.getLocalName());
@@ -205,9 +205,9 @@ public abstract class NodeUtils {
      *
      * @param newNode
      */
-    public static void fixParentRelation(Node<?> newNode) {
+    public static void fixParentRelation(final Node<?> newNode) {
         if (newNode.getParent() != null) {
-            List<Node<?>> siblings = newNode.getParent().getChildren();
+            List<Node<?>> siblings = newNode.getParent().getValue();
             if (!siblings.contains(newNode)) {
                 siblings.add(newNode);
             }
@@ -219,9 +219,9 @@ public abstract class NodeUtils {
      *
      * @param parentNode
      */
-    public static void fixChildrenRelation(CompositeNode parentNode) {
-        if (parentNode.getChildren() != null) {
-            for (Node<?> child : parentNode.getChildren()) {
+    public static void fixChildrenRelation(final CompositeNode parentNode) {
+        if (parentNode.getValue() != null) {
+            for (Node<?> child : parentNode.getValue()) {
                 if (child instanceof AbstractNodeTO<?>) {
                     ((AbstractNodeTO<?>) child).setParent(parentNode);
                 }
@@ -234,7 +234,7 @@ public abstract class NodeUtils {
      * @param dataMap
      * @return list of values of map, found by given keys
      */
-    public static <T, K> List<K> collectMapValues(List<T> keys, Map<T, K> dataMap) {
+    public static <T, K> List<K> collectMapValues(final List<T> keys, final Map<T, K> dataMap) {
         List<K> valueSubList = new ArrayList<>();
         for (T key : keys) {
             valueSubList.add(dataMap.get(key));
@@ -247,7 +247,7 @@ public abstract class NodeUtils {
      * @param nodes
      * @return list of children in list of appropriate type
      */
-    public static List<Node<?>> buildChildrenList(Node<?>... nodes) {
+    public static List<Node<?>> buildChildrenList(final Node<?>... nodes) {
         return Lists.newArrayList(nodes);
     }
 
index ccba69b4b925df413397dd5d4c3babebaa656d0c..c55567987b16ab8ed756cbe7be755f5ea6ad247c 100644 (file)
@@ -36,9 +36,9 @@ import org.opendaylight.yangtools.yang.data.api.SimpleNode;
  * XML as {@link InputStream}. The output of the operation SHOULD be root
  * <code>CompositeNode</code> or <code>SimpleElement</code> depends by which
  * element XML begins. The XML header is omitted by XML parser.
- * 
+ *
  * @author Lukas Sedlak
- * 
+ *
  * @see CompositeNode
  * @see SimpleNode
  * @see Node
@@ -56,7 +56,7 @@ public final class XmlTreeBuilder {
      * output of the operation SHOULD be root <code>CompositeNode</code> or
      * <code>SimpleElement</code> depends on element that XML document begins.
      * The XML header is omitted by XML parser.
-     * 
+     *
      * @param inputStream
      *            XML Input Stream
      * @return root <code>Node</code> element conformant to XML start element in
@@ -91,7 +91,7 @@ public final class XmlTreeBuilder {
                 if (newNode != null) {
                     processingQueue.push(newNode);
                     if (compParentNode != null) {
-                        compParentNode.getChildren().add(newNode);
+                        compParentNode.getValue().add(newNode);
                     }
                 }
             } else if (event.isEndElement()) {
@@ -109,14 +109,14 @@ public final class XmlTreeBuilder {
      * characters value. If the SimpleNode is composed only by empty XML tag
      * (i.e. {@code <emptyTag />} or {@code<emptyTag></emptyTag>}) the result
      * will be also <code>true</code>.
-     * 
+     *
      * @param event
      *            actual XMLEvent that is processed
      * @return <code>true</code> only and only if the XMLEvent Start Element is
      *         Simple element tag and contains character values or is empty XML
      *         tag.
      * @throws XMLStreamException
-     * 
+     *
      * @see SimpleNode
      */
     private static boolean isSimpleNodeEvent(final XMLEvent event) throws XMLStreamException {
@@ -144,13 +144,13 @@ public final class XmlTreeBuilder {
      * contains 1..N XML child elements. (i.e. {@code <compositeNode>
      *         <simpleNode>data</simpleNode>
      * </compositeNode>})
-     * 
+     *
      * @param event
      *            actual XMLEvent that is processed
      * @return <code>true</code> only if XML Element contains 1..N child
      *         elements, otherwise returns <code>false</code>
      * @throws XMLStreamException
-     * 
+     *
      * @see CompositeNode
      */
     private static boolean isCompositeNodeEvent(final XMLEvent event) throws XMLStreamException {
@@ -177,7 +177,7 @@ public final class XmlTreeBuilder {
     /**
      * Creates and returns <code>SimpleNode</code> instance from actually
      * processed XML Start Element.
-     * 
+     *
      * @param startElement
      *            actual XML Start Element that is processed
      * @param parent
@@ -185,11 +185,11 @@ public final class XmlTreeBuilder {
      * @return <code>new SimpleNode</code> instance from actually processed XML
      *         Start Element
      * @throws XMLStreamException
-     * 
+     *
      * @see SimpleNode
      */
     private static SimpleNode<String> resolveSimpleNodeFromStartElement(final StartElement startElement,
-            CompositeNode parent) throws XMLStreamException {
+            final CompositeNode parent) throws XMLStreamException {
         checkArgument(startElement != null, "Start Element cannot be NULL!");
         String data = null;
 
@@ -210,19 +210,19 @@ public final class XmlTreeBuilder {
     /**
      * Creates and returns <code>MutableCompositeNode</code> instance from
      * actually processed XML Start Element.
-     * 
+     *
      * @param startElement
      *            actual XML Start Element that is processed
      * @param parent
      *            Parent CompositeNode
      * @return <code>new MutableCompositeNode</code> instance from actually
      *         processed XML Start Element
-     * 
+     *
      * @see CompositeNode
      * @see MutableCompositeNode
      */
     private static MutableCompositeNode resolveCompositeNodeFromStartElement(final StartElement startElement,
-            CompositeNode parent) {
+            final CompositeNode parent) {
         checkArgument(startElement != null, "Start Element cannot be NULL!");
 
         return NodeFactory.createMutableCompositeNode(resolveElementQName(startElement), parent,
@@ -231,12 +231,12 @@ public final class XmlTreeBuilder {
 
     /**
      * Extract and retrieve XML Element QName to OpenDaylight QName.
-     * 
+     *
      * @param element
      *            Start Element
      * @return QName instance composed of <code>elements</code> Namespace and
      *         Local Part.
-     * 
+     *
      * @see QName
      */
     private static QName resolveElementQName(final StartElement element) {
index 6ffaf20ccc6f231c6af028d635d31a120b1a066b..7b180f96651a8e81aacfc848f3d8364ea67b2da5 100644 (file)
@@ -65,7 +65,7 @@ public class XmlDocumentUtils {
         Element element;
         SchemaContext schemaContext;
 
-        ElementWithSchemaContext(Element element,SchemaContext schemaContext) {
+        ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
             this.schemaContext = schemaContext;
             this.element = element;
         }
@@ -82,7 +82,7 @@ public class XmlDocumentUtils {
     private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
 
         @Override
-        public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
+        public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
             return TypeDefinitionAwareCodec.from(baseType);
         }
     };
@@ -101,7 +101,7 @@ public class XmlDocumentUtils {
      * @return new instance of XML Document
      * @throws UnsupportedDataTypeException
      */
-    public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
+    public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
             throws UnsupportedDataTypeException {
         Preconditions.checkNotNull(data);
         Preconditions.checkNotNull(schema);
@@ -139,7 +139,7 @@ public class XmlDocumentUtils {
      * @return new instance of XML Document
      * @throws UnsupportedDataTypeException
      */
-    public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
+    public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider)
             throws UnsupportedDataTypeException {
         Preconditions.checkNotNull(data);
 
@@ -157,8 +157,8 @@ public class XmlDocumentUtils {
         return doc;
     }
 
-    private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
-            XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
+    private static Element createXmlRootElement(final Document doc, final Node<?> data, final SchemaNode schema,
+            final XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
         Element itemEl = createElementFor(doc, data);
         if (data instanceof SimpleNode<?>) {
             if (schema instanceof LeafListSchemaNode) {
@@ -174,7 +174,7 @@ public class XmlDocumentUtils {
                 }
             }
         } else { // CompositeNode
-            for (Node<?> child : ((CompositeNode) data).getChildren()) {
+            for (Node<?> child : ((CompositeNode) data).getValue()) {
                 DataSchemaNode childSchema = null;
                 if (schema != null) {
                     childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
@@ -192,7 +192,7 @@ public class XmlDocumentUtils {
         return itemEl;
     }
 
-    public static Element createElementFor(Document doc, Node<?> data) {
+    public static Element createElementFor(final Document doc, final Node<?> data) {
         QName dataType = data.getNodeType();
         Element ret;
         if (dataType.getNamespace() != null) {
@@ -210,15 +210,15 @@ public class XmlDocumentUtils {
         return ret;
     }
 
-    public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
-            DataSchemaNode schema, XmlCodecProvider codecProvider) {
+    public static void writeValueByType(final Element element, final SimpleNode<?> node, final TypeDefinition<?> type,
+            final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
 
         Object nodeValue = node.getValue();
 
         writeValueByType(element, type, codecProvider, nodeValue);
     }
 
-    public static void writeValueByType(Element element, TypeDefinition<?> type, XmlCodecProvider codecProvider, Object nodeValue) {
+    public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
         if (baseType instanceof IdentityrefTypeDefinition) {
             if (nodeValue instanceof QName) {
@@ -269,7 +269,7 @@ public class XmlDocumentUtils {
     }
 
 
-    public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
+    public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
         TypeDefinition<?> superType = type;
         while (superType.getBaseType() != null) {
             superType = superType.getBaseType();
@@ -277,7 +277,7 @@ public class XmlDocumentUtils {
         return superType;
     }
 
-    private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
+    private static final DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
         if (dataSchemaNode != null && node != null) {
             for (DataSchemaNode dsn : dataSchemaNode) {
                 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
@@ -295,28 +295,28 @@ public class XmlDocumentUtils {
         return null;
     }
 
-    public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
-            Optional<XmlCodecProvider> codecProvider) {
+    public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
+            final Optional<XmlCodecProvider> codecProvider) {
         if (schema.isPresent()) {
             return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
         }
         return toDomNode(xmlElement);
     }
 
-    public static CompositeNode fromElement(Element xmlElement) {
+    public static CompositeNode fromElement(final Element xmlElement) {
         CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
         node.setQName(qNameFromElement(xmlElement));
 
         return node.toInstance();
     }
 
-    public static QName qNameFromElement(Element xmlElement) {
+    public static QName qNameFromElement(final Element xmlElement) {
         String namespace = xmlElement.getNamespaceURI();
         String localName = xmlElement.getLocalName();
         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
     }
 
-    private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         checkQName(xmlElement, schema.getQName());
         if (schema instanceof DataNodeContainer) {
             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
@@ -328,12 +328,12 @@ public class XmlDocumentUtils {
         return null;
     }
 
-    private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
+    private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
         return toNodeWithSchema(xmlElement, schema, codecProvider, null);
     }
 
-    protected static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
-            XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
+            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
         String text = xmlElement.getTextContent();
         Object value = null;
@@ -355,8 +355,8 @@ public class XmlDocumentUtils {
         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
     }
 
-    private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
-            XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
+            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
         String text = xmlElement.getTextContent();
         Object value = null;
@@ -374,8 +374,8 @@ public class XmlDocumentUtils {
         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
     }
 
-    private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
-            XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
+            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
         return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
@@ -383,10 +383,11 @@ public class XmlDocumentUtils {
 
     public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
 
-    public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
+    public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
         Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
-        if(attributeNodeNS == null)
-            return Optional.absent();
+        if(attributeNodeNS == null) {
+                       return Optional.absent();
+               }
 
         ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
         Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
@@ -394,12 +395,12 @@ public class XmlDocumentUtils {
         return Optional.of(action);
     }
 
-    private static void checkQName(Element xmlElement, QName qName) {
+    private static void checkQName(final Element xmlElement, final QName qName) {
         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
     }
 
-    public static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
+    public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Set<DataSchemaNode> dataSchemaNode) {
         if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
             for (DataSchemaNode dsn : dataSchemaNode) {
                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
@@ -417,11 +418,11 @@ public class XmlDocumentUtils {
         return Optional.absent();
     }
 
-    public static Node<?> toDomNode(Document doc) {
+    public static Node<?> toDomNode(final Document doc) {
         return toDomNode(doc.getDocumentElement());
     }
 
-    private static Node<?> toDomNode(Element element) {
+    private static Node<?> toDomNode(final Element element) {
         QName qname = qNameFromElement(element);
 
         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
@@ -447,11 +448,11 @@ public class XmlDocumentUtils {
         return ImmutableCompositeNode.create(qname, values.build());
     }
 
-    public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,SchemaContext schemaCtx) {
+    public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,final SchemaContext schemaCtx) {
         return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
 
             @Override
-            public Optional<Node<?>> apply(ElementWithSchemaContext input) {
+            public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
                 if (context.isPresent()) {
                     QName partialQName = qNameFromElement(input.getElement());
                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
@@ -493,7 +494,7 @@ public class XmlDocumentUtils {
      *         Element with equal notification QName defined in XML Document.
      */
     public static CompositeNode notificationToDomNodes(final Document document,
-            final Optional<Set<NotificationDefinition>> notifications, SchemaContext schemaCtx) {
+            final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
         if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
             final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
             for (int i = 0; i < originChildNodes.getLength(); i++) {
@@ -532,7 +533,7 @@ public class XmlDocumentUtils {
         return Optional.<NotificationDefinition>absent();
     }
 
-    private static final <T> List<T> forEachChild(NodeList nodes, SchemaContext schemaContext, Function<ElementWithSchemaContext, Optional<T>> forBody) {
+    private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
         ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
         for (int i = 0; i < nodes.getLength(); i++) {
             org.w3c.dom.Node child = nodes.item(i);
index fcec7afc214a5967d3c7099e76c3b7fee50cd8f3..a127bc5e0b467fe472c6ea93a4a8f2ec3585478a 100644 (file)
@@ -13,7 +13,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedAttrNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueAttrNode;
 
 public class ImmutableLeafNodeBuilder<T> extends AbstractImmutableNormalizedNodeBuilder<InstanceIdentifier.NodeIdentifier, T, LeafNode<T>> {
 
@@ -26,7 +26,7 @@ public class ImmutableLeafNodeBuilder<T> extends AbstractImmutableNormalizedNode
         return new ImmutableLeafNode<>(getNodeIdentifier(), getValue(), getAttributes());
     }
 
-    private static final class ImmutableLeafNode<T> extends AbstractImmutableNormalizedAttrNode<InstanceIdentifier.NodeIdentifier, T> implements LeafNode<T> {
+    private static final class ImmutableLeafNode<T> extends AbstractImmutableNormalizedValueAttrNode<InstanceIdentifier.NodeIdentifier, T> implements LeafNode<T> {
 
         ImmutableLeafNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier, final T value, final Map<QName, String> attributes) {
             super(nodeIdentifier, value, attributes);
index fd5cf52678ecd92f248c0d8493ca3a2579187e68..ba351f13481c7491c963f5063dc6ed17931d2b5c 100644 (file)
@@ -12,7 +12,7 @@ import java.util.Map;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedAttrNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueAttrNode;
 
 import com.google.common.base.Preconditions;
 
@@ -27,7 +27,7 @@ public class ImmutableLeafSetEntryNodeBuilder<T> extends AbstractImmutableNormal
         return new ImmutableLeafSetEntryNode<>(getNodeIdentifier(), getValue(), getAttributes());
     }
 
-    private static final class ImmutableLeafSetEntryNode<T> extends AbstractImmutableNormalizedAttrNode<InstanceIdentifier.NodeWithValue, T> implements LeafSetEntryNode<T> {
+    private static final class ImmutableLeafSetEntryNode<T> extends AbstractImmutableNormalizedValueAttrNode<InstanceIdentifier.NodeWithValue, T> implements LeafSetEntryNode<T> {
 
         ImmutableLeafSetEntryNode(final InstanceIdentifier.NodeWithValue nodeIdentifier, final T value, final Map<QName, String> attributes) {
             super(nodeIdentifier, value, attributes);
index dfc6be4a18a65246d3c32b2a180536e4dd644b86..6d04d5989cd41cb2a965425a2a1ec6f01b5e7f55 100644 (file)
@@ -8,11 +8,12 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import java.util.Collections;
-import java.util.LinkedHashMap;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.MapAdaptor;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
@@ -22,25 +23,23 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueNode;
 
 import com.google.common.base.Optional;
 import com.google.common.collect.Iterables;
 
 public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSetEntryNode<T>> {
 
-    private Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> value;
+    private final Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> value;
     private InstanceIdentifier.NodeIdentifier nodeIdentifier;
-    private boolean dirty;
 
     protected ImmutableLeafSetNodeBuilder() {
-        value = new LinkedHashMap<>();
-        dirty = false;
+        value = new HashMap<>();
     }
 
     protected ImmutableLeafSetNodeBuilder(final ImmutableLeafSetNode<T> node) {
         nodeIdentifier = node.getIdentifier();
-        value = node.getChildren();
-        dirty = true;
+        value = MapAdaptor.getDefaultInstance().takeSnapshot(node.children);
     }
 
     public static <T> ListNodeBuilder<T, LeafSetEntryNode<T>> create() {
@@ -55,31 +54,21 @@ public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSe
         return new ImmutableLeafSetNodeBuilder<T>((ImmutableLeafSetNode<T>) node);
     }
 
-    private void checkDirty() {
-        if (dirty) {
-            value = new LinkedHashMap<>(value);
-            dirty = false;
-        }
-    }
-
     @Override
     public ListNodeBuilder<T, LeafSetEntryNode<T>> withChild(final LeafSetEntryNode<T> child) {
-        checkDirty();
         this.value.put(child.getIdentifier(), child);
         return this;
     }
 
     @Override
     public ListNodeBuilder<T, LeafSetEntryNode<T>> withoutChild(final PathArgument key) {
-        checkDirty();
         this.value.remove(key);
         return this;
     }
 
     @Override
     public LeafSetNode<T> build() {
-        dirty = true;
-        return new ImmutableLeafSetNode<>(nodeIdentifier, value);
+        return new ImmutableLeafSetNode<>(nodeIdentifier, MapAdaptor.getDefaultInstance().optimize(value));
     }
 
     @Override
@@ -91,7 +80,6 @@ public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSe
 
     @Override
     public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final List<LeafSetEntryNode<T>> value) {
-        checkDirty();
         for (final LeafSetEntryNode<T> leafSetEntry : value) {
             withChild(leafSetEntry);
         }
@@ -114,7 +102,7 @@ public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSe
     }
 
     protected final static class ImmutableLeafSetNode<T> extends
-            AbstractImmutableNormalizedNode<InstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
+            AbstractImmutableNormalizedValueNode<InstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
             Immutable, LeafSetNode<T> {
 
         private final Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children;
@@ -135,10 +123,6 @@ public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSe
             return children.hashCode();
         }
 
-        private Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> getChildren() {
-            return Collections.unmodifiableMap(children);
-        }
-
         @Override
         protected boolean valueEquals(final AbstractImmutableNormalizedNode<?, ?> other) {
             return children.equals(((ImmutableLeafSetNode<?>) other).children);
index c7c58e1899942c016bd4f4bc906ae886eaf08e07..4a52f95d3ec12ba201df1d115c323bd02f19097d 100644 (file)
@@ -7,11 +7,12 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
-import java.util.LinkedHashMap;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.MapAdaptor;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
@@ -27,19 +28,16 @@ import com.google.common.collect.Iterables;
 public class ImmutableMapNodeBuilder
         implements CollectionNodeBuilder<MapEntryNode, MapNode> {
 
-    private Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> value;
+    private final Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> value;
     private InstanceIdentifier.NodeIdentifier nodeIdentifier;
-    private boolean dirty = false;
 
     protected ImmutableMapNodeBuilder() {
-        this.value = new LinkedHashMap<>();
-        this.dirty = false;
+        this.value = new HashMap<>();
     }
 
     protected ImmutableMapNodeBuilder(final ImmutableMapNode node) {
         this.nodeIdentifier = node.getIdentifier();
-        this.value = node.children;
-        this.dirty = true;
+        this.value = MapAdaptor.getDefaultInstance().takeSnapshot(node.children);
     }
 
     public static CollectionNodeBuilder<MapEntryNode, MapNode> create() {
@@ -54,23 +52,14 @@ public class ImmutableMapNodeBuilder
         return new ImmutableMapNodeBuilder((ImmutableMapNode) node);
     }
 
-    private void checkDirty() {
-        if (dirty) {
-            value = new LinkedHashMap<>(value);
-            dirty = false;
-        }
-    }
-
     @Override
     public CollectionNodeBuilder<MapEntryNode, MapNode> withChild(final MapEntryNode child) {
-        checkDirty();
         this.value.put(child.getIdentifier(), child);
         return this;
     }
 
     @Override
     public CollectionNodeBuilder<MapEntryNode, MapNode> withoutChild(final InstanceIdentifier.PathArgument key) {
-        checkDirty();
         this.value.remove(key);
         return this;
     }
@@ -93,8 +82,7 @@ public class ImmutableMapNodeBuilder
 
     @Override
     public MapNode build() {
-        dirty = true;
-        return new ImmutableMapNode(nodeIdentifier, value);
+        return new ImmutableMapNode(nodeIdentifier, MapAdaptor.getDefaultInstance().optimize(value));
     }
 
     @Override
@@ -116,7 +104,7 @@ public class ImmutableMapNodeBuilder
 
         ImmutableMapNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier,
                          final Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children) {
-            super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+            super(nodeIdentifier);
             this.children = children;
         }
 
@@ -125,6 +113,11 @@ public class ImmutableMapNodeBuilder
             return Optional.fromNullable(children.get(child));
         }
 
+               @Override
+               public Iterable<MapEntryNode> getValue() {
+                       return Iterables.unmodifiableIterable(children.values());
+               }
+
         @Override
         protected int valueHashCode() {
             return children.hashCode();
index d66f0228953bf4f171cc2ea41401f5f216d7ac9d..c440bd7f8d747a7adacd89cb1c60e7f04608b529 100644 (file)
@@ -122,7 +122,7 @@ public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T,
 
         ImmutableOrderedLeafSetNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier,
                 final Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children) {
-            super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+            super(nodeIdentifier);
             this.children = children;
         }
 
@@ -155,6 +155,11 @@ public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T,
             // TODO Auto-generated method stub
             return 0;
         }
+
+               @Override
+               public Iterable<LeafSetEntryNode<T>> getValue() {
+                       return Iterables.unmodifiableIterable(children.values());
+               }
     }
 
     @Override
index 3f9e4d5f12ae029b6bd00199baa13c6e219af291..ca0ea95365da2341e3277c5b579e1114b0a86b70 100644 (file)
@@ -116,7 +116,7 @@ public class ImmutableOrderedMapNodeBuilder
 
         ImmutableOrderedMapNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier,
                          final Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children) {
-            super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+            super(nodeIdentifier);
             this.children = children;
         }
 
@@ -144,5 +144,10 @@ public class ImmutableOrderedMapNodeBuilder
         public int getSize() {
             return children.size();
         }
+
+               @Override
+               public Iterable<MapEntryNode> getValue() {
+                       return Iterables.unmodifiableIterable(children.values());
+               }
     }
 }
index 498b65824599fcf0c48ea91d6f9544a357402c70..274b781d3e66fded64bdf5485dada1f47561c20f 100644 (file)
@@ -19,6 +19,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueNode;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
@@ -109,7 +110,7 @@ public class ImmutableUnkeyedListNodeBuilder implements CollectionNodeBuilder<Un
     }
 
     protected static final class ImmutableUnkeyedListNode extends
-            AbstractImmutableNormalizedNode<InstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>>
+            AbstractImmutableNormalizedValueNode<InstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>>
             implements Immutable, UnkeyedListNode {
 
         private final ImmutableList<UnkeyedListEntryNode> children;
index 7c7d53d61ac210a77bc7a5dc7c7d3e29a5f3b334..438b05c7da3af2bab1424fba7e56b00c80a007e7 100644 (file)
@@ -26,7 +26,7 @@ public abstract class AbstractImmutableDataContainerNode<K extends PathArgument>
 
     public AbstractImmutableDataContainerNode(
             final Map<PathArgument, DataContainerChild<? extends PathArgument, ?>> children, final K nodeIdentifier) {
-        super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+        super(nodeIdentifier);
         this.children = children;
     }
 
@@ -35,6 +35,11 @@ public abstract class AbstractImmutableDataContainerNode<K extends PathArgument>
         return Optional.<DataContainerChild<? extends PathArgument, ?>> fromNullable(children.get(child));
     }
 
+    @Override
+    public final Iterable<DataContainerChild<? extends PathArgument, ?>> getValue() {
+        return Iterables.unmodifiableIterable(children.values());
+    }
+
     @Override
     protected int valueHashCode() {
         return children.hashCode();
index 708f9225c2f29c640db725b4550b2d5386d2a6cf..14b0f419297352315c71d5b2517395fee7e7cfb8 100644 (file)
@@ -21,11 +21,9 @@ public abstract class AbstractImmutableNormalizedNode<K extends InstanceIdentifi
         implements NormalizedNode<K, V>, Immutable {
 
     private final K nodeIdentifier;
-    private final V value;
 
-    protected AbstractImmutableNormalizedNode(final K nodeIdentifier, final V value) {
+    protected AbstractImmutableNormalizedNode(final K nodeIdentifier) {
         this.nodeIdentifier = Preconditions.checkNotNull(nodeIdentifier, "nodeIdentifier");
-        this.value = Preconditions.checkNotNull(value, "value");
     }
 
     @Override
@@ -48,11 +46,6 @@ public abstract class AbstractImmutableNormalizedNode<K extends InstanceIdentifi
         return getNodeType();
     }
 
-    @Override
-    public final V getValue() {
-        return value;
-    }
-
     @Override
     public final V setValue(final V value) {
         throw new UnsupportedOperationException("Immutable");
@@ -16,13 +16,13 @@ import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import com.google.common.base.Objects.ToStringHelper;
 import com.google.common.collect.ImmutableMap;
 
-public abstract class AbstractImmutableNormalizedAttrNode<K extends InstanceIdentifier.PathArgument,V>
-        extends AbstractImmutableNormalizedNode<K, V>
+public abstract class AbstractImmutableNormalizedValueAttrNode<K extends InstanceIdentifier.PathArgument,V>
+        extends AbstractImmutableNormalizedValueNode<K, V>
         implements AttributesContainer {
 
     private final Map<QName, String> attributes;
 
-    protected AbstractImmutableNormalizedAttrNode(final K nodeIdentifier, final V value, final Map<QName, String> attributes) {
+    protected AbstractImmutableNormalizedValueAttrNode(final K nodeIdentifier, final V value, final Map<QName, String> attributes) {
         super(nodeIdentifier, value);
         this.attributes = ImmutableMap.copyOf(attributes);
     }
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableNormalizedValueNode.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableNormalizedValueNode.java
new file mode 100644 (file)
index 0000000..16ca637
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * 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.yang.data.impl.schema.nodes;
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+
+import com.google.common.base.Preconditions;
+
+public abstract class AbstractImmutableNormalizedValueNode<K extends InstanceIdentifier.PathArgument,V>
+        extends AbstractImmutableNormalizedNode<K, V> {
+
+    private final V value;
+
+    protected AbstractImmutableNormalizedValueNode(final K nodeIdentifier, final V value) {
+       super(nodeIdentifier);
+        this.value = Preconditions.checkNotNull(value, "value");
+    }
+
+    @Override
+    public final V getValue() {
+        return value;
+    }
+}
index 6ac17cdc03290ac6eb15552e1abdc0fa67301624..209f3665b708eeaee3e9d677d4cacbfac08da12a 100644 (file)
@@ -61,8 +61,8 @@ public class LazyNodeToNodeMapTest {
         Assert.assertEquals(2, lazyN2N.getKeyNodes().size());
 
         Assert.assertEquals(mutableTree, subMutant.getParent());
-        Assert.assertEquals(mutableTree.getChildren().size(), 1);
-        Assert.assertEquals(mutableTree.getChildren().iterator().next(), subMutant);
+        Assert.assertEquals(mutableTree.getValue().size(), 1);
+        Assert.assertEquals(mutableTree.getValue().iterator().next(), subMutant);
     }
 
     /**
index d9531d4225218fda7f293402a41ac145fb8869ee..9c58b9f92bfe5f813424d85fd9c342af6b5ad458 100644 (file)
@@ -34,15 +34,15 @@ public class MyNodeBuilder extends BuilderSupport {
             .getLogger(MyNodeBuilder.class);
 
     private URI qnNamespace;
-    private String qnPrefix;
-    private Date qnRevision;
+    private final String qnPrefix;
+    private final Date qnRevision;
 
     private CompositeNode rootNode;
 
        /**
         * @param baseQName
         */
-       private MyNodeBuilder(QName baseQName) {
+       private MyNodeBuilder(final QName baseQName) {
                qnNamespace = baseQName.getNamespace();
                qnPrefix = baseQName.getPrefix();
                qnRevision = baseQName.getRevision();
@@ -64,7 +64,7 @@ public class MyNodeBuilder extends BuilderSupport {
     }
 
     @Override
-    protected void setParent(Object parent, Object child) {
+    protected void setParent(final Object parent, final Object child) {
        // do nothing
         if (child instanceof AbstractNodeTO<?>) {
             ((AbstractNodeTO<?>) child).setParent((CompositeNode) parent);
@@ -74,7 +74,7 @@ public class MyNodeBuilder extends BuilderSupport {
     }
 
     @Override
-    protected Object createNode(Object name) {
+    protected Object createNode(final Object name) {
         MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
                 createQName(name), getCurrentNode(), null, null, null);
         NodeUtils.fixParentRelation(newNode);
@@ -82,7 +82,7 @@ public class MyNodeBuilder extends BuilderSupport {
     }
 
     @Override
-    protected Object createNode(Object name, @SuppressWarnings("rawtypes") Map attributes) {
+    protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes) {
         ModifyAction modifyAction = processAttributes(attributes);
         MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
                 createQName(name), getCurrentNode(), null, modifyAction, null);
@@ -92,7 +92,7 @@ public class MyNodeBuilder extends BuilderSupport {
 
 
     @Override
-    protected Object createNode(Object name, @SuppressWarnings("rawtypes") Map attributes, Object value) {
+    protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes, final Object value) {
         ModifyAction modifyAction = processAttributes(attributes);
         SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(
                 createQName(name), (CompositeNode) getCurrent(), value, modifyAction);
@@ -104,7 +104,7 @@ public class MyNodeBuilder extends BuilderSupport {
      * @param attributes
      * @return
      */
-    private ModifyAction processAttributes(@SuppressWarnings("rawtypes") Map attributes) {
+    private ModifyAction processAttributes(@SuppressWarnings("rawtypes") final Map attributes) {
         LOG.debug("attributes:" + attributes);
         ModifyAction modAction = null;
 
@@ -131,13 +131,13 @@ public class MyNodeBuilder extends BuilderSupport {
     }
 
     @Override
-    protected Object createNode(Object name, Object value) {
+    protected Object createNode(final Object name, final Object value) {
         SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(createQName(name), (CompositeNode) getCurrent(), value);
         NodeUtils.fixParentRelation(newNode);
         return newNode;
     }
 
-    private QName createQName(Object localName) {
+    private QName createQName(final Object localName) {
        LOG.debug("qname for: "+localName);
            return new QName(qnNamespace, qnRevision, qnPrefix, (String) localName);
     }
@@ -157,7 +157,7 @@ public class MyNodeBuilder extends BuilderSupport {
     }
 
        @Override
-       protected Object postNodeCompletion(Object parent, Object node) {
+       protected Object postNodeCompletion(final Object parent, final Object node) {
            Node<?> nodeRevisited = (Node<?>) node;
            LOG.debug("postNodeCompletion at: \n  "+ nodeRevisited+"\n  "+parent);
            if (nodeRevisited instanceof MutableCompositeNode) {
@@ -173,7 +173,7 @@ public class MyNodeBuilder extends BuilderSupport {
                    rootNode = (CompositeNode) nodeRevisited;
                } else {
                    NodeUtils.fixParentRelation(nodeRevisited);
-                   nodeRevisited.getParent().getChildren().remove(mutant);
+                   nodeRevisited.getParent().getValue().remove(mutant);
                }
            }
 
index 9b5edc99eacc85a8f490ffc17828e64e472ae0c4..ed6d709c35216a6a61768a3dba23784752835d1c 100644 (file)
@@ -60,7 +60,7 @@ public class NodeFactoryTest {
      */
     @Test
     public void testImmutableNodes() throws Exception {
-        Assert.assertEquals(2, network.getChildren().size());
+        Assert.assertEquals(2, network.getValue().size());
         CompositeNode tpList = NodeUtils.findNodeByXpath(networkShadow,
                 NodeHelper.AddNamespaceToPattern(
                         "//{0}node[{0}node-id/text()='nodeId_19']/{0}termination-points", ns));
@@ -120,7 +120,7 @@ public class NodeFactoryTest {
         Document shadowConfig = NodeUtils.buildShadowDomTree(root);
         NodeHelper.compareXmlTree(shadowConfig, "./mutableNodesConfig.xml", getClass());
 
-        Assert.assertEquals(1, root.getChildren().size());
+        Assert.assertEquals(1, root.getValue().size());
         Assert.assertEquals(1, ifNode.getSimpleNodesByName("name").size());
         Assert.assertEquals(1, ifNode.getSimpleNodesByName("mtu").size());
         Assert.assertEquals(2, topNode.getCompositesByName("interface").size());
index eb5df99258489456910f640680c33664fc03955b..02fe73d2abbd20e61ffca36f707f2b369621992a 100644 (file)
@@ -129,7 +129,7 @@ public abstract class NodeHelper {
       "    </network-elements>\n" +
       "</network>";
 
-    private static String domTreeString(Document domTree) throws TransformerException {
+    private static String domTreeString(final Document domTree) throws TransformerException {
         TransformerFactory transformerFact = TransformerFactory.newInstance();
         transformerFact.setAttribute("indent-number", 4);
         Transformer transformer = transformerFact.newTransformer();
@@ -146,11 +146,11 @@ public abstract class NodeHelper {
      * @param out
      * @throws Exception
      */
-    private static void dumpDoc(Document domTree, PrintStream out) throws Exception {
+    private static void dumpDoc(final Document domTree, final PrintStream out) throws Exception {
       out.println(domTreeString(domTree));
     }
 
-       public static void dumpDoc(Document domTree, Logger logger) throws TransformerException {
+       public static void dumpDoc(final Document domTree, final Logger logger) throws TransformerException {
                logger.info("{}", domTreeString(domTree));
        }
 
@@ -158,7 +158,7 @@ public abstract class NodeHelper {
      * @param qName
      * @return example tree, see {@link #NETWORK_XML}
      */
-    public static CompositeNode buildTestConfigTree(QName qName) {
+    public static CompositeNode buildTestConfigTree(final QName qName) {
         List<Node<?>> value = new ArrayList<Node<?>>();
         value.add(NodeFactory.createImmutableSimpleNode(new QName(qName, "element-id"), null, "ntElementId_09"));
         CompositeNode ntElementNode1 = NodeFactory.createImmutableCompositeNode(new QName(qName, "network-element"), null, value);
@@ -330,8 +330,8 @@ public abstract class NodeHelper {
     /**
      * @param parentNode
      */
-    public static void assignParentToChildren(CompositeNode parentNode) {
-        for (Node<?> child : parentNode.getChildren()) {
+    public static void assignParentToChildren(final CompositeNode parentNode) {
+        for (Node<?> child : parentNode.getValue()) {
             ((AbstractNodeTO<?>) child).setParent(parentNode);
         }
     }
@@ -356,7 +356,7 @@ public abstract class NodeHelper {
      * @return tree root
      * @throws Exception
      */
-    public static CompositeNode loadConfigByGroovy(String scriptName) throws Exception {
+    public static CompositeNode loadConfigByGroovy(final String scriptName) throws Exception {
        InputStream configStream = NodeHelper.class.getResourceAsStream(scriptName);
        Binding binding = new Binding();
        GroovyShell gShell = new GroovyShell(binding);
@@ -378,7 +378,7 @@ public abstract class NodeHelper {
      * @param nsArg , e.g.: <pre>{"uri:ns1", "uri:ns2"}</pre>
      * @return pattern with namespaces: <pre>//uri:ns1:network/uri:ns2:xx[text() = ''sss'']"</pre>
      */
-    public static String AddNamespaceToPattern(String pattern, Object... nsArg) {
+    public static String AddNamespaceToPattern(final String pattern, final Object... nsArg) {
         Object[] ns = nsArg;
         String patternNs = pattern.replaceAll("'", "''");
         if (ns == null) {
@@ -399,7 +399,7 @@ public abstract class NodeHelper {
      * @throws SAXException
      * @throws IOException
      */
-    public static void compareXmlTree(Document tree, String xmlFile, Class<?> clazz) throws Exception,
+    public static void compareXmlTree(final Document tree, final String xmlFile, final Class<?> clazz) throws Exception,
             SAXException, IOException {
         ByteArrayOutputStream actualRaw = new ByteArrayOutputStream();
         dumpDoc(tree, new PrintStream(actualRaw));
index cccb7837be2f0c5076d11c68f9fc93f4532bcdad..285cdb0b30705e3128c76fe282a91586b62fbad7 100644 (file)
@@ -111,7 +111,7 @@ public class NodeUtilsTest {
         CompositeNode topology = network.getCompositesByName("topologies").iterator().next()
             .getCompositesByName("topology").iterator().next();
 
-        Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getChildren());
+        Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getValue());
         Assert.assertEquals(3, nodeMap.size());
     }
 
@@ -144,13 +144,13 @@ public class NodeUtilsTest {
        NodeHelper.compareXmlTree(shadowTree, "./config02g-shadow.xml", getClass());
     }
 
-    private static void checkFamilyBinding(CompositeNode treeRoot) throws Exception {
+    private static void checkFamilyBinding(final CompositeNode treeRoot) throws Exception {
         Stack<CompositeNode> jobQueue = new Stack<>();
         jobQueue.push(treeRoot);
 
         while (!jobQueue.isEmpty()) {
             CompositeNode job = jobQueue.pop();
-            for (Node<?> child : job.getChildren()) {
+            for (Node<?> child : job.getValue()) {
                 if (child instanceof CompositeNode) {
                     jobQueue.push((CompositeNode) child);
                 }
index b302c84b9974aef69eb172ca1b497515646efd11..0d7445da70f4b38b8fcf091b50f808b9b9d070fd 100644 (file)
@@ -34,10 +34,10 @@ import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 public class XmlTreeBuilderTest {
 
        private InputStream inputStream;
-       
+
        /**
         * Perform pre-test initialization
-        * 
+        *
         * @throws Exception
         */
        @Before
@@ -61,42 +61,42 @@ public class XmlTreeBuilderTest {
                }
                assertNotNull(rootNode);
                assertTrue(rootNode instanceof CompositeNode);
-               
+
                CompositeNode compRootNode = (CompositeNode)rootNode;
-               assertNotNull(compRootNode.getChildren());
-               
+               assertNotNull(compRootNode.getValue());
+
                SimpleNode<String> methodName = null;
                SimpleNode<String> emptyTag = null;
                CompositeNode params = null;
-               for (final Node<?> childNode : compRootNode.getChildren()) {
+               for (final Node<?> childNode : compRootNode.getValue()) {
                        if (childNode instanceof SimpleNode) {
                                if ("emptyTag".equals(childNode.getNodeType().getLocalName())) {
                                        emptyTag = (SimpleNode<String>) childNode;
                                } else if ("methodName".equals(childNode.getNodeType().getLocalName())) {
                                        methodName = (SimpleNode<String>) childNode;
                                }
-                               
+
                        } else if (childNode instanceof CompositeNode) {
                                params = (CompositeNode) childNode;
                        }
                }
-               
+
                assertNotNull(methodName);
                assertNotNull(params);
                assertTrue(emptyTag.getValue().isEmpty());
                assertEquals(methodName.getValue(), "getDeviceEquipment");
-               
+
                String deviceId = null;
                String deviceIP = null;
-               for (final Node<?> param : params.getChildren()) {
+               for (final Node<?> param : params.getValue()) {
                        if (param instanceof CompositeNode) {
-                               final Node<?> valueNode = ((CompositeNode) param).getChildren().get(0);
-                               
+                               final Node<?> valueNode = ((CompositeNode) param).getValue().get(0);
+
                                assertTrue(valueNode instanceof CompositeNode);
                                final CompositeNode value = (CompositeNode) valueNode;
-                               final Node<?> stringNode = value.getChildren().get(0);
+                               final Node<?> stringNode = value.getValue().get(0);
                                assertTrue(stringNode instanceof SimpleNode);
-                               
+
                                final SimpleNode<String> string = (SimpleNode<String>) stringNode;
                                if ("DeviceID123".equals(string.getValue())) {
                                        deviceId = string.getValue();
@@ -105,11 +105,11 @@ public class XmlTreeBuilderTest {
                                }
                        }
                }
-               
+
                assertNotNull(deviceId);
                assertNotNull(deviceIP);
        }
-       
+
        @Test
        public void nodeMapInCompositeNodeTest() {
            Node<?> rootNode = null;
@@ -118,7 +118,7 @@ public class XmlTreeBuilderTest {
             } catch (XMLStreamException e) {
                     e.printStackTrace();
             }
-            
+
             CompositeNode compRootNode = (CompositeNode)rootNode;
             List<CompositeNode> params = compRootNode.getCompositesByName("params");
             assertEquals(1, params.size());
index cae5136a40f75867d97cd56829818b7649028177..401c009fd4b4e64bf015cf91fb99e515b8c010c1 100644 (file)
@@ -12,6 +12,7 @@ import java.util.Set;
 import org.opendaylight.yangtools.yang.common.QName;
 
 /**
+ *
  * The ChoiceNode defines a set of alternatives. It consists of a number of
  * branches defined as ChoiceCaseNode objects.
  */
@@ -19,7 +20,7 @@ public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
 
     /**
      * Returns cases of choice.
-     * 
+     *
      * @return set of ChoiceCaseNode objects defined in this node which
      *         represents set of arguments of the YANG <code>case</code>
      *         substatement of the <code>choice</code> statement
@@ -27,9 +28,9 @@ public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
     Set<ChoiceCaseNode> getCases();
 
     /**
-     * 
+     *
      * Returns the concrete case according to specified Q name.
-     * 
+     *
      * @param name
      *            QName of seeked Choice Case Node
      * @return child case node of this Choice if child with given name is
@@ -39,7 +40,7 @@ public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
 
     /**
      * Returns the concrete case according to specified name.
-     * 
+     *
      * @param name
      *            name of seeked child as String
      * @return child case node (or local name of case node) of this Choice if
@@ -48,9 +49,9 @@ public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
     ChoiceCaseNode getCaseNodeByName(String name);
 
     /**
-     * 
+     *
      * Returns name of case which is in the choice specified as default
-     * 
+     *
      * @return string with the name of case which is specified in the argument
      *         of the YANG <code>default</code> substatement of
      *         <code>choice</code> statement.
index 6b3f4703bad31618a11eaad5573774adee47cc9b..ab8ae21cafd9010502fd3496ff6e5bb4b5763152 100644 (file)
@@ -8,10 +8,22 @@
 package org.opendaylight.yangtools.yang.model.api;
 
 /**
+ *
+ * Data Schema Node represents abstract supertype from which all data tree
+ * definitions are derived.
  *
  * Contains the method which are used for getting metadata from the schema nodes
  * which contains data.
  *
+ * @see ContainerSchemaNode
+ * @see ListSchemaNode
+ * @see LeafListSchemaNode
+ * @see ChoiceNode
+ * @see ChoiceCaseNode
+ * @see LeafSchemaNode
+ * @see AnyXmlSchemaNode
+ *
+ *
  */
 public interface DataSchemaNode extends SchemaNode {
 
index 16fda82ed4761af26b7c381b54a4fdb32f4ebe8e..22456181507f07da9b16c3ff7754ae0a9f489e07 100644 (file)
@@ -158,7 +158,7 @@ public interface Module extends DataNodeContainer, SourceStreamAware, ModuleIden
      * @return set of the augmentation schema instances which are specified in
      *         the module as YANG {@link Module <b><font
      *         color="#dc143c">augment</font></b>} keyword and are
-     *         lexicographicaly ordered
+     *         lexicographically ordered
      */
     Set<AugmentationSchema> getAugmentations();
 
@@ -188,7 +188,7 @@ public interface Module extends DataNodeContainer, SourceStreamAware, ModuleIden
      * @return set of identity schema node instances which are specified in the
      *         module as YANG {@link Module <b><font
      *         color="#bdb76b">identity</font></b>} keywords and are
-     *         lexicographicaly ordered
+     *         lexicographically ordered
      */
     Set<IdentitySchemaNode> getIdentities();
 
@@ -199,7 +199,7 @@ public interface Module extends DataNodeContainer, SourceStreamAware, ModuleIden
      * @return set of extension definition instances which are specified in the
      *         module as YANG {@link Module <b><font
      *         color="#808000">extension</font></b>} keyword and are
-     *         lexicographicaly ordered
+     *         lexicographically ordered
      */
     List<ExtensionDefinition> getExtensionSchemaNodes();
 
index 51eb64159301e5a4998df1438de97909f6ad9fea..6d13ee5f2f45ba2d60ae591050033a5ef25a3cd8 100644 (file)
@@ -7,22 +7,33 @@
  */
 package org.opendaylight.yangtools.yang.model.api;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import java.util.Arrays;
 import java.util.List;
-
 import org.opendaylight.yangtools.yang.common.QName;
 
-import com.google.common.collect.ImmutableList;
-
 /**
  *
  * Represents unique path to the every node inside the module.
  *
  */
 public class SchemaPath {
+    /**
+     * Shared instance of the conceptual root schema node.
+     */
+    public static final SchemaPath ROOT = new SchemaPath(ImmutableList.<QName> of(), true, null);
+
+    /**
+     * Shared instance of the "same" relative schema node.
+     */
+    public static final SchemaPath SAME = new SchemaPath(ImmutableList.<QName> of(), false, null);
+
     /**
      * List of QName instances which represents complete path to the node.
      */
-    private final List<QName> path;
+    private final ImmutableList<QName> path;
 
     /**
      * Boolean value which represents type of schema path (relative or
@@ -39,10 +50,12 @@ public class SchemaPath {
      * @param absolute
      *            boolean value which specifies if the path is absolute or
      *            relative
+     *
+     * @deprecated Use {@link #create(Iterable, boolean)} instead.
      */
+    @Deprecated
     public SchemaPath(final List<QName> path, final boolean absolute) {
-        this.path = ImmutableList.copyOf(path);
-        this.absolute = absolute;
+        this(ImmutableList.copyOf(path), absolute, null);
     }
 
     /**
@@ -50,11 +63,113 @@ public class SchemaPath {
      *
      * @return list of <code>QName</code> instances which represents complete
      *         path to schema node
+     *
+     * @deprecated Use {@link #getPathFromRoot()} instead.
      */
+    @Deprecated
     public List<QName> getPath() {
         return path;
     }
 
+    private SchemaPath(final ImmutableList<QName> path, final boolean absolute, final Void dummy) {
+        this.path = Preconditions.checkNotNull(path);
+        this.absolute = absolute;
+    }
+
+    /**
+     * Constructs new instance of this class with the concrete path.
+     *
+     * @param path
+     *            list of QName instances which specifies exact path to the
+     *            module node
+     * @param absolute
+     *            boolean value which specifies if the path is absolute or
+     *            relative
+     *
+     * @return A SchemaPath instance.
+     */
+    public static SchemaPath create(final Iterable<QName> path, final boolean absolute) {
+        if (Iterables.isEmpty(path)) {
+            return absolute ? ROOT : SAME;
+        } else {
+            return new SchemaPath(ImmutableList.copyOf(path), absolute, null);
+        }
+    }
+
+    /**
+     * Constructs new instance of this class with the concrete path.
+     *
+     * @param absolute
+     *            boolean value which specifies if the path is absolute or
+     *            relative
+     * @param path
+     *            one or more QName instances which specifies exact path to the
+     *            module node
+     *
+     * @return A SchemaPath instance.
+     */
+    public static SchemaPath create(final boolean absolute, final QName... path) {
+       return create(Arrays.asList(path), absolute);
+    }
+
+    /**
+     * Create a child path based on concatenation of this path and a relative path.
+     *
+     * @param relative Relative path
+     * @return A new child path
+     */
+    public SchemaPath createChild(final Iterable<QName> relative) {
+        if (Iterables.isEmpty(relative)) {
+            return this;
+        }
+        return create(Iterables.concat(path, relative), absolute);
+    }
+
+    /**
+     * Create a child path based on concatenation of this path and a relative path.
+     *
+     * @param relative Relative SchemaPath
+     * @return A new child path
+     */
+    public SchemaPath createChild(final SchemaPath relative) {
+        Preconditions.checkArgument(!relative.isAbsolute(), "Child creation requires relative path");
+        return createChild(relative.path);
+    }
+
+    /**
+     * Create a child path based on concatenation of this path and additional
+     * path elements.
+     *
+     * @param elements Relative SchemaPath elements
+     * @return A new child path
+     */
+    public SchemaPath createChild(final QName... elements) {
+        return createChild(Arrays.asList(elements));
+    }
+
+    /**
+     * Returns the list of nodes which need to be traversed to get from the
+     * starting point (root for absolute SchemaPaths) to the node represented
+     * by this object.
+     *
+     * @return list of <code>qname</code> instances which represents
+     *         path from the root to the schema node.
+     */
+    public Iterable<QName> getPathFromRoot() {
+        return path;
+    }
+
+    /**
+     * Returns the list of nodes which need to be traversed to get from this
+     * node to the starting point (root for absolute SchemaPaths).
+     *
+     * @return list of <code>qname</code> instances which represents
+     *         path from the schema node towards the root.
+     */
+    public Iterable<QName> getPathTowardsRoot() {
+        return path.reverse();
+    }
+
     /**
      * Describes whether schema path is|isn't absolute.
      *
@@ -70,7 +185,14 @@ public class SchemaPath {
         final int prime = 31;
         int result = 1;
         result = prime * result + absolute.hashCode();
-        result = prime * result + ((path == null) ? 0 : path.hashCode());
+
+        // TODO: Temporary fix for Bug 1076 - hash computation
+        // Which adds same behaviour as using List.hashCode().
+        int pathHash = 1;
+        for (Object o : path) {
+            pathHash = prime * pathHash + o.hashCode();
+        }
+        result = prime * result + pathHash;
         return result;
     }
 
@@ -89,14 +211,8 @@ public class SchemaPath {
         if (absolute != other.absolute) {
             return false;
         }
-        if (path == null) {
-            if (other.path != null) {
-                return false;
-            }
-        } else if (!path.equals(other.path)) {
-            return false;
-        }
-        return true;
+
+        return Iterables.elementsEqual(path, other.path);
     }
 
     @Override
index 61647ddbfa31204a05e1d62e0436f0915df4651e..6cfa27e6d3096df806fbf056f1529cac63d28993 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
@@ -18,6 +17,8 @@ import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 
+import com.google.common.base.Optional;
+
 /**
  * The Abstract Integer class defines implementation of IntegerTypeDefinition
  * interface which represents SIGNED Integer values defined in Yang language. <br>
@@ -43,22 +44,23 @@ abstract class AbstractSignedInteger implements IntegerTypeDefinition {
     private final List<RangeConstraint> rangeStatements;
 
     /**
-     * @param name
-     * @param description
-     * @param minRange
-     * @param maxRange
-     * @param units
+     * Construct SignedInteger
+     *
+     * @param name Name of type
+     * @param description Description of type
+     * @param minRange Minimal range
+     * @param maxRange Maxium range
+     * @param units Units
      */
-    public AbstractSignedInteger(final QName name, final String description, final Number minRange,
+    protected AbstractSignedInteger(final QName name, final String description, final Number minRange,
             final Number maxRange, final String units) {
         this.name = name;
-        this.path = new SchemaPath(Collections.singletonList(name), true);
+        this.path = SchemaPath.create(Collections.singletonList(name), true);
         this.description = description;
         this.units = units;
-        this.rangeStatements = new ArrayList<RangeConstraint>();
         final String rangeDescription = "Integer values between " + minRange + " and " + maxRange + ", inclusively.";
-        this.rangeStatements.add(BaseConstraints.rangeConstraint(minRange, maxRange, rangeDescription,
-                "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
+        this.rangeStatements = Collections.singletonList(BaseConstraints.newRangeConstraint(minRange, maxRange, Optional.of(rangeDescription),
+                Optional.of("https://tools.ietf.org/html/rfc6020#section-9.2.4")));
     }
 
     @Override
@@ -119,7 +121,7 @@ abstract class AbstractSignedInteger implements IntegerTypeDefinition {
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
index 270adad8cd7ebe43665fcf95ac05a3456846626c..b33392a7a0fcf1632694da9dee3510c7c4310d90 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
@@ -18,6 +17,8 @@ import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
 
+import com.google.common.base.Optional;
+
 /**
  * The Abstract Integer class defines implementation of IntegerTypeDefinition
  * interface which represents UNSIGNED Integer values defined in Yang language. <br>
@@ -44,21 +45,21 @@ abstract class AbstractUnsignedInteger implements UnsignedIntegerTypeDefinition
     private final List<RangeConstraint> rangeStatements;
 
     /**
+     * Construct Unsigned Integer
      *
-     * @param name
-     * @param description
-     * @param maxRange
-     * @param units
+     * @param name Name of type
+     * @param description Description of type
+     * @param maxRange Maximum value
+     * @param units Units
      */
     public AbstractUnsignedInteger(final QName name, final String description, final Number maxRange, final String units) {
         this.name = name;
-        this.path = new SchemaPath(Collections.singletonList(name), true);
+        this.path = SchemaPath.create(Collections.singletonList(name), true);
         this.description = description;
         this.units = units;
-        this.rangeStatements = new ArrayList<RangeConstraint>();
         final String rangeDescription = "Integer values between " + MIN_VALUE + " and " + maxRange + ", inclusively.";
-        this.rangeStatements.add(BaseConstraints.rangeConstraint(MIN_VALUE, maxRange, rangeDescription,
-                "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
+        this.rangeStatements = Collections.singletonList(BaseConstraints.newRangeConstraint(MIN_VALUE, maxRange, Optional.of(rangeDescription),
+                Optional.of("https://tools.ietf.org/html/rfc6020#section-9.2.4")));
     }
 
     @Override
@@ -119,7 +120,7 @@ abstract class AbstractUnsignedInteger implements UnsignedIntegerTypeDefinition
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
index c6ba5d619c0605e0d8dbab39ccb4d81b9f3d4687..7dd5fb402934afbb3caad6913c409e587caf1a59 100644 (file)
@@ -11,423 +11,172 @@ import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 
+import com.google.common.base.Optional;
+
+/**
+ * Utility class which provides factory methods to construct Constraints.
+ *
+ * Provides static factory methods which constructs instances of
+ * <ul>
+ * <li>{@link LengthConstraint} - {@link #lengthConstraint(Number, Number, String, String)}
+ * <li>{@link RangeConstraint} - {@link #rangeConstraint(Number, Number, String, String)}
+ * <li>{@link PatternConstraint} - {@link #patternConstraint(String, String, String)}
+ * </ul>
+ */
 public final class BaseConstraints {
 
     private BaseConstraints() {
     }
 
-    public static LengthConstraint lengthConstraint(final Number min, final Number max, final String description,
-            final String reference) {
+
+    /**
+     * Creates a {@link LengthConstraint}.
+     *
+     * Creates an instance of Length constraint based on supplied parameters
+     * with additional behaviour:
+     *
+     * <ul>
+     * <li>{@link LengthConstraint#getErrorAppTag()} returns <code>length-out-of-specified-bounds</code>
+     * <li>{@link LengthConstraint#getErrorMessage() returns <code>The argument is out of bounds &lt;<i>min</i>, <i>max</i> &gt;</code>
+     * </ul>
+     *
+     * @see LengthConstraint
+     *
+     * @param min  length-restricting lower bound value. The value MUST NOT be negative.
+     * @param max length-restricting upper bound value. The value MUST NOT be negative.
+     * @param description Description associated with constraint. {@link Optional#absent()} if description is undefined.
+     * @param reference Reference associated with constraint. {@link Optional#absent()} if reference is undefined.
+     * @return Instance of {@link LengthConstraint}
+     */
+    public static LengthConstraint newLengthConstraint(final Number min, final Number max, final Optional<String> description,
+            final Optional<String> reference) {
         return new LengthConstraintImpl(min, max, description, reference);
     }
 
-    public static RangeConstraint rangeConstraint(final Number min, final Number max, final String description,
-            final String reference) {
+    /**
+     * Creates a {@link RangeConstraint}.
+     *
+     * Creates an instance of Range constraint based on supplied parameters
+     * with additional behaviour:
+     *
+     * <ul>
+     * <li>{@link RangeConstraint#getErrorAppTag()} returns <code>range-out-of-specified-bounds</code>
+     * <li>{@link RangeConstraint#getErrorMessage() returns <code>The argument is out of bounds &lt;<i>min</i>, <i>max</i> &gt;</code>
+     * </ul>
+     *
+     *
+     * @see RangeConstraint
+     *
+     * @param min value-restricting lower bound value. The value MUST NOT Be null.
+     * @param max value-restricting upper bound value. The value MUST NOT Be null.
+     * @param description Description associated with constraint. {@link Optional#absent()} if description is undefined.
+     * @param reference Reference associated with constraint. {@link Optional#absent()} if reference is undefined.
+     * @return Instance of {@link RangeConstraint}
+     */
+    public static RangeConstraint newRangeConstraint(final Number min, final Number max, final Optional<String> description,
+            final Optional<String> reference) {
         return new RangeConstraintImpl(min, max, description, reference);
     }
 
-    public static PatternConstraint patternConstraint(final String pattern, final String description,
-            final String reference) {
+
+    /**
+     * Creates a {@link PatternConstraint}.
+     *
+     * Creates an instance of Pattern constraint based on supplied parameters
+     * with additional behaviour:
+     *
+     * <ul>
+     * <li>{@link PatternConstraint#getErrorAppTag()} returns <code>invalid-regular-expression</code>
+     * </ul>
+     *
+     * @see PatternConstraint
+     *
+     * @param pattern Regular expression, MUST NOT BE null.
+     * @param description Description associated with constraint.
+     * @param reference Reference associated with constraint.
+     * @returnInstance of {@link PatternConstraint}
+     */
+    public static PatternConstraint newPatternConstraint(final String pattern, final Optional<String> description,
+            final Optional<String> reference) {
         return new PatternConstraintImpl(pattern, description, reference);
     }
 
-    private static final class LengthConstraintImpl implements LengthConstraint {
-
-        private final Number min;
-        private final Number max;
-
-        private final String description;
-        private final String reference;
-
-        private final String errorAppTag;
-        private final String errorMessage;
 
-        public LengthConstraintImpl(Number min, Number max, final String description, final String reference) {
-            super();
-            this.min = min;
-            this.max = max;
-            this.description = description;
-            this.reference = reference;
-
-            this.errorAppTag = "length-out-of-specified-bounds";
-            this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
-        }
-
-        @Override
-        public String getDescription() {
-            return description;
-        }
-
-        @Override
-        public String getErrorAppTag() {
-            return errorAppTag;
-        }
-
-        @Override
-        public String getErrorMessage() {
-            return errorMessage;
-        }
-
-        @Override
-        public String getReference() {
-            return reference;
-        }
-
-        @Override
-        public Number getMin() {
-            return min;
-        }
-
-        @Override
-        public Number getMax() {
-            return max;
-        }
-
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((description == null) ? 0 : description.hashCode());
-            result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
-            result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
-            result = prime * result + ((max == null) ? 0 : max.hashCode());
-            result = prime * result + ((min == null) ? 0 : min.hashCode());
-            result = prime * result + ((reference == null) ? 0 : reference.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(final Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            final LengthConstraintImpl other = (LengthConstraintImpl) obj;
-            if (description == null) {
-                if (other.description != null) {
-                    return false;
-                }
-            } else if (!description.equals(other.description)) {
-                return false;
-            }
-            if (errorAppTag == null) {
-                if (other.errorAppTag != null) {
-                    return false;
-                }
-            } else if (!errorAppTag.equals(other.errorAppTag)) {
-                return false;
-            }
-            if (errorMessage == null) {
-                if (other.errorMessage != null) {
-                    return false;
-                }
-            } else if (!errorMessage.equals(other.errorMessage)) {
-                return false;
-            }
-            if (max != other.max) {
-                return false;
-            }
-            if (min != other.min) {
-                return false;
-            }
-            if (reference == null) {
-                if (other.reference != null) {
-                    return false;
-                }
-            } else if (!reference.equals(other.reference)) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("LengthConstraintImpl [min=");
-            builder.append(min);
-            builder.append(", max=");
-            builder.append(max);
-            builder.append(", description=");
-            builder.append(description);
-            builder.append(", errorAppTag=");
-            builder.append(errorAppTag);
-            builder.append(", reference=");
-            builder.append(reference);
-            builder.append(", errorMessage=");
-            builder.append(errorMessage);
-            builder.append("]");
-            return builder.toString();
-        }
+    /**
+     * Creates a {@link LengthConstraint}.
+     *
+     * Creates an instance of Length constraint based on supplied parameters
+     * with additional behaviour:
+     *
+     * <ul>
+     * <li>{@link LengthConstraint#getErrorAppTag()} returns <code>length-out-of-specified-bounds</code>
+     * <li>{@link LengthConstraint#getErrorMessage() returns <code>The argument is out of bounds &lt;<i>min</i>, <i>max</i> &gt;</code>
+     * </ul>
+     *
+     * @see LengthConstraint
+     *
+     * @param min  length-restricting lower bound value. The value MUST NOT be negative.
+     * @param max length-restricting upper bound value. The value MUST NOT be negative.
+     * @param description Description associated with constraint.
+     * @param reference Reference associated with constraint.
+     * @return Instance of {@link LengthConstraint}
+     * @deprecated Use {@link #newLengthConstraint(Number, Number, Optional, Optional)} instead.
+     */
+    @Deprecated
+    public static LengthConstraint lengthConstraint(final Number min, final Number max, final String description,
+            final String reference) {
+        return newLengthConstraint(min, max, Optional.fromNullable(description), Optional.fromNullable(reference));
     }
 
-    private static final class RangeConstraintImpl implements RangeConstraint {
-        private final Number min;
-        private final Number max;
-
-        private final String description;
-        private final String reference;
-
-        private final String errorAppTag;
-        private final String errorMessage;
-
-        public RangeConstraintImpl(Number min, Number max, String description, String reference) {
-            super();
-            this.min = min;
-            this.max = max;
-            this.description = description;
-            this.reference = reference;
-
-            this.errorAppTag = "range-out-of-specified-bounds";
-            this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
-        }
-
-        @Override
-        public String getDescription() {
-            return description;
-        }
-
-        @Override
-        public String getErrorAppTag() {
-            return errorAppTag;
-        }
-
-        @Override
-        public String getErrorMessage() {
-            return errorMessage;
-        }
-
-        @Override
-        public String getReference() {
-            return reference;
-        }
-
-        @Override
-        public Number getMin() {
-            return min;
-        }
-
-        @Override
-        public Number getMax() {
-            return max;
-        }
-
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((description == null) ? 0 : description.hashCode());
-            result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
-            result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
-            result = prime * result + ((max == null) ? 0 : max.hashCode());
-            result = prime * result + ((min == null) ? 0 : min.hashCode());
-            result = prime * result + ((reference == null) ? 0 : reference.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(final Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            final RangeConstraintImpl other = (RangeConstraintImpl) obj;
-            if (description == null) {
-                if (other.description != null) {
-                    return false;
-                }
-            } else if (!description.equals(other.description)) {
-                return false;
-            }
-            if (errorAppTag == null) {
-                if (other.errorAppTag != null) {
-                    return false;
-                }
-            } else if (!errorAppTag.equals(other.errorAppTag)) {
-                return false;
-            }
-            if (errorMessage == null) {
-                if (other.errorMessage != null) {
-                    return false;
-                }
-            } else if (!errorMessage.equals(other.errorMessage)) {
-                return false;
-            }
-            if (max == null) {
-                if (other.max != null) {
-                    return false;
-                }
-            } else if (!max.equals(other.max)) {
-                return false;
-            }
-            if (min == null) {
-                if (other.min != null) {
-                    return false;
-                }
-            } else if (!min.equals(other.min)) {
-                return false;
-            }
-            if (reference == null) {
-                if (other.reference != null) {
-                    return false;
-                }
-            } else if (!reference.equals(other.reference)) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override
-        public String toString() {
-            final StringBuilder builder = new StringBuilder();
-            builder.append("RangeConstraintImpl [min=");
-            builder.append(min);
-            builder.append(", max=");
-            builder.append(max);
-            builder.append(", description=");
-            builder.append(description);
-            builder.append(", reference=");
-            builder.append(reference);
-            builder.append(", errorAppTag=");
-            builder.append(errorAppTag);
-            builder.append(", errorMessage=");
-            builder.append(errorMessage);
-            builder.append("]");
-            return builder.toString();
-        }
+    /**
+     * Creates a {@link RangeConstraint}.
+     *
+     * Creates an instance of Range constraint based on supplied parameters
+     * with additional behaviour:
+     *
+     * <ul>
+     * <li>{@link RangeConstraint#getErrorAppTag()} returns <code>range-out-of-specified-bounds</code>
+     * <li>{@link RangeConstraint#getErrorMessage() returns <code>The argument is out of bounds &lt;<i>min</i>, <i>max</i> &gt;</code>
+     * </ul>
+     *
+     *
+     * @see RangeConstraint
+     *
+     * @param min value-restricting lower bound value. The value MUST NOT Be null.
+     * @param max value-restricting upper bound value. The value MUST NOT Be null.
+     * @param description Description associated with constraint.
+     * @param reference Reference associated with constraint.
+     * @return Instance of {@link RangeConstraint}
+     * @deprecated Use {@link #newRangeConstraint(Number, Number, Optional, Optional)} instead.
+     */
+    @Deprecated
+    public static RangeConstraint rangeConstraint(final Number min, final Number max, final String description,
+            final String reference) {
+        return newRangeConstraint(min, max, Optional.fromNullable(description), Optional.fromNullable(reference));
     }
 
-    private static final class PatternConstraintImpl implements PatternConstraint {
-
-        private final String regex;
-        private final String description;
-        private final String reference;
-
-        private final String errorAppTag;
-        private final String errorMessage;
-
-        public PatternConstraintImpl(final String regex, final String description, final String reference) {
-            super();
-            this.regex = regex;
-            this.description = description;
-            this.reference = reference;
-
-            errorAppTag = "invalid-regular-expression";
-            // TODO: add erro message
-            errorMessage = "";
-        }
-
-        @Override
-        public String getDescription() {
-            return description;
-        }
-
-        @Override
-        public String getErrorAppTag() {
-            return errorAppTag;
-        }
-
-        @Override
-        public String getErrorMessage() {
-            return errorMessage;
-        }
-
-        @Override
-        public String getReference() {
-            return reference;
-        }
-
-        @Override
-        public String getRegularExpression() {
-            return regex;
-        }
-
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((description == null) ? 0 : description.hashCode());
-            result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
-            result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
-            result = prime * result + ((reference == null) ? 0 : reference.hashCode());
-            result = prime * result + ((regex == null) ? 0 : regex.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(final Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            final PatternConstraintImpl other = (PatternConstraintImpl) obj;
-            if (description == null) {
-                if (other.description != null) {
-                    return false;
-                }
-            } else if (!description.equals(other.description)) {
-                return false;
-            }
-            if (errorAppTag == null) {
-                if (other.errorAppTag != null) {
-                    return false;
-                }
-            } else if (!errorAppTag.equals(other.errorAppTag)) {
-                return false;
-            }
-            if (errorMessage == null) {
-                if (other.errorMessage != null) {
-                    return false;
-                }
-            } else if (!errorMessage.equals(other.errorMessage)) {
-                return false;
-            }
-            if (reference == null) {
-                if (other.reference != null) {
-                    return false;
-                }
-            } else if (!reference.equals(other.reference)) {
-                return false;
-            }
-            if (regex == null) {
-                if (other.regex != null) {
-                    return false;
-                }
-            } else if (!regex.equals(other.regex)) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("PatternConstraintImpl [regex=");
-            builder.append(regex);
-            builder.append(", description=");
-            builder.append(description);
-            builder.append(", reference=");
-            builder.append(reference);
-            builder.append(", errorAppTag=");
-            builder.append(errorAppTag);
-            builder.append(", errorMessage=");
-            builder.append(errorMessage);
-            builder.append("]");
-            return builder.toString();
-        }
+    /**
+     * Creates a {@link PatternConstraint}.
+     *
+     * Creates an instance of Range constraint based on supplied parameters
+     * with additional behaviour:
+     *
+     * <ul>
+     * <li>{@link PatternConstraint#getErrorAppTag()} returns <code>invalid-regular-expression</code>
+     * </ul>
+     *
+     *
+     * @see PatternConstraint
+     *
+     * @param pattern Regular expression, MUST NOT
+     * @param description Description associated with constraint.
+     * @param reference Reference associated with constraint.
+     * @return Instance of {@link PatternConstraint}
+     * @deprecated Use {@link #newPatternConstraint(String, Optional, Optional)} Instead.
+     */
+    @Deprecated
+    public static PatternConstraint patternConstraint(final String pattern, final String description,
+            final String reference) {
+        return newPatternConstraint(pattern, Optional.fromNullable(description), Optional.fromNullable(reference));
     }
 }
index e897f6a55cdafc034a2bb443f4dba7a30eb44607..53dc55b58555f473eb4c838a39336dfd56a82ec5 100644 (file)
@@ -12,22 +12,36 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Date;
 import java.util.List;
+import java.util.Set;
 
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+
+/**
+ * Utility methods and constants to work with built-in YANG types
+ *
+ *
+ */
 public final class BaseTypes {
 
     private BaseTypes() {
     }
 
     public static final URI BASE_TYPES_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
+
     public static final QName BINARY_QNAME = constructQName("binary");
     public static final QName BITS_QNAME = constructQName("bits");
     public static final QName BOOLEAN_QNAME = constructQName("boolean");
     public static final QName DECIMAL64_QNAME = constructQName("decimal64");
     public static final QName EMPTY_QNAME = constructQName("empty");
     public static final QName ENUMERATION_QNAME = constructQName("enumeration");
+    public static final QName IDENTITYREF_QNAME = constructQName("identityref");
+    public static final QName INSTANCE_IDENTIFIER_QNAME = constructQName("instance-identifier");
     public static final QName INT8_QNAME = constructQName("int8");
     public static final QName INT16_QNAME = constructQName("int16");
     public static final QName INT32_QNAME = constructQName("int32");
@@ -38,6 +52,28 @@ public final class BaseTypes {
     public static final QName UINT16_QNAME = constructQName("uint16");
     public static final QName UINT32_QNAME = constructQName("uint32");
     public static final QName UINT64_QNAME = constructQName("uint64");
+    public static final QName UNION_QNAME = constructQName("union");
+
+    private static final Set<String> BUILD_IN_TYPES = ImmutableSet.<String> builder().add(BINARY_QNAME.getLocalName()) //
+            .add(BITS_QNAME.getLocalName()) //
+            .add(BOOLEAN_QNAME.getLocalName()) //
+            .add(DECIMAL64_QNAME.getLocalName()) //
+            .add(EMPTY_QNAME.getLocalName()) //
+            .add(ENUMERATION_QNAME.getLocalName()) //
+            .add(IDENTITYREF_QNAME.getLocalName()) //
+            .add(INSTANCE_IDENTIFIER_QNAME.getLocalName()) //
+            .add(INT8_QNAME.getLocalName()) //
+            .add(INT16_QNAME.getLocalName()) //
+            .add(INT32_QNAME.getLocalName()) //
+            .add(INT64_QNAME.getLocalName()) //
+            .add(LEAFREF_QNAME.getLocalName()) //
+            .add(STRING_QNAME.getLocalName()) //
+            .add(UINT8_QNAME.getLocalName()) //
+            .add(UINT16_QNAME.getLocalName()) //
+            .add(UINT32_QNAME.getLocalName()) //
+            .add(UINT64_QNAME.getLocalName()) //
+            .add(UNION_QNAME.getLocalName()) //
+            .build();
 
     /**
      * Construct QName for Built-in base Yang type. The namespace for built-in
@@ -52,15 +88,16 @@ public final class BaseTypes {
     }
 
     /**
-     * Creates Schema Path from Qname.
+     * Creates Schema Path from {@link QName}.
      *
      * @param typeName
      *            yang type QName
      * @return Schema Path from Qname.
+     * @deprecated Use {@link SchemaPath#create(boolean, QName...)} instead.
      */
+    @Deprecated
     public static SchemaPath schemaPath(final QName typeName) {
-        List<QName> pathList = Collections.singletonList(typeName);
-        return new SchemaPath(pathList, true);
+        return SchemaPath.create(Collections.singletonList(typeName), true);
     }
 
     /**
@@ -74,7 +111,11 @@ public final class BaseTypes {
      * @param revision
      *            Revision Date
      * @return Schema Path
+     *
+     * @deprecated Use {@link SchemaPath#create(boolean, Iterable)} with QNames
+     *             manually constructed.
      */
+    @Deprecated
     public static SchemaPath schemaPath(final List<String> actualPath, final URI namespace, final Date revision) {
         if (actualPath == null) {
             throw new IllegalArgumentException("The actual path List MUST be specified.");
@@ -86,6 +127,72 @@ public final class BaseTypes {
                 pathList.add(qname);
             }
         }
-        return new SchemaPath(pathList, true);
+        return SchemaPath.create(pathList, true);
+    }
+
+    /**
+     * Returns true if supplied type is representation of built-in YANG type as
+     * per RFC 6020.
+     *
+     * See package documentation for description of base types.
+     *
+     * @param type
+     * @return true if type is built-in YANG Types.
+     */
+    public static boolean isYangBuildInType(final String type) {
+        return BUILD_IN_TYPES.contains(type);
+    }
+
+    /**
+     * Returns default instance of built-in for supplied type
+     *
+     * See package documentation for description of base build-in types
+     * with default instance.
+     *
+     * @param typeName
+     * @return Returns default instance or {@link Optional#absent()} if default
+     *         instance does not exists
+     *
+     */
+    public static Optional<TypeDefinition<?>> defaultBaseTypeFor(final String typeName) {
+        return Optional.<TypeDefinition<?>> fromNullable(defaultBaseTypeForImpl(typeName));
+    }
+
+    private static TypeDefinition<?> defaultBaseTypeForImpl(final String typeName) {
+        Preconditions.checkNotNull(typeName, "typeName must not be null.");
+
+        if (typeName.startsWith("int")) {
+            if ("int8".equals(typeName)) {
+                return Int8.getInstance();
+            } else if ("int16".equals(typeName)) {
+                return Int16.getInstance();
+            } else if ("int32".equals(typeName)) {
+                return Int32.getInstance();
+            } else if ("int64".equals(typeName)) {
+                return Int64.getInstance();
+            }
+        } else if (typeName.startsWith("uint")) {
+            if ("uint8".equals(typeName)) {
+                return Uint8.getInstance();
+            } else if ("uint16".equals(typeName)) {
+                return Uint16.getInstance();
+            } else if ("uint32".equals(typeName)) {
+                return Uint32.getInstance();
+            } else if ("uint64".equals(typeName)) {
+                return Uint64.getInstance();
+            }
+        } else if ("string".equals(typeName)) {
+            return StringType.getInstance();
+        } else if ("binary".equals(typeName)) {
+            return BinaryType.getInstance();
+        } else if ("boolean".equals(typeName)) {
+            return BooleanType.getInstance();
+        } else if ("empty".equals(typeName)) {
+            return EmptyType.getInstance();
+        } else if ("instance-identifier".equals(typeName)) {
+            return InstanceIdentifier.getInstance();
+        }
+        return null;
     }
+
 }
index fa5c7aa4c539afbf8e47a170d6a4d90d071af99f..9d93f745f3d8675bca3315c21dcdfd8afb7d7ee4 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
@@ -18,26 +17,29 @@ import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
 
+import com.google.common.base.Optional;
+
 /**
  * The <code>default</code> implementation of Binary Type Definition interface.
  *
  * @see BinaryTypeDefinition
  */
 public final class BinaryType implements BinaryTypeDefinition {
-    private static final BinaryType INSTANCE = new BinaryType();
-    private final QName name = BaseTypes.constructQName("binary");
-    private final SchemaPath path = new SchemaPath(Collections.singletonList(name), true);
     private static final String DESCRIPTION = "The binary built-in type represents any binary data, i.e., a sequence of octets.";
     private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.8";
-    private final List<Byte> bytes;
-    private final List<LengthConstraint> lengthConstraints;
     private static final String UNITS = "";
 
+    private final static QName QNAME = BaseTypes.BINARY_QNAME;
+
+    private static final BinaryType INSTANCE = new BinaryType();
+
+    private final static SchemaPath PATH = SchemaPath.create(Collections.singletonList(QNAME), true);
+    private final List<Byte> bytes = Collections.emptyList();
+    private final List<LengthConstraint> lengthConstraints;
+
     private BinaryType() {
-        final List<LengthConstraint> constraints = new ArrayList<LengthConstraint>();
-        constraints.add(BaseConstraints.lengthConstraint(0, Long.MAX_VALUE, "", ""));
-        this.lengthConstraints = Collections.unmodifiableList(constraints);
-        this.bytes = Collections.emptyList();
+        this.lengthConstraints = Collections.singletonList(
+                BaseConstraints.newLengthConstraint(0, Long.MAX_VALUE, Optional.of(""), Optional.of("")));
     }
 
     public static BinaryType getInstance() {
@@ -84,7 +86,7 @@ public final class BinaryType implements BinaryTypeDefinition {
      */
     @Override
     public QName getQName() {
-        return name;
+        return QNAME;
     }
 
     /*
@@ -94,7 +96,7 @@ public final class BinaryType implements BinaryTypeDefinition {
      */
     @Override
     public SchemaPath getPath() {
-        return path;
+        return PATH;
     }
 
     /*
@@ -151,13 +153,13 @@ public final class BinaryType implements BinaryTypeDefinition {
         int result = 1;
         result = prime * result + ((bytes == null) ? 0 : bytes.hashCode());
         result = prime * result + ((lengthConstraints == null) ? 0 : lengthConstraints.hashCode());
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
-        result = prime * result + ((path == null) ? 0 : path.hashCode());
+        result = prime * result + QNAME.hashCode();
+        result = prime * result + PATH.hashCode();
         return result;
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
@@ -182,20 +184,6 @@ public final class BinaryType implements BinaryTypeDefinition {
         } else if (!lengthConstraints.equals(other.lengthConstraints)) {
             return false;
         }
-        if (name == null) {
-            if (other.name != null) {
-                return false;
-            }
-        } else if (!name.equals(other.name)) {
-            return false;
-        }
-        if (path == null) {
-            if (other.path != null) {
-                return false;
-            }
-        } else if (!path.equals(other.path)) {
-            return false;
-        }
         return true;
     }
 
@@ -203,9 +191,7 @@ public final class BinaryType implements BinaryTypeDefinition {
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("BinaryType [name=");
-        builder.append(name);
-        builder.append(", path=");
-        builder.append(path);
+        builder.append(QNAME);
         builder.append(", description=");
         builder.append(DESCRIPTION);
         builder.append(", reference=");
index c53df1bc6aa71259f030a996bc4259f2d8378518..e89e6572f459730a09d1cb30e3956138ec962596 100644 (file)
@@ -16,13 +16,17 @@ import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
 /**
  * The <code>default</code> implementation of Bits Type Definition interface.
  *
  * @see BitsTypeDefinition
  */
 public final class BitsType implements BitsTypeDefinition {
-    private final QName name = BaseTypes.constructQName("bits");
+    private final static QName NAME = BaseTypes.BITS_QNAME;
+
     private final SchemaPath path;
     private final String description = "The bits built-in type represents a bit set.  "
             + "That is, a bits value is a set of flags identified by small integer position "
@@ -37,11 +41,13 @@ public final class BitsType implements BitsTypeDefinition {
      * Instantiates Bits type as empty bits list.
      *
      * @param path
+     * @deprecated Use static factory method {@link #create(SchemaPath, List)} instead.
      */
+    @Deprecated
     public BitsType(final SchemaPath path) {
         super();
         this.bits = Collections.emptyList();
-        this.path = path;
+        this.path = Preconditions.checkNotNull(path,"path must not be null");
     }
 
     /**
@@ -49,11 +55,17 @@ public final class BitsType implements BitsTypeDefinition {
      *
      * @param path
      * @param bits
+     * @deprecated Use static factory method {@link #create(SchemaPath, List)} instead.
      */
+    @Deprecated
     public BitsType(final SchemaPath path, final List<Bit> bits) {
         super();
-        this.bits = Collections.unmodifiableList(bits);
-        this.path = path;
+        this.bits = ImmutableList.copyOf(bits);
+        this.path = Preconditions.checkNotNull(path,"path must not be null");
+    }
+
+    public static BitsType create(final SchemaPath path, final List<Bit> bits) {
+        return new BitsType(path,bits);
     }
 
     /*
@@ -96,7 +108,7 @@ public final class BitsType implements BitsTypeDefinition {
      */
     @Override
     public QName getQName() {
-        return name;
+        return NAME;
     }
 
     /*
@@ -156,13 +168,13 @@ public final class BitsType implements BitsTypeDefinition {
         int result = 1;
         result = prime * result + ((bits == null) ? 0 : bits.hashCode());
         result = prime * result + ((description == null) ? 0 : description.hashCode());
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
-        result = prime * result + ((path == null) ? 0 : path.hashCode());
+        result = prime * result + NAME.hashCode();
+        result = prime * result + path.hashCode();
         return result;
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
@@ -187,13 +199,7 @@ public final class BitsType implements BitsTypeDefinition {
         } else if (!description.equals(other.description)) {
             return false;
         }
-        if (name == null) {
-            if (other.name != null) {
-                return false;
-            }
-        } else if (!name.equals(other.name)) {
-            return false;
-        }
+
         if (path == null) {
             if (other.path != null) {
                 return false;
@@ -208,7 +214,7 @@ public final class BitsType implements BitsTypeDefinition {
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("BitsType [name=");
-        builder.append(name);
+        builder.append(NAME);
         builder.append(", path=");
         builder.append(path);
         builder.append(", description=");
index b4740884fb24743a4c3b3b5f6522da9d81a580de..ad3a0ef6d29410beb12b3e5aaa30595058a7caf2 100644 (file)
@@ -23,8 +23,7 @@ import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
  */
 public final class BooleanType implements BooleanTypeDefinition {
     private static final BooleanType INSTANCE = new BooleanType();
-    private static final QName NAME = BaseTypes.constructQName("boolean");
-    private static final SchemaPath PATH = new SchemaPath(Collections.singletonList(NAME), true);
+    private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(BaseTypes.BOOLEAN_QNAME), true);
     private static final String DESCRIPTION = "The boolean built-in type represents a boolean value.";
     private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.5";
     private static final String UNITS = "";
@@ -35,6 +34,10 @@ public final class BooleanType implements BooleanTypeDefinition {
     private BooleanType() {
     }
 
+    /**
+     * Returns default instance of boolean built-in type.
+     * @return default instance of boolean built-in type.
+     */
     public static BooleanType getInstance() {
         return INSTANCE;
     }
@@ -79,7 +82,7 @@ public final class BooleanType implements BooleanTypeDefinition {
      */
     @Override
     public QName getQName() {
-        return NAME;
+        return BaseTypes.BOOLEAN_QNAME;
     }
 
     /*
@@ -132,7 +135,7 @@ public final class BooleanType implements BooleanTypeDefinition {
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("BooleanType [name=");
-        builder.append(NAME);
+        builder.append(BaseTypes.BOOLEAN_QNAME);
         builder.append(", path=");
         builder.append(PATH);
         builder.append("]");
index ed1db9a31505fc3ca961704e002862268975ca9f..850b51de87f52d091536008723b4075c1ba4763e 100644 (file)
@@ -24,6 +24,15 @@ import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 
+/**
+ * DataNodeIterator is iterator, which walks down whole YANG DataNodeContainer
+ * and walks all instances of {@link DataSchemaNode} present in subtree.
+ *
+ * Iterator instance is eagerly created, walking happens on initialization.
+ *
+ * Iteration is not ordered.
+ *
+ */
 public class DataNodeIterator implements Iterator<DataSchemaNode> {
 
     private final DataNodeContainer container;
@@ -50,22 +59,47 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
         traverse(this.container);
     }
 
+    /**
+     * Returns list all containers present in subtree.
+     *
+     * @return Returns list all containers present in subtree.
+     */
     public List<ContainerSchemaNode> allContainers() {
         return allContainers;
     }
 
+    /**
+     * Returns list all lists present in subtree.
+     *
+     * @return Returns list all containers present in subtree.
+     */
     public List<ListSchemaNode> allLists() {
         return allLists;
     }
 
+    /**
+     * Returns list all choices present in subtree.
+     *
+     * @return Returns list all containers present in subtree.
+     */
     public List<ChoiceNode> allChoices() {
         return allChoices;
     }
 
+    /**
+     * Returns list all groupings present in subtree.
+     *
+     * @return Returns list all containers present in subtree.
+     */
     public List<GroupingDefinition> allGroupings() {
         return allGroupings;
     }
 
+    /**
+     * Returns list all typedefs present in subtree.
+     *
+     * @return Returns list all containers present in subtree.
+     */
     public List<TypeDefinition<?>> allTypedefs() {
         return allTypedefs;
     }
@@ -109,7 +143,7 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
 
     }
 
-    private void traverseModule(DataNodeContainer dataNode) {
+    private void traverseModule(final DataNodeContainer dataNode) {
         final Module module;
         if (dataNode instanceof Module) {
             module = (Module) dataNode;
@@ -136,7 +170,7 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
         }
     }
 
-    private void traverseGroupings(DataNodeContainer dataNode) {
+    private void traverseGroupings(final DataNodeContainer dataNode) {
         final Set<GroupingDefinition> groupings = dataNode.getGroupings();
         if (groupings != null) {
             for (GroupingDefinition grouping : groupings) {
index 666747915f3444becdf2e372b9fc9c15b6da1ab3..d975178a664015d4495b625ce173839fbb2ae85d 100644 (file)
@@ -19,6 +19,8 @@ import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 
+import com.google.common.base.Optional;
+
 /**
  * The <code>default</code> implementation of Decimal Type Definition interface.
  *
@@ -26,7 +28,7 @@ import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
  * @see DecimalTypeDefinition
  */
 public final class Decimal64 implements DecimalTypeDefinition {
-    private final QName name = BaseTypes.constructQName("decimal64");
+    private static final QName NAME = BaseTypes.DECIMAL64_QNAME;
     private final SchemaPath path;
     private static final String UNITS = "";
     private static final BigDecimal DEFAULT_VALUE = null;
@@ -60,7 +62,9 @@ public final class Decimal64 implements DecimalTypeDefinition {
      *
      * @see DecimalTypeDefinition
      * @exception IllegalArgumentException
+     * @deprecated Use static factory {@link #create(SchemaPath, Integer)}.
      */
+    @Deprecated
     public Decimal64(final SchemaPath path, final Integer fractionDigits) {
         if (!((fractionDigits.intValue() >= 1) && (fractionDigits.intValue() <= MAX_NUMBER_OF_FRACTION_DIGITS))) {
             throw new IllegalArgumentException(
@@ -71,6 +75,10 @@ public final class Decimal64 implements DecimalTypeDefinition {
         this.path = path;
     }
 
+    public static Decimal64 create(final SchemaPath path, final Integer fractionDigits) {
+        return new Decimal64(path, fractionDigits);
+    }
+
     /**
      * Returns unmodifiable List with default definition of Range Statements.
      *
@@ -81,8 +89,8 @@ public final class Decimal64 implements DecimalTypeDefinition {
         final BigDecimal min = new BigDecimal("-922337203685477580.8");
         final BigDecimal max = new BigDecimal("922337203685477580.7");
         final String rangeDescription = "Integer values between " + min + " and " + max + ", inclusively.";
-        rangeStmts.add(BaseConstraints.rangeConstraint(min, max, rangeDescription,
-                "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
+        rangeStmts.add(BaseConstraints.newRangeConstraint(min, max, Optional.of(rangeDescription),
+                Optional.of("https://tools.ietf.org/html/rfc6020#section-9.2.4")));
         return Collections.unmodifiableList(rangeStmts);
     }
 
@@ -103,7 +111,7 @@ public final class Decimal64 implements DecimalTypeDefinition {
 
     @Override
     public QName getQName() {
-        return name;
+        return NAME;
     }
 
     @Override
@@ -145,13 +153,13 @@ public final class Decimal64 implements DecimalTypeDefinition {
     public int hashCode() {
         final int prime = 31;
         int result = 1;
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
+        result = prime * result + ((NAME == null) ? 0 : NAME.hashCode());
         result = prime * result + ((path == null) ? 0 : path.hashCode());
         return result;
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
@@ -162,13 +170,6 @@ public final class Decimal64 implements DecimalTypeDefinition {
             return false;
         }
         Decimal64 other = (Decimal64) obj;
-        if (name == null) {
-            if (other.name != null) {
-                return false;
-            }
-        } else if (!name.equals(other.name)) {
-            return false;
-        }
         if (path == null) {
             if (other.path != null) {
                 return false;
@@ -181,6 +182,6 @@ public final class Decimal64 implements DecimalTypeDefinition {
 
     @Override
     public String toString() {
-        return Decimal64.class.getSimpleName() + "[qname=" + name + ", fractionDigits=" + fractionDigits + "]";
+        return Decimal64.class.getSimpleName() + "[qname=" + NAME + ", fractionDigits=" + fractionDigits + "]";
     }
 }
index c4f78c621da82d23f7177d79d4a344cdfa18926c..7efebad4d43bdd4b0d2d5c8a84826de0ef09082e 100644 (file)
@@ -10,16 +10,17 @@ package org.opendaylight.yangtools.yang.model.util;
 import java.util.Collections;
 import java.util.List;
 
+import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
 
-public final class EmptyType implements EmptyTypeDefinition {
-    private static EmptyType instance;
-    private static final QName NAME = BaseTypes.constructQName("empty");
-    private static final SchemaPath PATH = new SchemaPath(Collections.singletonList(NAME), true);
+public final class EmptyType implements EmptyTypeDefinition, Immutable {
+    private static final EmptyType INSTANCE = new EmptyType();
+    private static final QName NAME = BaseTypes.EMPTY_QNAME;
+    private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(NAME), true);
     private static final String DESCRIPTION = "The empty built-in type represents a leaf that does not have any value, it conveys information by its presence or absence.";
     private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#page-131";
 
@@ -27,10 +28,7 @@ public final class EmptyType implements EmptyTypeDefinition {
     }
 
     public static EmptyType getInstance() {
-        if (instance == null) {
-            instance = new EmptyType();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
index f359de0fddbfa9c7687197c89c62ea05fef152cb..1bd020019fa8fe63704dbd47572e9c478674bc7f 100644 (file)
@@ -16,6 +16,8 @@ import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
 /**
@@ -33,18 +35,55 @@ public final class EnumerationType implements EnumTypeDefinition {
     private final EnumPair defaultEnum;
     private final List<EnumPair> enums;
 
+
+    /**
+     * Constructs EnumerationType
+     *
+     * @param path
+     * @param enums
+     * @deprecated Use {@link #create(SchemaPath, List, Optional)} instead.
+     */
+    @Deprecated
     public EnumerationType(final SchemaPath path, final List<EnumPair> enums) {
-        super();
-        this.path = path;
-        this.enums = ImmutableList.copyOf(enums);
-        this.defaultEnum = null;
+        this(path,enums,Optional.<EnumPair>absent());
     }
 
+    /**
+     * Constructs EnumerationType
+     *
+     * @param path
+     * @param defaultEnum
+     * @param enums
+     * @deprecated Use {@link #create(SchemaPath, List, Optional)} instead.
+     */
+    @Deprecated
     public EnumerationType(final SchemaPath path, final EnumPair defaultEnum, final List<EnumPair> enums) {
-        super();
-        this.path = path;
-        this.defaultEnum = defaultEnum;
-        this.enums = ImmutableList.copyOf(enums);
+        this(path,enums,Optional.fromNullable(defaultEnum));
+    }
+
+    private EnumerationType(final SchemaPath path, final List<EnumPair> enums, final Optional<EnumPair> defaultEnum) {
+        this.path = Preconditions.checkNotNull(path,"path must not be null");
+        this.enums = ImmutableList.copyOf(Preconditions.checkNotNull(enums, "enums must not be null."));
+        if(defaultEnum.isPresent()) {
+            Preconditions.checkArgument(enums.contains(defaultEnum.get()),"defaultEnum must be contained in defined enumerations.");
+            this.defaultEnum = defaultEnum.get();
+        } else {
+            this.defaultEnum = null;
+        }
+    }
+
+    /**
+     *
+     * Constructs new enumeration
+     *
+     * @param path Schema Path to definition point of this enumeration
+     * @param enums List of defined enumeration values
+     * @param defaultValue {@link Optional#of(Object)} of default value, {@link Optional#absent()} if no default value is defined.
+     *        If defaultValue is set, it must be present in provided list of enumerations.
+     *
+     */
+    public static EnumerationType create(final SchemaPath path, final List<EnumPair> enums, final Optional<EnumPair> defaultValue) {
+        return new EnumerationType(path, enums, defaultValue);
     }
 
     /*
index 4c2c17b63ad2aae304dc0802d9f050f296bd18ee..c5add934bee984990ec6d7e8eb2b213922c278b1 100644 (file)
@@ -21,6 +21,17 @@ import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+/**
+ * Extended Type represents YANG type derived from other type.
+ *
+ * Extended type object is decorator on top of existing {@link TypeDefinition}
+ * which represents original type, and extended type
+ * may define additional constraints, modify description or reference
+ * of parent type or provide new type capture for specific use-cases.
+ *
+ */
 public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
 
     private final QName typeName;
@@ -35,10 +46,24 @@ public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
     private List<PatternConstraint> patterns = Collections.emptyList();
     private Integer fractionDigits = null;
 
-    private Status status;
-    private String units;
-    private Object defaultValue;
-    private boolean addedByUses;
+    private final Status status;
+    private final String units;
+    private final Object defaultValue;
+    private final boolean addedByUses;
+
+    /**
+    *
+    * Creates Builder for extended / derived type.
+    *
+    * @param typeName QName of derived type
+    * @param baseType Base type of derived type
+    * @param description Description of type
+    * @param reference Reference of Type
+    * @param path Schema path to type definition.
+    */
+    public static final Builder builder(final QName typeName,final TypeDefinition<?> baseType,final Optional<String> description,final Optional<String> reference,final SchemaPath path) {
+        return new Builder(typeName, baseType, description.or(""), reference.or(""), path);
+    }
 
     public static class Builder {
         private final QName typeName;
@@ -60,33 +85,55 @@ public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
         private List<PatternConstraint> patterns = Collections.emptyList();
         private Integer fractionDigits = null;
 
+        /**
+         *
+         * @param actualPath
+         * @param namespace
+         * @param revision
+         * @param typeName
+         * @param baseType
+         * @param description
+         * @param reference
+         *
+         * @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath) instead.
+         */
+        @Deprecated
         public Builder(final List<String> actualPath, final URI namespace,
                 final Date revision, final QName typeName,
-                TypeDefinition<?> baseType, final String description,
+                final TypeDefinition<?> baseType, final String description,
                 final String reference) {
-            this.typeName = typeName;
-            this.baseType = baseType;
-            this.path = BaseTypes.schemaPath(actualPath, namespace, revision);
-            this.description = description;
-            this.reference = reference;
+            this(typeName,baseType,description,reference,BaseTypes.schemaPath(actualPath, namespace, revision));
         }
 
-        public Builder(final QName typeName, TypeDefinition<?> baseType,
+        /**
+         *
+         * Creates Builder for extended / derived type.
+         *
+         * @param typeName QName of derived type
+         * @param baseType Base type of derived type
+         * @param description Description of type
+         * @param reference Reference of Type
+         * @param path Schema path to type definition.
+         *
+         * @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath) instead.
+         */
+        @Deprecated
+        public Builder(final QName typeName, final TypeDefinition<?> baseType,
                 final String description, final String reference,
-                SchemaPath path) {
-            this.typeName = typeName;
-            this.baseType = baseType;
-            this.path = path;
+                final SchemaPath path) {
+            this.typeName = Preconditions.checkNotNull(typeName, "type name must not be null.");
+            this.baseType = Preconditions.checkNotNull(baseType, "base type must not be null");
+            this.path = Preconditions.checkNotNull(path, "path must not be null.");
             this.description = description;
             this.reference = reference;
         }
 
-        public Builder status(Status status) {
+        public Builder status(final Status status) {
             this.status = status;
             return this;
         }
 
-        public Builder units(String units) {
+        public Builder units(final String units) {
             this.units = units;
             return this;
         }
@@ -138,7 +185,7 @@ public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
         }
     }
 
-    private ExtendedType(Builder builder) {
+    private ExtendedType(final Builder builder) {
         this.typeName = builder.typeName;
         this.baseType = builder.baseType;
         this.path = builder.path;
@@ -206,7 +253,7 @@ public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
     }
 
     @Override
-    public boolean equals(Object o) {
+    public boolean equals(final Object o) {
         if (this == o) {
             return true;
         }
index e34e0078588607c581c4f81e18d0ba37a9c170bf..16823e6708706682e24853627b07fc64581521f7 100644 (file)
@@ -17,6 +17,8 @@ import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
 
+import com.google.common.base.Preconditions;
+
 /**
  * The <code>default</code> implementation of Identityref Type Definition
  * interface.
@@ -24,16 +26,39 @@ import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
  * @see IdentityrefTypeDefinition
  */
 public final class IdentityrefType implements IdentityrefTypeDefinition {
-    private final QName name = BaseTypes.constructQName("identityref");
+    private static final QName NAME = BaseTypes.IDENTITYREF_QNAME;
     private final SchemaPath path;
     private static final String DESCRIPTION = "The identityref type is used to reference an existing identity.";
     private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.10";
     private final IdentitySchemaNode identity;
     private static final String UNITS = "";
 
-    public IdentityrefType(IdentitySchemaNode identity, SchemaPath schemaPath) {
-        this.identity = identity;
-        this.path = schemaPath;
+    /**
+     * Constructs new {@link IdentityrefTypeDefinition} definition.
+     *
+     * @param identity
+     * @param schemaPath
+     */
+    @Deprecated
+    public IdentityrefType(final IdentitySchemaNode identity, final SchemaPath schemaPath) {
+        this(schemaPath,identity);
+    }
+
+    private IdentityrefType(final SchemaPath path, final IdentitySchemaNode baseIdentity) {
+        this.path = Preconditions.checkNotNull(path, "Path must be specified");
+        this.identity = Preconditions.checkNotNull(baseIdentity,"baseIdentity must be specified.");
+    }
+
+    /**
+     *
+     * Constructs new {@link IdentityrefTypeDefinition} definition.
+     *
+     * @param path Path to the definition.
+     * @param baseIdentity Base Identity, all derived identities are valid arguments for instance of this type.
+     * @return New identityref definition.
+     */
+    public static IdentityrefType create(final SchemaPath path, final IdentitySchemaNode baseIdentity) {
+        return new IdentityrefType(path, baseIdentity);
     }
 
     @Override
@@ -48,7 +73,7 @@ public final class IdentityrefType implements IdentityrefTypeDefinition {
 
     @Override
     public QName getQName() {
-        return name;
+        return NAME;
     }
 
     @Override
index 6330801f35cb7424965e3584a1cd3114afb4089c..b2d5887a7e6cbef4be618d392a2b2f8bfc9ef3b8 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.yangtools.yang.model.util;
 import java.util.Collections;
 import java.util.List;
 
+import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
@@ -21,33 +22,62 @@ import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefi
  * The <code>default</code> implementation of Instance Identifier Type
  * Definition interface.
  *
+ * Instance Identifier has only two possible variants - one with
+ * {@link #requireInstance()} which returns true, other one
+ * returns false.
+ *
  * @see InstanceIdentifierTypeDefinition
- * @deprecated Depracated, use {@link org.opendaylight.yangtools.yang.data.api.InstanceIdentifier} instead
+ *
  */
-@Deprecated
-public final class InstanceIdentifier implements InstanceIdentifierTypeDefinition {
-    private static final QName NAME = BaseTypes.constructQName("instance-identifier");
-    private static final SchemaPath PATH = new SchemaPath(Collections.singletonList(NAME), true);
+public final class InstanceIdentifier implements InstanceIdentifierTypeDefinition, Immutable {
+
+    private static final QName NAME = BaseTypes.INSTANCE_IDENTIFIER_QNAME;
+    private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(NAME), true);
     private static final String DESCRIPTION = "The instance-identifier built-in type is used to "
             + "uniquely identify a particular instance node in the data tree.";
     private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.13";
 
-    private final RevisionAwareXPath xpath;
     private static final String UNITS = "";
-    private boolean requireInstance = true;
+    private final Boolean requireInstance;
 
-    private static final int HASH_BOOLEAN_TRUE = 1231;
-    private static final int HASH_BOOLEAN_FALSE = 1237;
+    private static final InstanceIdentifier INSTANCE_WITH_REQUIRED_TRUE = new InstanceIdentifier(true);
+    private static final InstanceIdentifier INSTANCE_WITH_REQUIRED_FALSE = new InstanceIdentifier(false);
 
+    /**
+     * Constructs new instance identifier.
+     *
+     * @param xpath
+     * @deprecated Use {@link #getInstance()} for default one, since Instance Identifier does not have xpath.
+     */
+    @Deprecated
     public InstanceIdentifier(final RevisionAwareXPath xpath) {
-        this.xpath = xpath;
+        requireInstance = true;
     }
 
+    /**
+     * Constructs new instance identifier.
+     *
+     * @param xpath
+     * @param requireInstance if instance of data is required
+     * @deprecated Use {@link #create(boolean)}, since Instance Identifier does not have xpath.
+     */
+    @Deprecated
     public InstanceIdentifier(final RevisionAwareXPath xpath, final boolean requireInstance) {
-        this.xpath = xpath;
         this.requireInstance = requireInstance;
     }
 
+    private InstanceIdentifier(final boolean requiredInstance) {
+        this.requireInstance = requiredInstance;
+    }
+
+    public static InstanceIdentifier getInstance() {
+        return INSTANCE_WITH_REQUIRED_TRUE;
+    }
+
+    public static InstanceIdentifier create(final boolean requireInstance) {
+        return requireInstance ? INSTANCE_WITH_REQUIRED_TRUE : INSTANCE_WITH_REQUIRED_FALSE;
+    }
+
     /*
      * (non-Javadoc)
      *
@@ -78,7 +108,7 @@ public final class InstanceIdentifier implements InstanceIdentifierTypeDefinitio
      */
     @Override
     public Object getDefaultValue() {
-        return xpath;
+        return null;
     }
 
     /*
@@ -151,8 +181,9 @@ public final class InstanceIdentifier implements InstanceIdentifierTypeDefinitio
      * InstanceIdentifierTypeDefinition# getPathStatement()
      */
     @Override
+    @Deprecated
     public RevisionAwareXPath getPathStatement() {
-        return xpath;
+        return null;
     }
 
     /*
@@ -170,13 +201,12 @@ public final class InstanceIdentifier implements InstanceIdentifierTypeDefinitio
     public int hashCode() {
         final int prime = 31;
         int result = 1;
-        result = prime * result + (requireInstance ? HASH_BOOLEAN_TRUE : HASH_BOOLEAN_FALSE);
-        result = prime * result + ((xpath == null) ? 0 : xpath.hashCode());
+        result = prime * result + requireInstance.hashCode();
         return result;
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
@@ -187,17 +217,9 @@ public final class InstanceIdentifier implements InstanceIdentifierTypeDefinitio
             return false;
         }
         InstanceIdentifier other = (InstanceIdentifier) obj;
-        if (requireInstance != other.requireInstance) {
-            return false;
-        }
-        if (xpath == null) {
-            if (other.xpath != null) {
-                return false;
-            }
-        } else if (!xpath.equals(other.xpath)) {
-            return false;
-        }
-        return true;
+        return requireInstance.equals(other.requireInstance);
     }
 
+
+
 }
index 63caa24500d6e285a685d80bc1a64ebcb992cfdb..f88e7984a16909b0682c60350662b6acf5aa664a 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang int16 built-in type. <br>
@@ -16,20 +16,21 @@ import org.opendaylight.yangtools.yang.common.QName;
  *
  * @see AbstractSignedInteger
  */
-public final class Int16 extends AbstractSignedInteger {
-    private static Int16 instance;
-    private static final QName NAME = BaseTypes.constructQName("int16");
+public final class Int16 extends AbstractSignedInteger implements Immutable {
     private static final String DESCRIPTION = "int16  represents integer values between -32768 and 32767, inclusively.";
 
+    private static final Int16 INSTANCE = new Int16();
+
     private Int16() {
-        super(NAME, DESCRIPTION, Short.MIN_VALUE, Short.MAX_VALUE, "");
+        super(BaseTypes.INT16_QNAME, DESCRIPTION, Short.MIN_VALUE, Short.MAX_VALUE, "");
     }
 
+    /**
+     * Returns default instance of int16 type.
+     * @return default instance of int16 type.
+     */
     public static Int16 getInstance() {
-        if (instance == null) {
-            instance = new Int16();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -39,7 +40,7 @@ public final class Int16 extends AbstractSignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.INT16_QNAME;
     }
 
 }
index b043d40a7ed7b443557e6a34fc3ccd379db0d1bb..d42768bc71b14b2ffc88008673a049d8dc4e5a85 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang int32 built-in type. <br>
@@ -18,20 +18,22 @@ import org.opendaylight.yangtools.yang.common.QName;
  * @see AbstractSignedInteger
  *
  */
-public final class Int32 extends AbstractSignedInteger {
-    private static Int32 instance;
-    private static final QName NAME = BaseTypes.constructQName("int32");
+public final class Int32 extends AbstractSignedInteger implements Immutable {
     private static final String DESCRIPTION = "int32  represents integer values between -2147483648 and 2147483647, inclusively.";
 
+
+    private static final Int32 INSTANCE = new Int32();
+
     private Int32() {
-        super(Int32.NAME, Int32.DESCRIPTION, Integer.MIN_VALUE, Integer.MAX_VALUE, "");
+        super(BaseTypes.INT32_QNAME, Int32.DESCRIPTION, Integer.MIN_VALUE, Integer.MAX_VALUE, "");
     }
 
+    /**
+     * Returns default instance of int32 type.
+     * @return default instance of int32 type.
+     */
     public static Int32 getInstance() {
-        if (instance == null) {
-            instance = new Int32();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -41,6 +43,7 @@ public final class Int32 extends AbstractSignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.INT32_QNAME;
     }
+
 }
index 892a1436ee37441dc6d180b0b51cefa5c8b9b2b3..ea6830fa13e90572a7eb2e6c66d89ebec0976bd4 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang int64 built-in type. <br>
@@ -16,20 +16,22 @@ import org.opendaylight.yangtools.yang.common.QName;
  * type is {@link Long}.
  *
  */
-public final class Int64 extends AbstractSignedInteger {
-    private static Int64 instance;
-    private static final QName NAME = BaseTypes.constructQName("int64");
+public final class Int64 extends AbstractSignedInteger implements Immutable {
     private static final String DESCRIPTION = "int64  represents integer values between -9223372036854775808 and 9223372036854775807, inclusively.";
 
     private Int64() {
-        super(NAME, DESCRIPTION, Long.MIN_VALUE, Long.MAX_VALUE, "");
+        super(BaseTypes.INT64_QNAME, DESCRIPTION, Long.MIN_VALUE, Long.MAX_VALUE, "");
     }
 
+
+    private static final Int64 INSTANCE = new Int64();
+
+    /**
+     * Returns default instance of int64 type.
+     * @return default instance of int64 type.
+     */
     public static Int64 getInstance() {
-        if (instance == null) {
-            instance = new Int64();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -39,7 +41,6 @@ public final class Int64 extends AbstractSignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.INT64_QNAME;
     }
-
 }
index 5df2db696f39a1391fd71441016c93dde6d6df0e..61d7a469491e3ee910fe29ebb332e9ae085c989f 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang int8 built-in type. <br>
@@ -16,20 +16,21 @@ import org.opendaylight.yangtools.yang.common.QName;
  *
  * @see AbstractSignedInteger
  */
-public final class Int8 extends AbstractSignedInteger {
-    private static Int8 instance;
-    private static final QName NAME = BaseTypes.constructQName("int8");
+public final class Int8 extends AbstractSignedInteger implements Immutable {
     private static final String DESCRIPTION = "represents integer values between -128 and 127, inclusively.";
 
     private Int8() {
-        super(NAME, DESCRIPTION, Byte.MIN_VALUE, Byte.MAX_VALUE, "");
+        super(BaseTypes.INT8_QNAME, DESCRIPTION, Byte.MIN_VALUE, Byte.MAX_VALUE, "");
     }
 
+    private static final Int8 INSTANCE = new Int8();
+
+    /**
+     * Returns default instance of int8 type.
+     * @return default instance of int8 type.
+     */
     public static Int8 getInstance() {
-        if (instance == null) {
-            instance = new Int8();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -39,7 +40,7 @@ public final class Int8 extends AbstractSignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.INT8_QNAME;
     }
 
 }
index 8ef325cfdf3bbc9aba90840b8b404d2c4bcdb0d9..65fd92458f72564de1f9fd084490854fc4c50498 100644 (file)
@@ -17,6 +17,8 @@ import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
 
+import com.google.common.base.Preconditions;
+
 /**
  * The <code>default</code> implementation of Instance Leafref Type Definition
  * interface.
@@ -30,9 +32,21 @@ public final class Leafref implements LeafrefTypeDefinition {
     private static final String REF = "https://tools.ietf.org/html/rfc6020#section-9.9";
 
     private final RevisionAwareXPath xpath;
+    private final SchemaPath path;
 
+    @Deprecated
     public Leafref(final RevisionAwareXPath xpath) {
-        this.xpath = xpath;
+        this(PATH,xpath);
+
+    }
+
+    private Leafref(final SchemaPath path, final RevisionAwareXPath target) {
+        this.path = Preconditions.checkNotNull(path,"path must be specified");
+        this.xpath = Preconditions.checkNotNull(target,"target must not be null.");
+    }
+
+    public static Leafref create(final SchemaPath path,final RevisionAwareXPath target) {
+        return new Leafref(path,target);
     }
 
     @Override
@@ -57,7 +71,7 @@ public final class Leafref implements LeafrefTypeDefinition {
 
     @Override
     public SchemaPath getPath() {
-        return PATH;
+        return path;
     }
 
     @Override
@@ -94,7 +108,7 @@ public final class Leafref implements LeafrefTypeDefinition {
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/LengthConstraintImpl.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/LengthConstraintImpl.java
new file mode 100644 (file)
index 0000000..bbab950
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * 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.model.util;
+
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ * {@link Immutable} implementation of {@link LengthConstraint}.
+ *
+ * Length constraint based on supplied parameters with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link LengthConstraint#getErrorAppTag()} returns
+ * <code>length-out-of-specified-bounds</code>
+ * <li>{@link LengthConstraint#getErrorMessage() returns <code>The argument is
+ * out of bounds &lt;<i>min</i>, <i>max</i> &gt;</code>
+ * </ul
+ */
+final class LengthConstraintImpl implements LengthConstraint, Immutable {
+
+    private final Number min;
+    private final Number max;
+
+    private final String description;
+    private final String reference;
+
+    private final String errorAppTag;
+    private final String errorMessage;
+
+    LengthConstraintImpl(final Number min, final Number max, final Optional<String> description,
+            final Optional<String> reference) {
+        super();
+        this.min = Preconditions.checkNotNull(min, "min must not be null.");
+        this.max = Preconditions.checkNotNull(max, "max must not be null");
+        this.description = description.orNull();
+        this.reference = reference.orNull();
+
+        this.errorAppTag = "length-out-of-specified-bounds";
+        this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
+    }
+
+    @Override
+    public String getDescription() {
+        return description;
+    }
+
+    @Override
+    public String getErrorAppTag() {
+        return errorAppTag;
+    }
+
+    @Override
+    public String getErrorMessage() {
+        return errorMessage;
+    }
+
+    @Override
+    public String getReference() {
+        return reference;
+    }
+
+    @Override
+    public Number getMin() {
+        return min;
+    }
+
+    @Override
+    public Number getMax() {
+        return max;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((description == null) ? 0 : description.hashCode());
+        result = prime * result + errorAppTag.hashCode();
+        result = prime * result + errorMessage.hashCode();
+        result = prime * result + max.hashCode();
+        result = prime * result + min.hashCode();
+        result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(final Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        final LengthConstraintImpl other = (LengthConstraintImpl) obj;
+        if (description == null) {
+            if (other.description != null) {
+                return false;
+            }
+        } else if (!description.equals(other.description)) {
+            return false;
+        }
+        if (errorAppTag == null) {
+            if (other.errorAppTag != null) {
+                return false;
+            }
+        } else if (!errorAppTag.equals(other.errorAppTag)) {
+            return false;
+        }
+        if (errorMessage == null) {
+            if (other.errorMessage != null) {
+                return false;
+            }
+        } else if (!errorMessage.equals(other.errorMessage)) {
+            return false;
+        }
+        if (max != other.max) {
+            return false;
+        }
+        if (min != other.min) {
+            return false;
+        }
+        if (reference == null) {
+            if (other.reference != null) {
+                return false;
+            }
+        } else if (!reference.equals(other.reference)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("LengthConstraintImpl [min=");
+        builder.append(min);
+        builder.append(", max=");
+        builder.append(max);
+        builder.append(", description=");
+        builder.append(description);
+        builder.append(", errorAppTag=");
+        builder.append(errorAppTag);
+        builder.append(", reference=");
+        builder.append(reference);
+        builder.append(", errorMessage=");
+        builder.append(errorMessage);
+        builder.append("]");
+        return builder.toString();
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/PatternConstraintImpl.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/PatternConstraintImpl.java
new file mode 100644 (file)
index 0000000..8ab67a7
--- /dev/null
@@ -0,0 +1,153 @@
+/*
+ * 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.model.util;
+
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ * {@link Immutable} implementation of {@link PatternConstraint}
+ *
+ * Creates an instance of Range constraint based on supplied parameters with
+ * additional behaviour:
+ *
+ * <ul>
+ * <li>{@link PatternConstraint#getErrorAppTag()} returns
+ * <code>invalid-regular-expression</code>
+ * </ul>
+ *
+ */
+final class PatternConstraintImpl implements PatternConstraint, Immutable {
+
+    private final String regex;
+    private final String description;
+    private final String reference;
+
+    private final String errorAppTag;
+    private final String errorMessage;
+
+    public PatternConstraintImpl(final String regex, final Optional<String> description,
+            final Optional<String> reference) {
+        super();
+        this.regex = Preconditions.checkNotNull(regex, "regex must not be null.");
+        this.description = description.orNull();
+        this.reference = reference.orNull();
+
+        // FIXME: Lookup better suitable error tag.
+        errorAppTag = "invalid-regular-expression";
+        // TODO: add erro message
+        errorMessage = "";
+    }
+
+    @Override
+    public String getDescription() {
+        return description;
+    }
+
+    @Override
+    public String getErrorAppTag() {
+        return errorAppTag;
+    }
+
+    @Override
+    public String getErrorMessage() {
+        return errorMessage;
+    }
+
+    @Override
+    public String getReference() {
+        return reference;
+    }
+
+    @Override
+    public String getRegularExpression() {
+        return regex;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((description == null) ? 0 : description.hashCode());
+        result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
+        result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
+        result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+        result = prime * result + regex.hashCode();
+        return result;
+    }
+
+    @Override
+    public boolean equals(final Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        final PatternConstraintImpl other = (PatternConstraintImpl) obj;
+        if (description == null) {
+            if (other.description != null) {
+                return false;
+            }
+        } else if (!description.equals(other.description)) {
+            return false;
+        }
+        if (errorAppTag == null) {
+            if (other.errorAppTag != null) {
+                return false;
+            }
+        } else if (!errorAppTag.equals(other.errorAppTag)) {
+            return false;
+        }
+        if (errorMessage == null) {
+            if (other.errorMessage != null) {
+                return false;
+            }
+        } else if (!errorMessage.equals(other.errorMessage)) {
+            return false;
+        }
+        if (reference == null) {
+            if (other.reference != null) {
+                return false;
+            }
+        } else if (!reference.equals(other.reference)) {
+            return false;
+        }
+        if (regex == null) {
+            if (other.regex != null) {
+                return false;
+            }
+        } else if (!regex.equals(other.regex)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("PatternConstraintImpl [regex=");
+        builder.append(regex);
+        builder.append(", description=");
+        builder.append(description);
+        builder.append(", reference=");
+        builder.append(reference);
+        builder.append(", errorAppTag=");
+        builder.append(errorAppTag);
+        builder.append(", errorMessage=");
+        builder.append(errorMessage);
+        builder.append("]");
+        return builder.toString();
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/RangeConstraintImpl.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/RangeConstraintImpl.java
new file mode 100644 (file)
index 0000000..70acbc8
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * 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.model.util;
+
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ * {@link Immutable} implementation of {@link LengthConstraint}.
+ *
+ * Range constraint based on supplied parameters with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link RangeConstraint#getErrorAppTag()} returns
+ * <code>range-out-of-specified-bounds</code>
+ * <li>{@link RangeConstraint#getErrorMessage() returns <code>The argument is
+ * out of bounds &lt;<i>min</i>, <i>max</i> &gt;</code>
+ * </ul>
+ */
+final class RangeConstraintImpl implements RangeConstraint, Immutable {
+    private final Number min;
+    private final Number max;
+
+    private final String description;
+    private final String reference;
+
+    private final String errorAppTag;
+    private final String errorMessage;
+
+    RangeConstraintImpl(final Number min, final Number max, final Optional<String> description,
+            final Optional<String> reference) {
+        super();
+        this.min = Preconditions.checkNotNull(min, "min must not be null.");
+        this.max = Preconditions.checkNotNull(max, "max must not be null.");
+        this.description = description.orNull();
+        this.reference = reference.orNull();
+
+        this.errorAppTag = "range-out-of-specified-bounds";
+        this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
+    }
+
+    @Override
+    public String getDescription() {
+        return description;
+    }
+
+    @Override
+    public String getErrorAppTag() {
+        return errorAppTag;
+    }
+
+    @Override
+    public String getErrorMessage() {
+        return errorMessage;
+    }
+
+    @Override
+    public String getReference() {
+        return reference;
+    }
+
+    @Override
+    public Number getMin() {
+        return min;
+    }
+
+    @Override
+    public Number getMax() {
+        return max;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((description == null) ? 0 : description.hashCode());
+        result = prime * result + errorAppTag.hashCode();
+        result = prime * result + errorMessage.hashCode();
+        result = prime * result + max.hashCode();
+        result = prime * result + min.hashCode();
+        result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(final Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        final RangeConstraintImpl other = (RangeConstraintImpl) obj;
+        if (description == null) {
+            if (other.description != null) {
+                return false;
+            }
+        } else if (!description.equals(other.description)) {
+            return false;
+        }
+        if (max == null) {
+            if (other.max != null) {
+                return false;
+            }
+        } else if (!max.equals(other.max)) {
+            return false;
+        }
+        if (min == null) {
+            if (other.min != null) {
+                return false;
+            }
+        } else if (!min.equals(other.min)) {
+            return false;
+        }
+        if (reference == null) {
+            if (other.reference != null) {
+                return false;
+            }
+        } else if (!reference.equals(other.reference)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        final StringBuilder builder = new StringBuilder();
+        builder.append("RangeConstraintImpl [min=");
+        builder.append(min);
+        builder.append(", max=");
+        builder.append(max);
+        builder.append(", description=");
+        builder.append(description);
+        builder.append(", reference=");
+        builder.append(reference);
+        builder.append(", errorAppTag=");
+        builder.append(errorAppTag);
+        builder.append(", errorMessage=");
+        builder.append(errorMessage);
+        builder.append("]");
+        return builder.toString();
+    }
+}
\ No newline at end of file
index c5852696e4ec14b9c516d00aae66b1de5397a72b..3ef6d5a64e12eb5a4b08ebdf6ab94f5acbd11f52 100644 (file)
@@ -10,9 +10,9 @@ package org.opendaylight.yangtools.yang.model.util;
 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
 
 /**
- * The <code>default</code> implementation of Instance Rewision Aware XPath
+ * The <code>helper</code> implementation of Instance Rewision Aware XPath
  * interface.
- * 
+ *
  * @see RevisionAwareXPath
  */
 public class RevisionAwareXPathImpl implements RevisionAwareXPath {
@@ -23,7 +23,7 @@ public class RevisionAwareXPathImpl implements RevisionAwareXPath {
     private static final int HASH_BOOLEAN_TRUE = 1231;
     private static final int HASH_BOOLEAN_FALSE = 1237;
 
-    public RevisionAwareXPathImpl(String xpath, boolean absolute) {
+    public RevisionAwareXPathImpl(final String xpath, final boolean absolute) {
         this.xpath = xpath;
         this.absolute = absolute;
     }
@@ -43,7 +43,7 @@ public class RevisionAwareXPathImpl implements RevisionAwareXPath {
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
index 0dc0c19e6b19d2b7e539052d2c15bab45848a6b7..64d7328004e9ea33497b372d351e56ecd4428ca3 100644 (file)
@@ -518,7 +518,7 @@ public final class SchemaContextUtil {
             List<QName> names = sp.getPath();
             List<QName> newNames = new ArrayList<>(names);
             newNames.remove(newNames.size() - 1);
-            SchemaPath newSp = new SchemaPath(newNames, sp.isAbsolute());
+            SchemaPath newSp = SchemaPath.create(newNames, sp.isAbsolute());
             parent = findDataSchemaNode(ctx, newSp);
 
             do {
@@ -541,7 +541,7 @@ public final class SchemaContextUtil {
                         if (nodeNewNames.isEmpty()) {
                             parent = getParentModule((SchemaNode) parent, ctx);
                         } else {
-                            SchemaPath nodeNewSp = new SchemaPath(nodeNewNames, nodeSp.isAbsolute());
+                            SchemaPath nodeNewSp = SchemaPath.create(nodeNewNames, nodeSp.isAbsolute());
                             parent = findDataSchemaNode(ctx, nodeNewSp);
                         }
                     } else {
@@ -574,7 +574,7 @@ public final class SchemaContextUtil {
             List<QName> names = sp.getPath();
             List<QName> newNames = new ArrayList<>(names);
             newNames.remove(newNames.size() - 1);
-            SchemaPath newSp = new SchemaPath(newNames, sp.isAbsolute());
+            SchemaPath newSp = SchemaPath.create(newNames, sp.isAbsolute());
             parent = findDataSchemaNode(ctx, newSp);
             if (parent instanceof AugmentationTarget) {
                 tmpPath.add(currentName);
index c40622ed30d47da7f190ede85f7dc488b9d414d9..857e6a4d030037e89bc8dc7b01607149542a463c 100644 (file)
@@ -7,10 +7,10 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.Status;
@@ -19,15 +19,16 @@ import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
 
+import com.google.common.base.Optional;
+
 /**
  * The <code>default</code> implementation of String Type Definition interface.
  *
  * @see StringTypeDefinition
  */
-public final class StringType implements StringTypeDefinition {
-    private static final StringType INSTANCE = new StringType();
-    private final QName name = BaseTypes.constructQName("string");
-    private final SchemaPath path = new SchemaPath(Collections.singletonList(name), true);
+public final class StringType implements StringTypeDefinition, Immutable {
+    private static final QName NAME = BaseTypes.STRING_QNAME;
+    private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(NAME), true);
     private static final String DEFAULT_VALUE = "";
     private static final String DESCRIPTION = "";
     private static final String REFERENCE = "";
@@ -35,13 +36,13 @@ public final class StringType implements StringTypeDefinition {
     private final List<PatternConstraint> patterns;
     private static final String UNITS = "";
 
+    private static final StringType INSTANCE = new StringType();
+
     /**
      * Default Constructor.
      */
     private StringType() {
-        final List<LengthConstraint> constraints = new ArrayList<LengthConstraint>();
-        constraints.add(BaseConstraints.lengthConstraint(0, Integer.MAX_VALUE, "", ""));
-        lengthStatements = Collections.unmodifiableList(constraints);
+        lengthStatements = Collections.singletonList(BaseConstraints.newLengthConstraint(0, Integer.MAX_VALUE, Optional.of(""), Optional.of("")));
         patterns = Collections.emptyList();
     }
 
@@ -89,7 +90,7 @@ public final class StringType implements StringTypeDefinition {
      */
     @Override
     public QName getQName() {
-        return name;
+        return NAME;
     }
 
     /*
@@ -99,7 +100,7 @@ public final class StringType implements StringTypeDefinition {
      */
     @Override
     public SchemaPath getPath() {
-        return path;
+        return PATH;
     }
 
     /*
@@ -166,14 +167,14 @@ public final class StringType implements StringTypeDefinition {
         final int prime = 31;
         int result = 1;
         result = prime * result + ((lengthStatements == null) ? 0 : lengthStatements.hashCode());
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
-        result = prime * result + ((path == null) ? 0 : path.hashCode());
+        result = prime * result + NAME.hashCode();
+        result = prime * result + PATH.hashCode();
         result = prime * result + ((patterns == null) ? 0 : patterns.hashCode());
         return result;
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
@@ -191,20 +192,6 @@ public final class StringType implements StringTypeDefinition {
         } else if (!lengthStatements.equals(other.lengthStatements)) {
             return false;
         }
-        if (name == null) {
-            if (other.name != null) {
-                return false;
-            }
-        } else if (!name.equals(other.name)) {
-            return false;
-        }
-        if (path == null) {
-            if (other.path != null) {
-                return false;
-            }
-        } else if (!path.getPath().equals(other.path.getPath())) {
-            return false;
-        }
         if (patterns == null) {
             if (other.patterns != null) {
                 return false;
@@ -219,9 +206,9 @@ public final class StringType implements StringTypeDefinition {
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("StringType [name=");
-        builder.append(name);
+        builder.append(NAME);
         builder.append(", path=");
-        builder.append(path);
+        builder.append(PATH);
         builder.append(", defaultValue=");
         builder.append(DEFAULT_VALUE);
         builder.append(", description=");
index 4c386c48d5b3988f083bb794f2840e745158746f..d557449220a153d725772905490748b080c8fe35 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang uint16 built-in type. <br>
@@ -15,21 +15,18 @@ import org.opendaylight.yangtools.yang.common.QName;
  * counterpart of Yang uint16 built-in type is {@link Integer}.
  *
  */
-public final class Uint16 extends AbstractUnsignedInteger {
+public final class Uint16 extends AbstractUnsignedInteger implements Immutable {
     public static final int MAX_VALUE = 65535;
-    private static Uint16 instance;
-    private static final QName NAME = BaseTypes.constructQName("uint16");
     private static final String DESCRIPTION = "uint16 represents integer values between 0 and 65535, inclusively.";
 
+    private static Uint16 INSTANCE = new Uint16();
+
     private Uint16() {
-        super(NAME, DESCRIPTION, MAX_VALUE, "");
+        super(BaseTypes.UINT16_QNAME, DESCRIPTION, MAX_VALUE, "");
     }
 
     public static Uint16 getInstance() {
-        if (instance == null) {
-            instance = new Uint16();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -39,7 +36,7 @@ public final class Uint16 extends AbstractUnsignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.UINT16_QNAME;
     }
 
 }
index dd3183d51bf028fdc605e3381f28fe7920224122..aef0f8fac27ff60928a27d9b251b772c0fab3f54 100644 (file)
@@ -7,28 +7,26 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang uint32 built-in type. <br>
  * uint32 represents integer values between 0 and 4294967295, inclusively.
  *
  */
-public final class Uint32 extends AbstractUnsignedInteger {
+public final class Uint32 extends AbstractUnsignedInteger implements Immutable {
     public static final long MAX_VALUE = 4294967295L;
-    private static Uint32 instance;
-    private static final QName NAME = BaseTypes.constructQName("uint32");
     private static final String DESCRIPTION = "uint32 represents integer values between 0 and 4294967295, inclusively.";
 
+    private static final Uint32 INSTANCE = new Uint32();
+
+
     private Uint32() {
-        super(NAME, DESCRIPTION, MAX_VALUE, "");
+        super(BaseTypes.UINT32_QNAME, DESCRIPTION, MAX_VALUE, "");
     }
 
     public static Uint32 getInstance() {
-        if (instance == null) {
-            instance = new Uint32();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -38,7 +36,7 @@ public final class Uint32 extends AbstractUnsignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.UINT32_QNAME;
     }
 
 }
index 555b76f5feb96ac74a99ee4d285a5edb707b9bae..3ec9d25369eb3c966fab370a661cc0a8aea750ab 100644 (file)
@@ -9,7 +9,7 @@ package org.opendaylight.yangtools.yang.model.util;
 
 import java.math.BigInteger;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang uint64 built-in type. <br>
@@ -18,21 +18,18 @@ import org.opendaylight.yangtools.yang.common.QName;
  * {@link BigInteger}.
  *
  */
-public final class Uint64 extends AbstractUnsignedInteger {
+public final class Uint64 extends AbstractUnsignedInteger implements Immutable {
     public static final BigInteger MAX_VALUE = new BigInteger("18446744073709551615");
-    private static Uint64 instance;
-    private static final QName NAME = BaseTypes.constructQName("uint64");
     private static final String DESCRIPTION = "uint64 represents integer values between 0 and 18446744073709551615, inclusively.";
 
+    private static final Uint64 INSTANCE = new Uint64();
+
     private Uint64() {
-        super(NAME, DESCRIPTION, MAX_VALUE, "");
+        super(BaseTypes.UINT64_QNAME, DESCRIPTION, MAX_VALUE, "");
     }
 
     public static Uint64 getInstance() {
-        if (instance == null) {
-            instance = new Uint64();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -42,7 +39,7 @@ public final class Uint64 extends AbstractUnsignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.UINT64_QNAME;
     }
 
 }
index 2212585f0238e69746df6a75f79b2e86424077cd..f44ba754a7d62c8c94310382c1e0b2c569799f62 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
 
 /**
  * Implementation of Yang uint8 built-in type. <br>
@@ -15,21 +15,18 @@ import org.opendaylight.yangtools.yang.common.QName;
  *
  * @see AbstractUnsignedInteger
  */
-public final class Uint8 extends AbstractUnsignedInteger {
+public final class Uint8 extends AbstractUnsignedInteger implements Immutable {
     public static final int MAX_VALUE = 255;
-    private static Uint8 instance;
-    private static final QName NAME = BaseTypes.constructQName("uint8");
     private static final String DESCRIPTION = "uint8  represents integer values between 0 and 255, inclusively.";
 
+    private static final Uint8 INSTANCE = new Uint8();
+
     private Uint8() {
-        super(NAME, DESCRIPTION, MAX_VALUE, "");
+        super(BaseTypes.UINT8_QNAME, DESCRIPTION, MAX_VALUE, "");
     }
 
     public static Uint8 getInstance() {
-        if (instance == null) {
-            instance = new Uint8();
-        }
-        return instance;
+        return INSTANCE;
     }
 
     @Override
@@ -39,7 +36,7 @@ public final class Uint8 extends AbstractUnsignedInteger {
 
     @Override
     public String toString() {
-        return "type " + NAME;
+        return "type " + BaseTypes.UINT8_QNAME;
     }
 
 }
index 99390b09803a438152bba18f0cee6ceaf8e196b5..3386bb720f5e238d8760f6b1cc7bc765070d3e7e 100644 (file)
@@ -17,18 +17,23 @@ import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
 public final class UnionType implements UnionTypeDefinition {
-    private final QName name = BaseTypes.constructQName("union");
-    private final SchemaPath path = BaseTypes.schemaPath(name);
+    private final SchemaPath path = SchemaPath.create(Collections.singletonList(BaseTypes.UNION_QNAME),true);
     private static final String DESCRIPTION = "The union built-in type represents a value that corresponds to one of its member types.";
     private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.12";
     private final List<TypeDefinition<?>> types;
 
-    public UnionType(List<TypeDefinition<?>> types) {
-        if (types == null) {
-            throw new IllegalArgumentException("When the type is 'union', the 'type' statement MUST be present.");
-        }
-        this.types = types;
+    @Deprecated
+    public UnionType(final List<TypeDefinition<?>> types) {
+        Preconditions.checkNotNull(types,"When the type is 'union', the 'type' statement MUST be present.");
+        this.types = ImmutableList.copyOf(types);
+    }
+
+    public static UnionType create(final List<TypeDefinition<?>> types) {
+        return new UnionType(types);
     }
 
     @Override
@@ -48,7 +53,7 @@ public final class UnionType implements UnionTypeDefinition {
 
     @Override
     public QName getQName() {
-        return name;
+        return BaseTypes.UNION_QNAME;
     }
 
     @Override
@@ -90,7 +95,7 @@ public final class UnionType implements UnionTypeDefinition {
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
@@ -111,7 +116,7 @@ public final class UnionType implements UnionTypeDefinition {
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("type ");
-        builder.append(name);
+        builder.append(BaseTypes.UNION_QNAME);
         builder.append(" (types=[");
         for (TypeDefinition<?> td : types) {
             builder.append(", " + td.getQName().getLocalName());
index 23bb8395ca059cf83eeb61e7863a3e4d977d43d2..2e23b81db600af9e5db25af9b484a543aee50527 100644 (file)
@@ -19,6 +19,16 @@ import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
 
+/**
+ * Utility implementation of unknown type definition.
+ *
+ * Unknown type definition is derived type, for
+ * which base built-in type is not yet known. This types
+ * are possible during parsing and resolving of YANG model
+ * without all requisites allready processed.
+ *
+ *
+ */
 public final class UnknownType implements UnknownTypeDefinition {
 
     private final QName name;
@@ -66,12 +76,12 @@ public final class UnknownType implements UnknownTypeDefinition {
             this.path = BaseTypes.schemaPath(name);
         }
 
-        public Builder description(String description) {
+        public Builder description(final String description) {
             this.description = description;
             return this;
         }
 
-        public Builder reference(String reference) {
+        public Builder reference(final String reference) {
             this.reference = reference;
             return this;
         }
@@ -106,12 +116,12 @@ public final class UnknownType implements UnknownTypeDefinition {
             return this;
         }
 
-        public Builder status(Status status) {
+        public Builder status(final Status status) {
             this.status = status;
             return this;
         }
 
-        public Builder units(String units) {
+        public Builder units(final String units) {
             this.units = units;
             return this;
         }
@@ -126,7 +136,7 @@ public final class UnknownType implements UnknownTypeDefinition {
         }
     }
 
-    private UnknownType(Builder builder) {
+    private UnknownType(final Builder builder) {
         this.name = builder.name;
         this.path = builder.path;
         this.description = builder.description;
@@ -296,7 +306,7 @@ public final class UnknownType implements UnknownTypeDefinition {
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
index f156dafabcfe7ee550d6d8a3d59fb86e3f4cf30c..98c63d022ba6a8a3a734a7b03897e8526e174afc 100644 (file)
@@ -7,83 +7,40 @@
  */
 package org.opendaylight.yangtools.yang.model.util;
 
-import java.util.HashSet;
-import java.util.Set;
-
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 
+/**
+ * Utility class which provides various helper methods for working with YANG
+ * built-in types.
+ *
+ * @deprecated Use {@link BaseTypes} instead.
+ */
+@Deprecated
 public final class YangTypesConverter {
-    private static final Set<String> BASE_YANG_TYPES = new HashSet<String>();
-
     /**
      * It isn't desirable to create the instances of this class
      */
     private YangTypesConverter() {
     }
 
-    static {
-        BASE_YANG_TYPES.add("binary");
-        BASE_YANG_TYPES.add("bits");
-        BASE_YANG_TYPES.add("boolean");
-        BASE_YANG_TYPES.add("decimal64");
-        BASE_YANG_TYPES.add("empty");
-        BASE_YANG_TYPES.add("enumeration");
-        BASE_YANG_TYPES.add("identityref");
-        BASE_YANG_TYPES.add("instance-identifier");
-        BASE_YANG_TYPES.add("int8");
-        BASE_YANG_TYPES.add("int16");
-        BASE_YANG_TYPES.add("int32");
-        BASE_YANG_TYPES.add("int64");
-        BASE_YANG_TYPES.add("leafref");
-        BASE_YANG_TYPES.add("string");
-        BASE_YANG_TYPES.add("uint8");
-        BASE_YANG_TYPES.add("uint16");
-        BASE_YANG_TYPES.add("uint32");
-        BASE_YANG_TYPES.add("uint64");
-        BASE_YANG_TYPES.add("union");
-    }
-
-    public static boolean isBaseYangType(String type) {
-        return BASE_YANG_TYPES.contains(type);
+    @Deprecated
+    public static boolean isBaseYangType(final String type) {
+        return BaseTypes.isYangBuildInType(type);
     }
 
-    public static TypeDefinition<?> javaTypeForBaseYangType(String typeName) {
-        TypeDefinition<?> type = null;
-
-        if (typeName.startsWith("int")) {
-            if ("int8".equals(typeName)) {
-                type = Int8.getInstance();
-            } else if ("int16".equals(typeName)) {
-                type = Int16.getInstance();
-            } else if ("int32".equals(typeName)) {
-                type = Int32.getInstance();
-            } else if ("int64".equals(typeName)) {
-                type = Int64.getInstance();
-            }
-        } else if (typeName.startsWith("uint")) {
-            if ("uint8".equals(typeName)) {
-                type = Uint8.getInstance();
-            } else if ("uint16".equals(typeName)) {
-                type = Uint16.getInstance();
-            } else if ("uint32".equals(typeName)) {
-                type = Uint32.getInstance();
-            } else if ("uint64".equals(typeName)) {
-                type = Uint64.getInstance();
-            }
-        } else if ("string".equals(typeName)) {
-            type = StringType.getInstance();
-        } else if ("binary".equals(typeName)) {
-            type = BinaryType.getInstance();
-        } else if ("boolean".equals(typeName)) {
-            type = BooleanType.getInstance();
-        } else if ("empty".equals(typeName)) {
-            type = EmptyType.getInstance();
-        } else if ("instance-identifier".equals(typeName)) {
-            // FIXME
-            type = new InstanceIdentifier(null, true);
-        }
-
-        return type;
+    /**
+     *
+     * Returns default instance of built-in type for supplied string.
+     *
+     * @param typeName
+     * @return default instance of built-in type for supplied string or null, if
+     *         default instance does not exist.
+     *
+     * @deprecated Use {@link BaseTypes#defaultBaseTypeFor(String)} instead.
+     */
+    @Deprecated
+    public static TypeDefinition<?> javaTypeForBaseYangType(final String typeName) {
+        return BaseTypes.defaultBaseTypeFor(typeName).orNull();
     }
 
 }
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/package-info.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/package-info.java
new file mode 100644 (file)
index 0000000..ec30f79
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * 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
+ */
+/**
+ * Utility classes and implementations for concepts defined in yang-model-api.
+ *
+ *
+ * <h2>Base Types</h2>
+ *
+ * YANG specification defines several base types, for which YANG model does not
+ * exists, but have same properties as derived types. This package provides
+ * implementation of {@link org.opendaylight.yangtools.yang.model.api.TypeDefinition}
+ * interface and it's subinterfaces which represent YANG base types and
+ * types derived from them.
+ * <p>
+ * YANG Specification implicitly defines two types of base types - ones with default version,
+ * and ones which needs to be derived.
+ *
+ * <h3>Base built-in types with default instance and semantics</h3>
+ *
+ *    <dl>
+ *       <dt>empty</dt>
+ *       <dd>A leaf that does not have any value - {@link org.opendaylight.yangtools.yang.model.util.EmptyType}</dd>
+ *       <dt>binary</dt>
+ *       <dd>Any binary data - {@link org.opendaylight.yangtools.yang.model.util.BinaryType}
+ *       <dt>boolean</dt>
+ *       <dd>"true" or "false" - {@link org.opendaylight.yangtools.yang.model.util.BinaryType}</dd>
+ *       <dt>int8</dt>
+ *       <dd>8-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int8}</dd>
+ *       <dt>int16</dt>
+ *       <dd>16-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int16}</dd>
+ *       <dt>int32</dt>
+ *       <dd>32-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int32}</dd>
+ *       <dt>int64</dt>
+ *       <dd>64-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int64}</dd>
+ *       <dt>uint8</dt>
+ *       <dd>8-bit unsigned integer -{@link org.opendaylight.yangtools.yang.model.util.Uint8}</dd>
+ *       <dt>uint16</dt>
+ *       <dd>16-bit unsigned integer - {@link org.opendaylight.yangtools.yang.model.util.Int16}</dd>
+ *       <dt>uint32</dt>
+ *       <dd>32-bit unsigned integer - {@link org.opendaylight.yangtools.yang.model.util.Int32}</dd>
+ *       <dt>uint64</dt>
+ *       <dd>64-bit unsigned integer -{@link org.opendaylight.yangtools.yang.model.util.Int64}</dd>
+ *       <dt>instance-identifier</dt>
+ *       <dd>References a data tree node - {@link org.opendaylight.yangtools.yang.model.util.InstanceIdentifier}</dd>
+ *       <dt>string</dt>
+ *       <dd>{@link org.opendaylight.yangtools.yang.model.util.StringType}</dd>
+ *     </dl>
+ *
+ * Common trait of base types with default instance is, that there is no requirement
+ * for user input in YANG schema to further modify this types.
+ * <p>
+ * The implementation classes for these base types contains static method <code>getInstance()</code>
+ * which provides reusable {@link org.opendaylight.yangtools.concepts.Immutable} instance of type.
+ *
+ * <h3>Base built-in types without default instance</h3>
+ *
+ *     <dl>
+ *       <dt>bits</dt>
+ *       <dd>A set of bits or flags - {@link org.opendaylight.yangtools.yang.model.util.BitsType}</dd>
+ *       <dt>decimal64</dt>
+ *       <dd>64-bit signed decimal number - {@link org.opendaylight.yangtools.yang.model.util.Decimal64}</dd>
+ *       <dt>enumeration</dt>
+ *       <dd>Enumerated strings - {@link org.opendaylight.yangtools.yang.model.util.EnumerationType}</dd>
+ *       <dt>union</dt>
+ *       <dd>Choice of member types - {@link org.opendaylight.yangtools.yang.model.util.UnionType}</dd>
+ *       <dt>identity-ref</dt>
+ *       <dd>A reference to an abstract identity - {@link org.opendaylight.yangtools.yang.model.util.IdentityrefType}</dd>
+ *       <dt>leafref</dt>
+ *       <dd>A reference to a leaf instance - {@link org.opendaylight.yangtools.yang.model.util.Leafref}</dd>
+ *     </dl>
+ *
+ * Common trait of these base types without default instance is, that they require
+ * user input in YANG schema to create instance of this types, and may have infinity number of
+ * possible permutations.
+ * <p>
+ * The implementations have static factory method <code>create(SchemaPath,...)</code>
+ * which provides {@link org.opendaylight.yangtools.concepts.Immutable} instance of type.
+ *
+ */
+package org.opendaylight.yangtools.yang.model.util;
\ No newline at end of file
index bbe870bd76951ba5a6e3a1b2f64801b10960a72f..6b1d6c61232e0221c718d15a9a16a95a0b03df54 100644 (file)
@@ -8,44 +8,68 @@
 package org.opendaylight.yangtools.yang.model.util.repo;
 
 import org.opendaylight.yangtools.concepts.Delegator;
+
+import com.google.common.annotations.Beta;
 import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 
-import static com.google.common.base.Preconditions.*;
 
+/**
+ *
+ * Abstract caching schema provider with support of multiple context
+ * per backing {@link SchemaSourceProvider}.
+ *
+ * @param <I> Input Schema Source Representation
+ * @param <O> Output Schema Source Representation
+ */
 public abstract class AbstractCachingSchemaSourceProvider<I, O> implements AdvancedSchemaSourceProvider<O>,
         Delegator<AdvancedSchemaSourceProvider<I>> {
 
-    public class CompatibilitySchemaSourceProviderInstance implements SchemaSourceProvider<O> {
-
-        @Override
-        public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-    }
-
     private final AdvancedSchemaSourceProvider<I> defaultDelegate;
 
-    protected AbstractCachingSchemaSourceProvider(AdvancedSchemaSourceProvider<I> delegate) {
+    /**
+     * Construct caching schema source provider with supplied delegate.
+     *
+     * Default delegate is is used to retrieve schema source when cache does not
+     * contain requested sources.
+     *
+     * @param delegate SchemaSourceProvided used to look up and retrieve schema source
+     * when cache does not contain requested sources.
+     */
+    protected AbstractCachingSchemaSourceProvider(final AdvancedSchemaSourceProvider<I> delegate) {
         this.defaultDelegate = delegate;
     }
 
     @Override
-    public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
-        checkNotNull(moduleName, "Module name should not be null.");
-        checkNotNull(revision, "Revision should not be null");
+    public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
+        Preconditions.checkNotNull(moduleName, "Module name should not be null.");
+        Preconditions.checkNotNull(revision, "Revision should not be null");
         return getSchemaSource(SourceIdentifier.create(moduleName, revision));
     }
-    
+
     @Override
-    public Optional<O> getSchemaSource(SourceIdentifier sourceIdentifier) {
+    public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
         return getSchemaSourceImpl(sourceIdentifier, defaultDelegate);
     }
 
-    protected final Optional<O> getSchemaSourceImpl(SourceIdentifier identifier,
-            AdvancedSchemaSourceProvider<I> delegate) {
-        checkNotNull(identifier, "Source identifier name should not be null.");
+    /**
+     * Actual implementation of schema source retrieval.
+     *
+     * <ul>
+     * <li>look up cached schema source via {@link #getCachedSchemaSource(SourceIdentifier)}
+     * <li>If source was found in cache, returns source to client code.
+     * <li>If source was not found in cache, Look up schema source in supplied <code>delegate</code>
+     * <li>Updates cache with schema from delegate by {@link #cacheSchemaSource(SourceIdentifier, Optional)}
+     * <li>Result is returned to client code.
+     * </ul>
+     *
+     * @param identifier Source identifier
+     * @param delegate Delegate to lookup if there is a miss.
+     * @return Optional of schema source, present if source was found. Absent otherwise.
+     */
+    protected final Optional<O> getSchemaSourceImpl(final SourceIdentifier identifier,
+            final AdvancedSchemaSourceProvider<I> delegate) {
+        Preconditions.checkNotNull(identifier, "Source identifier name should not be null.");
 
         Optional<O> cached = getCachedSchemaSource(identifier);
         if (cached.isPresent()) {
@@ -55,33 +79,81 @@ public abstract class AbstractCachingSchemaSourceProvider<I, O> implements Advan
         return cacheSchemaSource(identifier, live);
     }
 
-    abstract protected Optional<O> cacheSchemaSource(SourceIdentifier identifier, Optional<I> stream);
-
+    /**
+     * Caches supplied result and returns cached result which should be returned to client.
+     *
+     * <p>
+     * Implementations of cache are required to cache schema source if possible.
+     * They are not required to cache {@link Optional#absent()}.
+     *
+     * Implementations are required to transform source representation if <code>O</code> and <code>I</code>
+     * are different.
+     *
+     * This method SHOULD NOT fail and should recover from Runtime exceptions
+     * by not caching source and only transforming it.
+     *
+     * @param identifier Source Identifier for which schema SHOULD be cached
+     * @param input Optional of schema source, representing one returned from delegate.
+     * @return Optional of schema source, representing result returned from this cache.
+     */
+    abstract protected Optional<O> cacheSchemaSource(SourceIdentifier identifier, Optional<I> input);
+
+    /**
+     * Returns cached schema source of {@link Optional#absent()} if source is not present in cache.
+     *
+     * <p>
+     * Implementations of cache MUST return cached schema source, if it is present in cache,
+     * otherwise source will be requested from deleate and then cache will be updated
+     * via {@link #cacheSchemaSource(SourceIdentifier, Optional)}.
+     *
+     * @param identifier Source Identifier for which schema should be retrieved.
+     * @return Cached schema source.
+     */
     abstract protected Optional<O> getCachedSchemaSource(SourceIdentifier identifier);
 
+    @Override
     public AdvancedSchemaSourceProvider<I> getDelegate() {
         return defaultDelegate;
     }
 
-    public SchemaSourceProvider<O> createInstanceFor(SchemaSourceProvider<I> delegate) {
-        checkNotNull(delegate, "Delegate should not be null");
+    /**
+     * Creates an lightweight instance of source provider, which uses this cache for caching
+     * and supplied additional delegate for lookup of not cached sources.
+     * <p>
+     *
+     * @param delegate Backing {@link SchemaSourceProvider} which should be used for lookup
+     *   for sources not present in schema.
+     * @return new instance of {@link SchemaSourceProvider} which first lookup in cache
+     *   and then in delegate.
+     *
+     */
+    @Beta
+    public SchemaSourceProvider<O> createInstanceFor(final SchemaSourceProvider<I> delegate) {
         return new SchemaSourceProviderInstance(SchemaSourceProviders.toAdvancedSchemaSourceProvider(delegate));
-            
+
     }
 
+    /**
+     *
+     * Lightweight instance of source provider, which is associated with parent
+     * {@link AbstractCachingSchemaSourceProvider}, but uses
+     * different delegate for retrieving not cached sources.
+     *
+     */
+    @Beta
     private class SchemaSourceProviderInstance implements //
-    AdvancedSchemaSourceProvider<O>, 
+    AdvancedSchemaSourceProvider<O>,
     Delegator<AdvancedSchemaSourceProvider<I>> {
 
         private final AdvancedSchemaSourceProvider<I> delegate;
 
-        protected SchemaSourceProviderInstance(AdvancedSchemaSourceProvider<I> delegate) {
+        protected SchemaSourceProviderInstance(final AdvancedSchemaSourceProvider<I> delegate) {
             super();
-            this.delegate = delegate;
+            this.delegate = Preconditions.checkNotNull(delegate, "Delegate should not be null");;
         }
 
         @Override
-        public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
+        public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
             return getSchemaSource(SourceIdentifier.create(moduleName, revision));
         }
 
@@ -91,7 +163,7 @@ public abstract class AbstractCachingSchemaSourceProvider<I, O> implements Advan
         }
 
         @Override
-        public Optional<O> getSchemaSource(SourceIdentifier sourceIdentifier) {
+        public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
             return getSchemaSourceImpl(sourceIdentifier, getDelegate());
         }
     }
index 1c7ffa1da54889bb04077f73c52fc21bd118f7d0..0b82e089089b317403b1a0ecac5a8609f7adb91f 100644 (file)
@@ -9,7 +9,51 @@ package org.opendaylight.yangtools.yang.model.util.repo;
 
 import com.google.common.base.Optional;
 
-public interface AdvancedSchemaSourceProvider<F> extends SchemaSourceProvider<F> {
+/**
+ * Provider of representation of YANG schema sources.
+ *
+ * <p>
+ * {@link AdvancedSchemaSourceProvider} is extension of
+ * {@link SchemaSourceProvider} which did not have object concept of source
+ * identifier, and introduces {@link SourceIdentifier} (which contains schema
+ * name and revision) as identifier of sources.
+ *
+ * <p>
+ * <b>Schema Source representation</b>
+ * <p>
+ * Representation of schema source. Representation of schema source could exists
+ * in various formats (Java types), depending on stage of processing, but
+ * representation MUST BE still result of processing of only single unit of schema
+ * source (file, input stream). E.g.:
+ * <ul>
+ * <li>{@link java.lang.String} - textual representation of source code
+ * <li>{@link java.io.InputStream} - input stream containing source code
+ * <li>{@link com.google.common.io.ByteSource} - source for input streams
+ * containing source code
+ * <li>Parsed AST - abstract syntax tree, which is result of a parser, but still
+ * it is not linked against other schemas.
+ *
+ * <p>
+ * Conversion between representations should be done via implementations of
+ * {@link SchemaSourceTransformation}.
+ *
+ * @param <T>
+ *            Schema source representation type provided by this implementation
+ */
+public interface AdvancedSchemaSourceProvider<T> extends SchemaSourceProvider<T> {
 
-    Optional<F> getSchemaSource(SourceIdentifier sourceIdentifier);
+    /**
+     * Returns representation source for supplied YANG source identifier.
+     *
+     * Returned representation of schema source must be immutable, must not
+     * change during runtime if {@link SourceIdentifier} has specified both
+     * {@link SourceIdentifier#getName()} and
+     * {@link SourceIdentifier#getRevision()}
+     *
+     * @param sourceIdentifier
+     *            source identifier.
+     * @return source representation if supplied YANG module is available
+     *         {@link Optional#absent()} otherwise.
+     */
+    Optional<T> getSchemaSource(SourceIdentifier sourceIdentifier);
 }
index 153a110c473f76c9ce486c7b968b2af6e2b56799..71ab88bfc4c0049b46c44eb8242d7a5ce1e767c1 100644 (file)
@@ -32,21 +32,83 @@ import com.google.common.base.Function;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 
-public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSourceProvider<I, InputStream> {
+/**
+ * Filesystem-based schema caching source provider
+ *
+ * This schema source provider caches all YANG modules loaded from backing
+ * schema source providers (registered via
+ * {@link #createInstanceFor(SchemaSourceProvider)} to supplied folder.
+ *
+ * @param <I>
+ *            Input format in which schema source is represented.
+ *
+ */
+public final class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSourceProvider<I, InputStream> {
     private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaCachingProvider.class);
 
     private final File storageDirectory;
-    private final Function<I, String> transformationFunction;
+    private final SchemaSourceTransformation<I, String> transformationFunction;
+
+    /**
+     *
+     * Construct filesystem caching schema source provider.
+     *
+     *
+     * @param delegate
+     *            Default delegate to lookup for missed entries in cache.
+     * @param directory
+     *            Directory where YANG files should be cached.
+     * @param transformationFunction
+     *            Transformation function which translates from input in format
+     *            <code>I</code> to InputStream.
+     * @throws IllegalArgumentException
+     *             If supplied directory does not exists or is not directory.
+     */
+    public FilesystemSchemaCachingProvider(final AdvancedSchemaSourceProvider<I> delegate, final File directory,
+            final SchemaSourceTransformation<I, String> transformationFunction) {
+        super(delegate);
+        Preconditions.checkNotNull(directory, "directory must not be null.");
+        Preconditions.checkArgument(directory.exists(), "directory must be directory.");
+        Preconditions.checkArgument(directory.isDirectory(), "directory must be directory.");
+        this.storageDirectory = directory;
+        this.transformationFunction = Preconditions.checkNotNull(transformationFunction,
+                "transformationFunction must not be null.");
+    }
 
+    /**
+     *
+     * Construct filesystem caching schema source provider.
+     *
+     *
+     * @param delegate
+     *            Default delegate to lookup for missed entries in cache.
+     * @param directory
+     *            Directory where YANG files should be cached.
+     * @param transformationFunction
+     *            Transformation function which translates from input in format
+     *            <code>I</code> to InputStream.
+     * @throws IllegalArgumentException
+     *             If supplied directory does not exists or is not directory.
+     * @deprecated Use
+     *             {@link #FilesystemSchemaCachingProvider(AdvancedSchemaSourceProvider, File, SchemaSourceTransformation)}
+     *             with
+     *             {@link SchemaSourceProviders#schemaSourceTransformationFrom(Function)}
+     *             instead.
+     */
+    @Deprecated
     public FilesystemSchemaCachingProvider(final AdvancedSchemaSourceProvider<I> delegate, final File directory,
             final Function<I, String> transformationFunction) {
         super(delegate);
+        Preconditions.checkNotNull(directory, "directory must not be null.");
+        Preconditions.checkArgument(directory.exists(), "directory must be directory.");
+        Preconditions.checkArgument(directory.isDirectory(), "directory must be directory.");
         this.storageDirectory = directory;
-        this.transformationFunction = transformationFunction;
+        this.transformationFunction = SchemaSourceProviders.schemaSourceTransformationFrom(transformationFunction);
     }
 
     @Override
-    protected synchronized Optional<InputStream> cacheSchemaSource(final SourceIdentifier identifier, final Optional<I> source) {
+    protected synchronized Optional<InputStream> cacheSchemaSource(final SourceIdentifier identifier,
+            final Optional<I> source) {
         File schemaFile = toFile(identifier);
         try {
             if (source.isPresent() && schemaFile.createNewFile()) {
@@ -55,25 +117,25 @@ public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSou
                     writer.write(transformToString(source.get()));
                     writer.flush();
                 } catch (IOException e) {
-
+                    LOG.warn("Could not chache source for {}. Source: ",identifier,source.get(),e);
                 }
             }
         } catch (IOException e) {
-
+            LOG.warn("Could not create cache file for {}. File: ",identifier,schemaFile,e);
         }
         return transformToStream(source);
     }
 
     private Optional<InputStream> transformToStream(final Optional<I> source) {
         if (source.isPresent()) {
-            return Optional.<InputStream> of(
-                    new ByteArrayInputStream(transformToString(source.get()).getBytes(Charsets.UTF_8)));
+            return Optional.<InputStream> of(new ByteArrayInputStream(transformToString(source.get()).getBytes(
+                    Charsets.UTF_8)));
         }
         return Optional.absent();
     }
 
     private String transformToString(final I input) {
-        return transformationFunction.apply(input);
+        return transformationFunction.transform(input);
     }
 
     @Override
@@ -104,6 +166,7 @@ public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSou
     private File findFileWithNewestRev(final SourceIdentifier identifier) {
         File[] files = storageDirectory.listFiles(new FilenameFilter() {
             final String regex = identifier.getName() + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)";
+
             @Override
             public boolean accept(final File dir, final String name) {
                 if (name.matches(regex)) {
@@ -147,13 +210,6 @@ public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSou
         return file;
     }
 
-    private static final Function<String, String> NOOP_TRANSFORMATION = new Function<String, String>() {
-        @Override
-        public String apply(final String input) {
-            return input;
-        }
-    };
-
     public static FilesystemSchemaCachingProvider<String> createFromStringSourceProvider(
             final SchemaSourceProvider<String> liveProvider, final File directory) {
         Preconditions.checkNotNull(liveProvider);
@@ -162,6 +218,6 @@ public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSou
         return new FilesystemSchemaCachingProvider<String>(
                 SchemaSourceProviders.toAdvancedSchemaSourceProvider(liveProvider),//
                 directory, //
-                NOOP_TRANSFORMATION);
+                SchemaSourceProviders.<String>identityTransformation());
     }
 }
index b2fd12fbbe423c0e2ca9d27e091beb235c0f87c2..8804eaacd12231617461d4c9907d0787e4152f30 100644 (file)
@@ -8,9 +8,18 @@
 package org.opendaylight.yangtools.yang.model.util.repo;
 
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
 
+
+/**
+ * Represent Schema Service.
+ *
+ *
+ * @deprecated Replaced by {@link SchemaContextHolder}, which provides
+ *    component-local view for actual {@link SchemaContext}.
+ */
+@Deprecated
 public interface SchemaService {
 
-    
     SchemaContext getSchemaContext();
 }
index 2e56634adf9b6134d7641ed52da34011e2010c23..82fea38e4a296c99aace36e74499f6c1b290a1b3 100644 (file)
@@ -9,8 +9,28 @@ package org.opendaylight.yangtools.yang.model.util.repo;
 
 import com.google.common.base.Optional;
 
+/**
+ * Provider of text stream representation of YANG Modules
+ *
+ * Provider is holder / user implemented service, which
+ * may be able to retrieve representation of YANG sources
+ * for other components.
+ *
+ * @param <F> Format in which YANG source is represented.
+ */
 public interface SchemaSourceProvider<F> {
 
+    /**
+     * Returns source for supplied YANG module identifier and revision.
+     *
+     * @param moduleName module name
+     * @param revision revision of module
+     * @return source representation if supplied YANG module is available
+     *  {@link Optional#absent()} otherwise.
+     *  @deprecated Use {@link AdvancedSchemaSourceProvider#getSchemaSource(SourceIdentifier)}
+     *     instead.
+     */
+    @Deprecated
     Optional<F> getSchemaSource(String moduleName, Optional<String> revision);
 
 }
index 10fa4d52a2cab66a3603e66740bb3e5b26a445f9..24a92ba872215c730733af4426fbba2156336e62 100644 (file)
  */
 package org.opendaylight.yangtools.yang.model.util.repo;
 
+import java.io.ByteArrayInputStream;
 import java.io.InputStream;
-import java.io.StringBufferInputStream;
 
 import org.opendaylight.yangtools.concepts.Delegator;
 
+import com.google.common.base.Charsets;
+import com.google.common.base.Function;
 import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 
-public class SchemaSourceProviders {
+/**
+ *
+ * Utility functions for {@link SchemaSourceProvider}
+ *
+ */
+public final class SchemaSourceProviders {
 
     @SuppressWarnings("rawtypes")
     private static final SchemaSourceProvider NOOP_PROVIDER = new AdvancedSchemaSourceProvider() {
 
         @Override
-        public Optional getSchemaSource(String moduleName, Optional revision) {
+        public Optional getSchemaSource(final String moduleName, final Optional revision) {
             return Optional.absent();
         }
 
         @Override
-        public Optional getSchemaSource(SourceIdentifier sourceIdentifier) {
+        public Optional getSchemaSource(final SourceIdentifier sourceIdentifier) {
             return Optional.absent();
         }
 
     };
 
+    @SuppressWarnings("rawtypes")
+    private static final SchemaSourceTransformation IDENTITY_TRANFORMATION = new IdentityTransformation();
+
+    private static final StringToInputStreamTransformation STRING_TO_INPUTSTREAM_TRANSFORMATION = new StringToInputStreamTransformation();
+
+    private SchemaSourceProviders() {
+        throw new UnsupportedOperationException("Utility class.");
+    }
+
+    /**
+     * Returns a noop schema source provider.
+     *
+     * Noop schema provider returns {@link Optional#absent()} for each call to
+     * query schema source.
+     *
+     * @return
+     */
     @SuppressWarnings("unchecked")
     public static <T> SchemaSourceProvider<T> noopProvider() {
-        return (SchemaSourceProvider<T>) NOOP_PROVIDER;
+        return NOOP_PROVIDER;
     }
 
+    /**
+     *
+     * Returns delegating schema source provider which returns InputStream from
+     * supplied String based schema source provider.
+     *
+     * @param delegate
+     * @return
+     */
     public static SchemaSourceProvider<InputStream> inputStreamProviderfromStringProvider(
-            AdvancedSchemaSourceProvider<String> delegate) {
-        return new StringToInputStreamSchemaSourceProvider(delegate);
+            final AdvancedSchemaSourceProvider<String> delegate) {
+        return TransformingSourceProvider.create(delegate, STRING_TO_INPUTSTREAM_TRANSFORMATION);
     }
 
-    public static <O> AdvancedSchemaSourceProvider<O> toAdvancedSchemaSourceProvider(SchemaSourceProvider<O> schemaSourceProvider) {
+    /**
+     * Returns identity implementation of SchemaSourceTransformation
+     *
+     * Identity implementation of SchemaSourceTransformation is useful
+     * for usecases where Input and Output of SchemaSourceTransformation
+     * are identitcal, and you want to reuse input as an output.
+     *
+     * This implementation is really simple <code>return input;</code>.
+     *
+     * @return
+     */
+    @SuppressWarnings("unchecked")
+    public static <I> SchemaSourceTransformation<I, I> identityTransformation() {
+        return IDENTITY_TRANFORMATION;
+    }
+
+    public static <I, O> SchemaSourceTransformation<I, O> schemaSourceTransformationFrom(
+            final Function<I, O> transformation) {
+        return new FunctionBasedSchemaSourceTransformation<I, O>(transformation);
+    }
+
+    /**
+     *
+     * Casts {@link SchemaSourceProvider} to
+     * {@link AdvancedSchemaSourceProvider} or wraps it with utility
+     * implementation if supplied delegate does not implement
+     * {@link AdvancedSchemaSourceProvider}.
+     *
+     * @param schemaSourceProvider
+     */
+    public static <O> AdvancedSchemaSourceProvider<O> toAdvancedSchemaSourceProvider(
+            final SchemaSourceProvider<O> schemaSourceProvider) {
         if (schemaSourceProvider instanceof AdvancedSchemaSourceProvider<?>) {
             return (AdvancedSchemaSourceProvider<O>) schemaSourceProvider;
         }
         return new SchemaSourceCompatibilityWrapper<O>(schemaSourceProvider);
     }
 
-    private final static class StringToInputStreamSchemaSourceProvider implements //
-            AdvancedSchemaSourceProvider<InputStream>, Delegator<AdvancedSchemaSourceProvider<String>> {
+    private static final class FunctionBasedSchemaSourceTransformation<I, O> implements
+            SchemaSourceTransformation<I, O> {
 
-        private AdvancedSchemaSourceProvider<String> delegate;
 
-        public StringToInputStreamSchemaSourceProvider(AdvancedSchemaSourceProvider<String> delegate) {
-            this.delegate = delegate;
-        }
+        private final Function<I, O> delegate;
 
-        @Override
-        public AdvancedSchemaSourceProvider<String> getDelegate() {
-            return delegate;
+        protected FunctionBasedSchemaSourceTransformation(final Function<I, O> delegate) {
+            super();
+            this.delegate = Preconditions.checkNotNull(delegate, "delegate MUST NOT be null.");
         }
 
         @Override
-        public Optional<InputStream> getSchemaSource(SourceIdentifier sourceIdentifier) {
-            Optional<String> potentialSource = getDelegate().getSchemaSource(sourceIdentifier);
-            if (potentialSource.isPresent()) {
-                String stringSource = potentialSource.get();
-                @SuppressWarnings("deprecation")
-                StringBufferInputStream stringInputStream = new StringBufferInputStream(stringSource);
-                return Optional.<InputStream> of(stringInputStream);
-            }
-            return Optional.absent();
+        public O transform(final I input) {
+            return delegate.apply(input);
         }
 
         @Override
-        public Optional<InputStream> getSchemaSource(String moduleName, Optional<String> revision) {
-            return getSchemaSource(SourceIdentifier.create(moduleName, revision));
+        public String toString() {
+            return "FunctionBasedSchemaSourceTransformation [delegate=" + delegate + "]";
         }
     }
 
@@ -86,7 +140,7 @@ public class SchemaSourceProviders {
 
         private final SchemaSourceProvider<O> delegate;
 
-        public SchemaSourceCompatibilityWrapper(SchemaSourceProvider<O> delegate) {
+        public SchemaSourceCompatibilityWrapper(final SchemaSourceProvider<O> delegate) {
             this.delegate = delegate;
         }
 
@@ -94,19 +148,56 @@ public class SchemaSourceProviders {
         public SchemaSourceProvider<O> getDelegate() {
             return delegate;
         }
-        
+
+
+        /*
+         * Deprecation warnings are suppresed, since this implementation
+         * needs to invoke deprecated method in order to provide
+         * implementation of non-deprecated APIs using legacy ones.
+         *
+         * (non-Javadoc)
+         * @see org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider#getSchemaSource(org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier)
+         */
+        @SuppressWarnings("deprecation")
         @Override
-        public Optional<O> getSchemaSource(SourceIdentifier sourceIdentifier) {
-            
+        public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
+
             final String moduleName = sourceIdentifier.getName();
             Optional<String> revision = Optional.fromNullable(sourceIdentifier.getRevision());
             return delegate.getSchemaSource(moduleName, revision);
         }
-        
+
+        /*
+         * Deprecation warnings are suppresed, since this implementation
+         * needs to invoke deprecated method in order to provide
+         * implementation of non-deprecated APIs using legacy ones.
+         *
+         * (non-Javadoc)
+         * @see org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider#getSchemaSource(org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier)
+         */
         @Override
-        public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
+        @SuppressWarnings("deprecation")
+        public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
             return delegate.getSchemaSource(moduleName, revision);
         }
     }
 
+    @SuppressWarnings("rawtypes")
+    private static class  IdentityTransformation implements SchemaSourceTransformation {
+
+        @Override
+        public Object transform(final Object input) {
+            return input;
+        }
+    }
+
+    private static class StringToInputStreamTransformation implements SchemaSourceTransformation<String, InputStream> {
+
+        @Override
+        public InputStream transform(final String input) {
+            return new ByteArrayInputStream(input.getBytes(Charsets.UTF_8));
+        }
+
+    }
+
 }
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SchemaSourceTransformation.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/SchemaSourceTransformation.java
new file mode 100644 (file)
index 0000000..6836618
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.model.util.repo;
+
+import com.google.common.annotations.Beta;
+
+/**
+ *
+ * Schema Source Transformation which transforms from one schema source
+ * representation to another.
+ *
+ * <p>
+ * <b>Representation of Schema Source</b>
+ * <p>
+ * Schema source may be represented by
+ * various Java Types, which depends on provider and/or consumer.
+ * <p>
+ * E.g example of possible representations:
+ * <ul>
+ * <li>{@link String}
+ * <li>{@link java.io.InputStream}
+ * <li>{@link com.google.common.io.ByteSource}
+ * </ul>
+ *
+ * FIXME: <b>Beta:</b> Consider allowing transformations, which may
+ * fail to produce Output, this will require introduction of
+ * checked exception.
+ *
+ * @param <I> Input schema source representation
+ * @param <O> Output schema source representation
+ */
+@Beta
+public interface SchemaSourceTransformation<I, O> {
+
+    /**
+     *
+     * Transforms supplied schema source in format <code>I</code> to schema
+     * source in format <code>O</code>.
+     *
+     * <ul>
+     * <li>Its execution does not cause any observable side effects.
+     * <li>If the contents of a,b are semantically same (e.g. contents of InputStream),
+     * output representations MUST BE also semantically equals.
+     * </ul>
+     *
+     * Implementations of transformation SHOULD NOT fail to
+     * transform valid non-null input to output representation.
+     *
+     *
+     * FIXME: <b>Beta:</b> Consider lowering condition for safe transformation
+     * and introduce checked exception for cases when transformation may fail.
+     *
+     * @param input Not null input which should be transformed
+     * @return Representation of input in <code>O</code> format.
+     * @throws NullPointerException if input is null.
+     *
+     */
+    @Beta
+    O transform(I input);
+}
index 5e06a57efa9b9a5d0a865c319345853c3dca2ce4..3c7812b0d81d5cbc58fe3087ba7d7a8cce9c7b4c 100644 (file)
@@ -7,19 +7,70 @@
  */
 package org.opendaylight.yangtools.yang.model.util.repo;
 
+import org.opendaylight.yangtools.concepts.Immutable;
+
 import com.google.common.base.Optional;
 
-public final class SourceIdentifier {
+/**
+ *
+ * YANG Schema source identifier
+ *
+ * Simple transfer object represents identifier of source for YANG schema (module or submodule),
+ * which consists of
+ * <ul>
+ * <li>YANG schema name ({@link #getName()}
+ * <li>Module revision (optional) ({link {@link #getRevision()})
+ * </ul>
+ *
+ * Source identifier is designated to be carry only necessary information
+ * to look-up YANG model source and to be used by {@link AdvancedSchemaSourceProvider}
+ * and similar.
+ *
+ * <b>Note:</b>On source retrieval layer it is impossible to distinguish
+ * between YANG module and/or submodule unless source is present.
+ *
+ * <p>
+ * (For further reference see: http://tools.ietf.org/html/rfc6020#section-5.2 and
+ * http://tools.ietf.org/html/rfc6022#section-3.1 ).
+ *
+ *
+ */
+public final class SourceIdentifier implements Immutable {
 
     private final String name;
     private final String revision;
 
+    /**
+     *
+     * Creates new YANG Schema source identifier.
+     *
+     * @param name Name of schema
+     * @param formattedRevision Revision of source in format YYYY-mm-dd
+     */
     public SourceIdentifier(final String name, final Optional<String> formattedRevision) {
         super();
         this.name = name;
         this.revision = formattedRevision.orNull();
     }
 
+    /**
+     * Returns model name
+     *
+     * @return model name
+     */
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Returns revision of source or null if revision was not supplied.
+     *
+     * @return revision of source or null if revision was not supplied.
+     */
+    public String getRevision() {
+        return revision;
+    }
+
     @Override
     public int hashCode() {
         final int prime = 31;
@@ -58,18 +109,23 @@ public final class SourceIdentifier {
         return true;
     }
 
-    public String getName() {
-        return name;
-    }
-
-    public String getRevision() {
-        return revision;
-    }
-
     public static SourceIdentifier create(final String moduleName, final Optional<String> revision) {
         return new SourceIdentifier(moduleName, revision);
     }
 
+    /**
+     * Returns filename for this YANG module as specified in RFC 6020.
+     *
+     * Returns filename in format
+     * <code>name ['@' revision] '.yang'</code>
+     * <p>
+     * Where revision is  date in format YYYY-mm-dd.
+     * <p>
+     * See
+     * http://tools.ietf.org/html/rfc6020#section-5.2
+     *
+     * @return Filename for this source identifier.
+     */
     public String toYangFilename() {
         return toYangFileName(name, Optional.fromNullable(revision));
     }
@@ -79,6 +135,20 @@ public final class SourceIdentifier {
         return "SourceIdentifier [name=" + name + "@" + revision + "]";
     }
 
+    /**
+     * Returns filename for this YANG module as specified in RFC 6020.
+     *
+     * Returns filename in format
+     * <code>moduleName ['@' revision] '.yang'</code>
+     *
+     * Where Where revision-date is in format YYYY-mm-dd.
+     *
+     * <p>
+     * See
+     * http://tools.ietf.org/html/rfc6020#section-5.2
+     *
+     * @return Filename for this source identifier.
+     */
     public static final String toYangFileName(final String moduleName, final Optional<String> revision) {
         StringBuilder filename = new StringBuilder(moduleName);
         if (revision.isPresent()) {
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/TransformingSourceProvider.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/TransformingSourceProvider.java
new file mode 100644 (file)
index 0000000..502bc9d
--- /dev/null
@@ -0,0 +1,69 @@
+package org.opendaylight.yangtools.yang.model.util.repo;
+
+import org.opendaylight.yangtools.concepts.Delegator;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ *
+ * Utility Source Provider implementation which uses delegate to retrieve
+ * sources and transformation function to convert sources to different
+ * representation.
+ *
+ *
+ * @param <I>
+ *            Representation of schema sources used by delegate
+ * @param <O>
+ *            Representation of schema sources exposed by this provider
+ */
+public final class TransformingSourceProvider<I, O> implements //
+        AdvancedSchemaSourceProvider<O>, Delegator<AdvancedSchemaSourceProvider<I>> {
+
+    private final AdvancedSchemaSourceProvider<I> delegate;
+    private final SchemaSourceTransformation<I, O> transformation;
+
+    /**
+     * Creates instance of transforming schema source provider which uses
+     * supplied delegate to retrieve sources and transformation to change
+     * sources to different representation.
+     *
+     * @param delegate
+     *            Delegate which provides sources.
+     * @param transformation
+     *            Transformation function which converts sources
+     * @return Instance of TransformingSourceProvider
+     * @throws NullPointerException
+     *             if any of arguments is null.
+     */
+    public static final <I, O> TransformingSourceProvider<I, O> create(final AdvancedSchemaSourceProvider<I> delegate,
+            final SchemaSourceTransformation<I, O> transformation) {
+        return new TransformingSourceProvider<>(delegate, transformation);
+    }
+
+    private TransformingSourceProvider(final AdvancedSchemaSourceProvider<I> delegate,
+            final SchemaSourceTransformation<I, O> transformation) {
+        this.delegate = Preconditions.checkNotNull(delegate, "delegate must not be null");
+        this.transformation = Preconditions.checkNotNull(transformation, "transformation must not be null");
+    }
+
+    @Override
+    public AdvancedSchemaSourceProvider<I> getDelegate() {
+        return delegate;
+    }
+
+    @Override
+    public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
+        Optional<I> potentialSource = getDelegate().getSchemaSource(sourceIdentifier);
+        if (potentialSource.isPresent()) {
+            I inputSource = potentialSource.get();
+            return Optional.<O> of(transformation.transform(inputSource));
+        }
+        return Optional.absent();
+    }
+
+    @Override
+    public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
+        return getSchemaSource(SourceIdentifier.create(moduleName, revision));
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/package-info.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/repo/package-info.java
new file mode 100644 (file)
index 0000000..6e31ba1
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * 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/eplv10.html
+ */
+/**
+ * This package introduces concepts, generic interfaces and implementations for
+ * creating and working with YANG Schema source repositories and working with them.
+ *
+ * <h2>Concepts</h2>
+ * <dl>
+ * <dt>Schema Source</dt>
+ * <dd>Source of YANG Schema, which is not processed, not resolved against other schemas
+ *    and from contents of <i>Schema Source</i> in combination with other Schema sources
+ *    it is possible to create resolved YANG Schema context.
+ * </dd>
+ * <dt>{@link org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier}</dt>
+ * <dd>Identifier of Schema Source. Identifier is not tied with source or representation.</dd>
+ * <dt>Schema Source Representation</dt>
+ * <dd>Representation of schema source. Representation of schema source could exists in various
+ * formats (Java types), depending on stage of processing, but representation MUST BE
+ * still result of processing only single unit of schema source (e.g. file, input stream). E.g.:
+ * <ul>
+ * <li>{@link java.lang.String} - textual representation of source code
+ * <li>{@link InputStream} - input stream containing source code
+ * <li>{@link com.google.common.io.ByteSource} - source for input streams containing source code
+ * <li>Parsed AST - abstract syntax tree, which is result of a parser, but still it is not linked
+ * against other schemas.
+ * </ul>
+ * </dd>
+ * <dt>{@link org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider}</dt>
+ * <dd>
+ *    Service which provides query API to obtain <i>Schema Source Representation</i> associated
+ *    with {@link org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier}.
+ * </dd>
+ * <dt>{@link org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceTransformation}</dt>
+ * <dd>
+ * Function (service) which provides transformation from one <i>Schema Source Representation</i>
+ * type to another.
+ * </dd>
+ * </dl>
+ *
+ *
+ */
+package org.opendaylight.yangtools.yang.model.util.repo;
\ No newline at end of file
index e024bee53b6d894f927dab9f136982802b932001..c35a81ac9c1a2bb9f10599d8fcd01c636b6d5069 100644 (file)
@@ -7,12 +7,14 @@
  */
 package org.opendaylight.yangtools.yang.model.parser.api;
 
-import com.google.common.io.ByteSource;
 import java.io.File;
 import java.io.IOException;
 import java.util.Collection;
+
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
+import com.google.common.io.ByteSource;
+
 /**
  * Parse yang models and convert data to SchemaContext.
  *
@@ -30,7 +32,7 @@ public interface YangContextParser extends YangModelParser {
      *         only module parsed from yangFile and modules which yangFile needs
      *         as dependencies.
      */
-    SchemaContext parseFile(final File yangFile, final File dependenciesDirectory) throws IOException;
+    SchemaContext parseFile(final File yangFile, final File dependenciesDirectory) throws IOException, YangSyntaxErrorException;
 
     /**
      * Parse one or more Yang model files and return the definitions of Yang
@@ -57,7 +59,7 @@ public interface YangContextParser extends YangModelParser {
      *            SchemaContext containing already parsed yang models
      * @return parsed data as SchemaContext
      */
-    SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException;
+    SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException, YangSyntaxErrorException;
 
     /**
      * Parse one or more Yang model streams and return the definitions of Yang
@@ -69,7 +71,7 @@ public interface YangContextParser extends YangModelParser {
      *            yang streams to parse
      * @return parsed data as SchemaContext
      */
-    SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException;
+    SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException;
 
     /**
      * Parse one or more Yang model streams and return the definitions of Yang
@@ -84,6 +86,6 @@ public interface YangContextParser extends YangModelParser {
      *            SchemaContext containing already parsed yang models
      * @return parsed data as SchemaContext
      */
-    SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException;
+    SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException, YangSyntaxErrorException;
 
 }
index 90dd6d6c5ae00441762fe7c279e191ba540bee0e..e477a827bdfed39b0f18137d369fd80e39b9c44c 100644 (file)
@@ -7,10 +7,6 @@
  */
 package org.opendaylight.yangtools.yang.model.parser.api;
 
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
-
 import java.io.File;
 import java.io.InputStream;
 import java.util.Collection;
@@ -18,12 +14,16 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
+
 /**
  * Yang Model Parser interface is designed for parsing yang models and convert
  * the information to Data Schema Tree.
  *
  */
-// refactor methods returning input streams, after introducing
+// FIXME: refactor methods returning input streams, after introducing (?)
 public interface YangModelParser {
 
     /**
@@ -113,7 +113,7 @@ public interface YangModelParser {
 
     /**
      * Equivalent to {@link #parseYangModels(List)} that returns parsed modules
-     * mapped to IputStreams from which they were parsed.
+     * mapped to InputStreams from which they were parsed.
      *
      * @param yangModelStreams
      *            yang streams to parse
diff --git a/yang/yang-parser-api/src/main/java/org/opendaylight/yangtools/yang/model/parser/api/YangSyntaxErrorException.java b/yang/yang-parser-api/src/main/java/org/opendaylight/yangtools/yang/model/parser/api/YangSyntaxErrorException.java
new file mode 100644 (file)
index 0000000..ce42cc3
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * 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/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.model.parser.api;
+
+import com.google.common.base.Preconditions;
+
+public class YangSyntaxErrorException extends Exception {
+    private static final long serialVersionUID = 1L;
+    private final String module;
+    private final int line;
+    private final int charPositionInLine;
+
+    public YangSyntaxErrorException(final String module, final int line, final int charPositionInLine,
+            final String message) {
+        this(module, line, charPositionInLine, message, null);
+    }
+
+    public YangSyntaxErrorException(final String module, final int line, final int charPositionInLine,
+            final String message, final Throwable cause) {
+        super(Preconditions.checkNotNull(message), cause);
+        this.module = module;
+        this.line = line;
+        this.charPositionInLine = charPositionInLine;
+    }
+
+    public String getModule() {
+        return module;
+    }
+
+    public int getLine() {
+        return line;
+    }
+
+    public int getCharPositionInLine() {
+        return charPositionInLine;
+    }
+
+    public String getFormattedMessage() {
+        final StringBuilder sb = new StringBuilder(getMessage());
+        if (module != null) {
+            sb.append(" in module ");
+            sb.append(module);
+        }
+        if (line != 0) {
+            sb.append(" on line ");
+            sb.append(line);
+            if (charPositionInLine != 0) {
+                sb.append(" character ");
+                sb.append(charPositionInLine);
+            }
+        }
+        return sb.toString();
+    }
+
+    @Override
+    public String toString() {
+        return this.getClass().getName() + ": " + getFormattedMessage();
+    }
+}
index 224c45fcda060f1ba1904b66f2914599d2af2b79..d908f93b0272d92d9c38bf6da3ef5f31f688ace5 100644 (file)
@@ -109,7 +109,7 @@ public final class AugmentationSchemaBuilderImpl extends AbstractDataNodeContain
             for (QName name : parsedPath) {
                 newPath.add(new QName(mb.getNamespace(), mb.getRevision(), name.getPrefix(), name.getLocalName()));
             }
-            instance.targetPath = new SchemaPath(newPath, false);
+            instance.targetPath = SchemaPath.create(newPath, false);
         } else {
             instance.targetPath = targetNodeSchemaPath;
         }
@@ -203,7 +203,7 @@ public final class AugmentationSchemaBuilderImpl extends AbstractDataNodeContain
     }
 
     @Override
-    public void setStatus(Status status) {
+    public void setStatus(final Status status) {
         this.status = Preconditions.checkNotNull(status, "status cannot be null");
     }
 
index c0ab82847fc0cdb231e3bc96aaf316126b3720e9..1b6f19a0697da38d6e2011fa6336b88e85e5ae2a 100644 (file)
@@ -17,6 +17,7 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Set;
 import java.util.TreeSet;
+
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -67,11 +68,12 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     private String belongsTo;
     private ModuleBuilder parent;
 
-    public ModuleBuilder getParent() {
+    @Override
+       public ModuleBuilder getParent() {
         return parent;
     }
 
-    public void setParent(ModuleBuilder parent) {
+    public void setParent(final ModuleBuilder parent) {
         this.parent = parent;
     }
 
@@ -120,17 +122,17 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         super(name, 0, null);
         this.name = name;
         this.sourcePath = sourcePath;
-        schemaPath = new SchemaPath(Collections.<QName> emptyList(), true);
+        schemaPath = SchemaPath.create(Collections.<QName> emptyList(), true);
         this.submodule = submodule;
         instance = new ModuleImpl(name, sourcePath);
         actualPath.push(this);
     }
 
-    public ModuleBuilder(Module base) {
+    public ModuleBuilder(final Module base) {
         super(base.getName(), 0, null);
         this.name = base.getName();
         this.sourcePath = base.getModuleSourcePath();
-        schemaPath = new SchemaPath(Collections.<QName> emptyList(), true);
+        schemaPath = SchemaPath.create(Collections.<QName> emptyList(), true);
         submodule = false;
         instance = new ModuleImpl(base.getName(), base.getModuleSourcePath());
         instance.setYangVersion(base.getYangVersion());
@@ -254,7 +256,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     @Override
-    public void setParent(Builder parent) {
+    public void setParent(final Builder parent) {
         throw new YangParseException(name, 0, "Can not set parent to module");
     }
 
@@ -376,7 +378,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         return belongsTo;
     }
 
-    public void setBelongsTo(String belongsTo) {
+    public void setBelongsTo(final String belongsTo) {
         this.belongsTo = belongsTo;
     }
 
@@ -555,7 +557,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     @Override
-    public void addUsesNode(UsesNodeBuilder usesBuilder) {
+    public void addUsesNode(final UsesNodeBuilder usesBuilder) {
         addedUsesNodes.add(usesBuilder);
         allUsesNodes.add(usesBuilder);
     }
@@ -648,7 +650,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         return outputBuilder;
     }
 
-    public void addNotification(NotificationDefinition notification) {
+    public void addNotification(final NotificationDefinition notification) {
         notifications.add(notification);
     }
 
@@ -742,7 +744,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     @Override
-    public void addTypedef(TypeDefinitionBuilder typedefBuilder) {
+    public void addTypedef(final TypeDefinitionBuilder typedefBuilder) {
         String nodeName = typedefBuilder.getQName().getLocalName();
         for (TypeDefinitionBuilder tdb : addedTypedefs) {
             if (tdb.getQName().getLocalName().equals(nodeName)) {
@@ -913,7 +915,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         return "module " + name;
     }
 
-    public void setSource(String source) {
+    public void setSource(final String source) {
         this.source = source;
     }
 
@@ -943,7 +945,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         private final List<UnknownSchemaNode> unknownNodes = new ArrayList<>();
         private String source;
 
-        private ModuleImpl(String name, String sourcePath) {
+        private ModuleImpl(final String name, final String sourcePath) {
             this.name = name;
             this.sourcePath = sourcePath;
         }
@@ -958,7 +960,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return namespace;
         }
 
-        private void setNamespace(URI namespace) {
+        private void setNamespace(final URI namespace) {
             this.namespace = namespace;
         }
 
@@ -972,7 +974,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return revision;
         }
 
-        private void setRevision(Date revision) {
+        private void setRevision(final Date revision) {
             this.revision = revision;
         }
 
@@ -981,7 +983,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return prefix;
         }
 
-        private void setPrefix(String prefix) {
+        private void setPrefix(final String prefix) {
             this.prefix = prefix;
         }
 
@@ -990,7 +992,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return yangVersion;
         }
 
-        private void setYangVersion(String yangVersion) {
+        private void setYangVersion(final String yangVersion) {
             this.yangVersion = yangVersion;
         }
 
@@ -999,7 +1001,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return description;
         }
 
-        private void setDescription(String description) {
+        private void setDescription(final String description) {
             this.description = description;
         }
 
@@ -1008,7 +1010,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return reference;
         }
 
-        private void setReference(String reference) {
+        private void setReference(final String reference) {
             this.reference = reference;
         }
 
@@ -1017,7 +1019,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return organization;
         }
 
-        private void setOrganization(String organization) {
+        private void setOrganization(final String organization) {
             this.organization = organization;
         }
 
@@ -1026,7 +1028,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return contact;
         }
 
-        private void setContact(String contact) {
+        private void setContact(final String contact) {
             this.contact = contact;
         }
 
@@ -1035,7 +1037,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return imports;
         }
 
-        private void setImports(Set<ModuleImport> imports) {
+        private void setImports(final Set<ModuleImport> imports) {
             if (imports != null) {
                 this.imports.addAll(imports);
             }
@@ -1046,7 +1048,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return features;
         }
 
-        private void setFeatures(Set<FeatureDefinition> features) {
+        private void setFeatures(final Set<FeatureDefinition> features) {
             if (features != null) {
                 this.features.addAll(features);
             }
@@ -1057,7 +1059,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return typeDefinitions;
         }
 
-        private void setTypeDefinitions(Set<TypeDefinition<?>> typeDefinitions) {
+        private void setTypeDefinitions(final Set<TypeDefinition<?>> typeDefinitions) {
             if (typeDefinitions != null) {
                 this.typeDefinitions.addAll(typeDefinitions);
             }
@@ -1068,7 +1070,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return notifications;
         }
 
-        private void setNotifications(Set<NotificationDefinition> notifications) {
+        private void setNotifications(final Set<NotificationDefinition> notifications) {
             if (notifications != null) {
                 this.notifications.addAll(notifications);
             }
@@ -1079,7 +1081,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return augmentations;
         }
 
-        private void setAugmentations(Set<AugmentationSchema> augmentations) {
+        private void setAugmentations(final Set<AugmentationSchema> augmentations) {
             if (augmentations != null) {
                 this.augmentations.addAll(augmentations);
             }
@@ -1090,7 +1092,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return rpcs;
         }
 
-        private void setRpcs(Set<RpcDefinition> rpcs) {
+        private void setRpcs(final Set<RpcDefinition> rpcs) {
             if (rpcs != null) {
                 this.rpcs.addAll(rpcs);
             }
@@ -1101,7 +1103,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return deviations;
         }
 
-        private void setDeviations(Set<Deviation> deviations) {
+        private void setDeviations(final Set<Deviation> deviations) {
             if (deviations != null) {
                 this.deviations.addAll(deviations);
             }
@@ -1112,7 +1114,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return Collections.unmodifiableSet(childNodes);
         }
 
-        private void addChildNodes(Set<DataSchemaNode> childNodes) {
+        private void addChildNodes(final Set<DataSchemaNode> childNodes) {
             if (childNodes != null) {
                 this.childNodes.addAll(childNodes);
             }
@@ -1123,7 +1125,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return groupings;
         }
 
-        private void setGroupings(Set<GroupingDefinition> groupings) {
+        private void setGroupings(final Set<GroupingDefinition> groupings) {
             if (groupings != null) {
                 this.groupings.addAll(groupings);
             }
@@ -1134,7 +1136,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
             return uses;
         }
 
-        private void setUses(Set<UsesNode> uses) {
+        private void setUses(final Set<UsesNode> uses) {
             if (uses != null) {
                 this.uses.addAll(uses);
             }
@@ -1175,16 +1177,16 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         }
 
         @Override
-        public DataSchemaNode getDataChildByName(QName name) {
+        public DataSchemaNode getDataChildByName(final QName name) {
             return getChildNode(childNodes, name);
         }
 
         @Override
-        public DataSchemaNode getDataChildByName(String name) {
+        public DataSchemaNode getDataChildByName(final String name) {
             return getChildNode(childNodes, name);
         }
 
-        void setSource(String source){
+        void setSource(final String source){
             this.source = source;
         }
 
@@ -1204,7 +1206,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
         }
 
         @Override
-        public boolean equals(Object obj) {
+        public boolean equals(final Object obj) {
             if (this == obj) {
                 return true;
             }
@@ -1393,7 +1395,7 @@ public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
index 1edf0b8543551bedc4479bc359611fa762a0439b..6b08839499fd2d5e39ab566e5c3cac957c5ac96a 100644 (file)
@@ -7,11 +7,17 @@
  */
 package org.opendaylight.yangtools.yang.parser.builder.impl;
 
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
 
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
-import org.opendaylight.yangtools.yang.model.api.type.*;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
 import org.opendaylight.yangtools.yang.model.util.UnionType;
 import org.opendaylight.yangtools.yang.parser.builder.api.AbstractTypeAwareBuilder;
@@ -44,7 +50,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setQName(QName qname) {
+    public void setQName(final QName qname) {
         throw new UnsupportedOperationException("Can not set qname to union type");
     }
 
@@ -75,10 +81,10 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     @Override
     public UnionType build() {
         if (!isBuilt) {
-            instance = new UnionType(types);
             for (TypeDefinitionBuilder tdb : typedefs) {
                 types.add(tdb.build());
             }
+            instance = new UnionType(types);
             isBuilt = true;
         }
         return instance;
@@ -120,7 +126,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setPath(SchemaPath path) {
+    public void setPath(final SchemaPath path) {
         throw new YangParseException(moduleName, line, "Can not set path to " + NAME);
     }
 
@@ -145,7 +151,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setRanges(List<RangeConstraint> ranges) {
+    public void setRanges(final List<RangeConstraint> ranges) {
         throw new YangParseException(moduleName, line, "Can not set ranges to " + NAME);
     }
 
@@ -155,7 +161,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setLengths(List<LengthConstraint> lengths) {
+    public void setLengths(final List<LengthConstraint> lengths) {
         throw new YangParseException(moduleName, line, "Can not set lengths to " + NAME);
     }
 
@@ -165,7 +171,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setPatterns(List<PatternConstraint> patterns) {
+    public void setPatterns(final List<PatternConstraint> patterns) {
         throw new YangParseException(moduleName, line, "Can not set patterns to " + NAME);
     }
 
@@ -175,7 +181,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setFractionDigits(Integer fractionDigits) {
+    public void setFractionDigits(final Integer fractionDigits) {
         throw new YangParseException(moduleName, line, "Can not set fraction digits to " + NAME);
     }
 
@@ -190,7 +196,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setDefaultValue(Object defaultValue) {
+    public void setDefaultValue(final Object defaultValue) {
         throw new YangParseException(moduleName, line, "Can not set default value to " + NAME);
     }
 
@@ -200,7 +206,7 @@ public final class UnionTypeBuilder extends AbstractTypeAwareBuilder implements
     }
 
     @Override
-    public void setUnits(String units) {
+    public void setUnits(final String units) {
         throw new YangParseException(moduleName, line, "Can not set units to " + NAME);
     }
 
index 6f81e7adaf66bfa951ccda2a25f2ab4eec886ea8..201ab916185d417cf212a005434fbb1cea191297 100644 (file)
@@ -7,7 +7,18 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
-import com.google.common.base.Optional;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
@@ -26,24 +37,45 @@ import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.UsesNode;
 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
 
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
+import com.google.common.base.Optional;
+import com.google.common.base.Supplier;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSetMultimap;
+import com.google.common.collect.Multimaps;
+import com.google.common.collect.SetMultimap;
 
 final class SchemaContextImpl implements SchemaContext {
-    private final Set<Module> modules;
+    private static final Supplier<HashSet<Module>> URI_SET_SUPPLIER = new Supplier<HashSet<Module>>() {
+        @Override
+        public HashSet<Module> get() {
+            return new HashSet<>();
+        }
+    };
+
     private final Map<ModuleIdentifier, String> identifiersToSources;
+    private final SetMultimap<URI, Module> namespaceToModules;
+    private final Set<Module> modules;
 
-    SchemaContextImpl(final Set<Module> modules, Map<ModuleIdentifier, String> identifiersToSources) {
-        this.modules = modules;
+    SchemaContextImpl(final Set<Module> modules, final Map<ModuleIdentifier, String> identifiersToSources) {
         this.identifiersToSources = identifiersToSources;
+
+        /*
+         * Instead of doing this on each invocation of getModules(), pre-compute
+         * it once and keep it around -- better than the set we got in.
+         */
+        this.modules = ImmutableSet.copyOf(ModuleDependencySort.sort(modules.toArray(new Module[modules.size()])));
+
+        /*
+         * The most common lookup is from Namespace->Module. Invest some quality time in
+         * building that up.
+         */
+        final SetMultimap<URI, Module> multimap = Multimaps.newSetMultimap(
+                new TreeMap<URI, Collection<Module>>(), URI_SET_SUPPLIER);
+        for (Module m : modules) {
+            multimap.put(m.getNamespace(), m);
+        }
+
+        namespaceToModules = ImmutableSetMultimap.copyOf(multimap);
     }
 
     @Override
@@ -57,8 +89,7 @@ final class SchemaContextImpl implements SchemaContext {
 
     @Override
     public Set<Module> getModules() {
-        List<Module> sorted = ModuleDependencySort.sort(modules.toArray(new Module[modules.size()]));
-        return new LinkedHashSet<Module>(sorted);
+        return modules;
     }
 
     @Override
@@ -106,36 +137,34 @@ final class SchemaContextImpl implements SchemaContext {
 
     @Override
     public Set<Module> findModuleByNamespace(final URI namespace) {
-        final Set<Module> ret = new HashSet<Module>();
-        if (namespace != null) {
-            for (final Module module : modules) {
-                if (module.getNamespace().equals(namespace)) {
-                    ret.add(module);
-                }
-            }
-        }
-        return ret;
+        final Set<Module> ret = namespaceToModules.get(namespace);
+        return ret == null ? Collections.<Module>emptySet() : ret;
     }
 
     @Override
-    public Module findModuleByNamespaceAndRevision(URI namespace, Date revision) {
-        if (namespace != null) {
-            Set<Module> modules = findModuleByNamespace(namespace);
-
-            if (revision == null) {
-                TreeMap<Date, Module> map = new TreeMap<Date, Module>();
-                for (Module module : modules) {
-                    map.put(module.getRevision(), module);
-                }
-                if (map.isEmpty()) {
-                    return null;
-                }
-                return map.lastEntry().getValue();
-            } else {
-                for (Module module : modules) {
-                    if (module.getRevision().equals(revision)) {
-                        return(module);
-                    }
+    public Module findModuleByNamespaceAndRevision(final URI namespace, final Date revision) {
+        if (namespace == null) {
+            return null;
+        }
+        final Set<Module> modules = findModuleByNamespace(namespace);
+        if (modules.isEmpty()) {
+            return null;
+        }
+
+        if (revision == null) {
+            // FIXME: The ordering of modules in Multimap could just guarantee this...
+            TreeMap<Date, Module> map = new TreeMap<Date, Module>();
+            for (Module module : modules) {
+                map.put(module.getRevision(), module);
+            }
+            if (map.isEmpty()) {
+                return null;
+            }
+            return map.lastEntry().getValue();
+        } else {
+            for (Module module : modules) {
+                if (module.getRevision().equals(revision)) {
+                    return(module);
                 }
             }
         }
@@ -224,7 +253,7 @@ final class SchemaContextImpl implements SchemaContext {
     }
 
     @Override
-    public DataSchemaNode getDataChildByName(QName name) {
+    public DataSchemaNode getDataChildByName(final QName name) {
         DataSchemaNode result = null;
         for (Module module : modules) {
             result = module.getDataChildByName(name);
@@ -236,7 +265,7 @@ final class SchemaContextImpl implements SchemaContext {
     }
 
     @Override
-    public DataSchemaNode getDataChildByName(String name) {
+    public DataSchemaNode getDataChildByName(final String name) {
         DataSchemaNode result = null;
         for (Module module : modules) {
             result = module.getDataChildByName(name);
@@ -269,7 +298,7 @@ final class SchemaContextImpl implements SchemaContext {
     }
 
     @Override
-    public Optional<String> getModuleSource(ModuleIdentifier moduleIdentifier) {
+    public Optional<String> getModuleSource(final ModuleIdentifier moduleIdentifier) {
         String maybeSource = identifiersToSources.get(moduleIdentifier);
         return Optional.fromNullable(maybeSource);
     }
index cbee5694ff650282ea3a141f430a3e130609c110..6f91f854a3d9244d2f7dbe87507f79473435f6a1 100644 (file)
@@ -7,54 +7,75 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import org.antlr.v4.runtime.BaseErrorListener;
 import org.antlr.v4.runtime.Parser;
 import org.antlr.v4.runtime.RecognitionException;
 import org.antlr.v4.runtime.Recognizer;
-import org.opendaylight.yangtools.yang.parser.util.YangParseException;
-
-import java.util.ArrayList;
-import java.util.List;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 final class YangErrorListener extends BaseErrorListener {
-    private final List<Exception> exceptions = new ArrayList<>();
+    private static final Logger LOG = LoggerFactory.getLogger(YangErrorListener.class);
+    private final List<YangSyntaxErrorException> exceptions = new ArrayList<>();
 
     @Override
-    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
-            String msg, RecognitionException e) {
-        String module = getModuleName(recognizer);
-        exceptions.add(new YangParseException(module, line, msg));
+    public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
+            final int charPositionInLine, final String msg, final RecognitionException e) {
+        LOG.debug("Syntax error at {}:{}: {}", line, charPositionInLine, msg, e);
+
+        final String module = getModuleName(recognizer);
+        exceptions.add(new YangSyntaxErrorException(module, line, charPositionInLine, msg, e));
     }
 
-    private String getModuleName(Recognizer<?, ?> recognizer) {
-        String result;
-        if (recognizer instanceof Parser) {
-            try {
-                Parser parser = (Parser) recognizer;
-                String model = parser.getInputStream().getTokenSource().getInputStream().toString();
-                model = model.substring(0, model.indexOf("\n"));
-                model = model.substring(model.indexOf("module") + 6);
-                model = model.substring(0, model.indexOf("{"));
-                model = model.trim();
-                result = model;
-            } catch (Exception e) {
-                result = "";
-            }
-        } else {
-            result = "";
+    private static String getModuleName(final Recognizer<?, ?> recognizer) {
+        if (!(recognizer instanceof Parser)) {
+            return null;
+        }
+
+        final Parser parser = (Parser) recognizer;
+        try {
+            String model = parser.getInputStream().getTokenSource().getInputStream().toString();
+            model = model.substring(0, model.indexOf("\n"));
+            model = model.substring(model.indexOf("module") + 6);
+            model = model.substring(0, model.indexOf("{"));
+            model = model.trim();
+            return model;
+        } catch (Exception e) {
+            LOG.debug("Failed to extract module name from parser {}", parser, e);
+            return null;
         }
-        return result;
     }
 
-    public void validate() {
-        if (!exceptions.isEmpty()) {
-            StringBuilder sb = new StringBuilder();
-            for (Exception e : exceptions) {
-                sb.append("\n");
-                sb.append(e.getMessage());
+    public void validate() throws YangSyntaxErrorException {
+        if (exceptions.isEmpty()) {
+            return;
+        }
+
+        // Single exception: just throw it
+        if (exceptions.size() == 1) {
+            throw exceptions.get(0);
+        }
+
+        final StringBuilder sb = new StringBuilder();
+        String module = null;
+        boolean first = true;
+        for (YangSyntaxErrorException e : exceptions) {
+            if (module == null) {
+                module = e.getModule();
             }
-            throw new YangParseException(sb.toString());
+            if (first) {
+                first = false;
+            } else {
+                sb.append('\n');
+            }
+
+            sb.append(e.getFormattedMessage());
         }
-    }
 
+        throw new YangSyntaxErrorException(module, 0, 0, sb.toString());
+    }
 }
index e705f9c1d5b6f48b8700f30905eb022309238158..1a463447a9c9eac5ee0a57293ac760f50623240d 100644 (file)
@@ -26,9 +26,6 @@ import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeU
 import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeUnionWithContext;
 import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeWithContext;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashBiMap;
-import com.google.common.io.ByteSource;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
@@ -45,6 +42,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeMap;
+
 import org.antlr.v4.runtime.ANTLRInputStream;
 import org.antlr.v4.runtime.CommonTokenStream;
 import org.antlr.v4.runtime.tree.ParseTree;
@@ -64,6 +62,7 @@ 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.parser.api.YangContextParser;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationTargetBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
@@ -97,6 +96,10 @@ import org.opendaylight.yangtools.yang.validator.YangModelBasicValidator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.HashBiMap;
+import com.google.common.io.ByteSource;
+
 
 public final class YangParserImpl implements YangContextParser {
     private static final Logger LOG = LoggerFactory.getLogger(YangParserImpl.class);
@@ -104,16 +107,17 @@ public final class YangParserImpl implements YangContextParser {
     private static final String FAIL_DEVIATION_TARGET = "Failed to find deviation target.";
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModels(final File yangFile, final File directory) {
         try {
             return parseFile(yangFile, directory).getModules();
-        } catch (IOException e) {
+        } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
         }
     }
 
     @Override
-    public SchemaContext parseFile(final File yangFile, final File directory) throws IOException {
+    public SchemaContext parseFile(final File yangFile, final File directory) throws IOException, YangSyntaxErrorException {
         Preconditions.checkState(yangFile.exists(), yangFile + " does not exists");
         Preconditions.checkState(directory.exists(), directory + " does not exists");
         Preconditions.checkState(directory.isDirectory(), directory + " is not a directory");
@@ -153,6 +157,7 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModels(final List<File> yangFiles) {
         return parseFiles(yangFiles).getModules();
     }
@@ -166,16 +171,17 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModels(final List<File> yangFiles, final SchemaContext context) {
         try {
             return parseFiles(yangFiles, context).getModules();
-        } catch (IOException e) {
+        } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
         }
     }
 
     @Override
-    public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException {
+    public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException, YangSyntaxErrorException {
         if (yangFiles == null) {
             return resolveSchemaContext(Collections.<Module> emptySet());
         }
@@ -186,17 +192,18 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
-        Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
         try {
+            Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
             return parseSources(sources).getModules();
-        } catch (IOException e) {
+        } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
         }
     }
 
     @Override
-    public SchemaContext parseSources(Collection<ByteSource> sources) throws IOException {
+    public SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
         Collection<Module> unsorted = parseYangModelSources(sources).values();
         Set<Module> sorted = new LinkedHashSet<>(
                 ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
@@ -204,17 +211,18 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
-    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, SchemaContext context) {
-        Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
+    @Deprecated
+    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, final SchemaContext context) {
         try {
+            Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
             return parseSources(sources, context).getModules();
-        } catch (IOException e) {
+        } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
         }
     }
 
     @Override
-    public SchemaContext parseSources(Collection<ByteSource> sources, SchemaContext context) throws IOException {
+    public SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException, YangSyntaxErrorException {
         if (sources == null) {
             return resolveSchemaContext(Collections.<Module> emptySet());
         }
@@ -234,7 +242,7 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
-    public Map<File, Module> parseYangModelsMapped(Collection<File> yangFiles) {
+    public Map<File, Module> parseYangModelsMapped(final Collection<File> yangFiles) {
         if (yangFiles == null || yangFiles.isEmpty()) {
             return Collections.emptyMap();
         }
@@ -253,7 +261,7 @@ public final class YangParserImpl implements YangContextParser {
         Map<ByteSource, Module> byteSourceToModule;
         try {
             byteSourceToModule = parseYangModelSources(byteSourceToFile.keySet());
-        } catch (IOException e) {
+        } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
         }
         Map<File, Module> result = new LinkedHashMap<>();
@@ -283,7 +291,7 @@ public final class YangParserImpl implements YangContextParser {
         Map<ByteSource, Module> sourceToModule;
         try {
             sourceToModule = parseYangModelSources(sourceToStream.keySet());
-        } catch (IOException e) {
+        } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
         }
         Map<InputStream, Module> result = new LinkedHashMap<>();
@@ -304,7 +312,7 @@ public final class YangParserImpl implements YangContextParser {
         return new SchemaContextImpl(modules, identifiersToSources);
     }
 
-    private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException {
+    private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
         if (sources == null || sources.isEmpty()) {
             return Collections.emptyMap();
         }
@@ -334,14 +342,15 @@ public final class YangParserImpl implements YangContextParser {
      *            collection of streams to parse
      * @return map, where key is source stream and value is module builder
      *         parsed from stream
+     * @throws YangSyntaxErrorException
      */
-    private Map<ByteSource, ModuleBuilder> resolveSources(Collection<ByteSource> streams) throws IOException {
+    private Map<ByteSource, ModuleBuilder> resolveSources(final Collection<ByteSource> streams) throws IOException, YangSyntaxErrorException {
         Map<ByteSource, ModuleBuilder> builders = parseSourcesToBuilders(streams);
         Map<ByteSource, ModuleBuilder> result = resolveSubmodules(builders);
         return result;
     }
 
-    private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(Collection<ByteSource> sources) throws IOException {
+    private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
         final ParseTreeWalker walker = new ParseTreeWalker();
         final Map<ByteSource, ParseTree> sourceToTree = parseYangSources(sources);
         final Map<ByteSource, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
@@ -369,10 +378,11 @@ public final class YangParserImpl implements YangContextParser {
             sourceToBuilder.put(source, moduleBuilder);
         }
 
+        ParserUtils.setSourceToBuilder(sourceToBuilder);
         return sourceToBuilder;
     }
 
-    private Map<ByteSource, ModuleBuilder> resolveSubmodules(Map<ByteSource, ModuleBuilder> builders) {
+    private Map<ByteSource, ModuleBuilder> resolveSubmodules(final Map<ByteSource, ModuleBuilder> builders) {
         Map<ByteSource, ModuleBuilder> modules = new HashMap<>();
         Set<ModuleBuilder> submodules = new HashSet<>();
         for (Map.Entry<ByteSource, ModuleBuilder> entry : builders.entrySet()) {
@@ -403,7 +413,7 @@ public final class YangParserImpl implements YangContextParser {
      *            collection of builders containing modules and submodules
      * @return collection of module builders
      */
-    private Collection<ModuleBuilder> resolveSubmodules(Collection<ModuleBuilder> builders) {
+    private Collection<ModuleBuilder> resolveSubmodules(final Collection<ModuleBuilder> builders) {
         Collection<ModuleBuilder> modules = new HashSet<>();
         Set<ModuleBuilder> submodules = new HashSet<>();
         for (ModuleBuilder moduleBuilder : builders) {
@@ -424,7 +434,7 @@ public final class YangParserImpl implements YangContextParser {
         return modules;
     }
 
-    private void addSubmoduleToModule(ModuleBuilder submodule, ModuleBuilder module) {
+    private void addSubmoduleToModule(final ModuleBuilder submodule, final ModuleBuilder module) {
         submodule.setParent(module);
         module.getDirtyNodes().addAll(submodule.getDirtyNodes());
         module.getModuleImports().addAll(submodule.getModuleImports());
@@ -458,7 +468,7 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
-            final Collection<ByteSource> yangFileStreams, final SchemaContext context) throws IOException {
+            final Collection<ByteSource> yangFileStreams, final SchemaContext context) throws IOException, YangSyntaxErrorException {
         Map<ByteSource, ModuleBuilder> parsedBuilders = resolveSources(yangFileStreams);
         ModuleBuilder[] builders = new ModuleBuilder[parsedBuilders.size()];
         parsedBuilders.values().toArray(builders);
@@ -480,7 +490,7 @@ public final class YangParserImpl implements YangContextParser {
      *            modules to order
      * @return modules ordered by name and revision
      */
-    private LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> orderModules(List<ModuleBuilder> modules) {
+    private LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> orderModules(final List<ModuleBuilder> modules) {
         final LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> result = new LinkedHashMap<>();
         for (final ModuleBuilder builder : modules) {
             if (builder == null) {
@@ -512,7 +522,7 @@ public final class YangParserImpl implements YangContextParser {
      * @param filtered
      *            collection to fill up
      */
-    private void filterImports(ModuleBuilder main, Collection<ModuleBuilder> other, Collection<ModuleBuilder> filtered) {
+    private void filterImports(final ModuleBuilder main, final Collection<ModuleBuilder> other, final Collection<ModuleBuilder> filtered) {
         Set<ModuleImport> imports = main.getModuleImports();
 
         // if this is submodule, add parent to filtered and pick its imports
@@ -549,7 +559,7 @@ public final class YangParserImpl implements YangContextParser {
         }
     }
 
-    private Map<ByteSource, ParseTree> parseYangSources(final Collection<ByteSource> sources) throws IOException {
+    private Map<ByteSource, ParseTree> parseYangSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
         final Map<ByteSource, ParseTree> trees = new HashMap<>();
         for (ByteSource source : sources) {
             trees.put(source, parseYangSource(source));
@@ -557,30 +567,22 @@ public final class YangParserImpl implements YangContextParser {
         return trees;
     }
 
-    private ParseTree parseYangSource(final ByteSource source) throws IOException {
-        ParseTree result = null;
-        InputStream stream = null;
-        try {
-            stream = source.openStream();
+    private YangContext parseYangSource(final ByteSource source) throws IOException, YangSyntaxErrorException {
+       try (InputStream stream = source.openStream()) {
             final ANTLRInputStream input = new ANTLRInputStream(stream);
             final YangLexer lexer = new YangLexer(input);
             final CommonTokenStream tokens = new CommonTokenStream(lexer);
             final YangParser parser = new YangParser(tokens);
             parser.removeErrorListeners();
-            YangErrorListener errorListener = new YangErrorListener();
+
+            final YangErrorListener errorListener = new YangErrorListener();
             parser.addErrorListener(errorListener);
-            result = parser.yang();
+
+            final YangContext result = parser.yang();
             errorListener.validate();
-        } finally {
-            if (stream != null) {
-                try {
-                    stream.close();
-                } catch (IOException e) {
-                    LOG.warn("Failed to close stream {}", stream);
-                }
-            }
-        }
-        return result;
+
+            return result;
+       }
     }
 
     public static YangContext parseStreamWithoutErrorListeners(final InputStream yangStream) {
@@ -756,7 +758,7 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     private void resolveDirtyNodesWithContext(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module, SchemaContext context) {
+            final ModuleBuilder module, final SchemaContext context) {
         final Set<TypeAwareBuilder> dirtyNodes = module.getDirtyNodes();
         if (!dirtyNodes.isEmpty()) {
             for (TypeAwareBuilder nodeToResolve : dirtyNodes) {
@@ -787,7 +789,7 @@ public final class YangParserImpl implements YangContextParser {
      *            SchemaContext containing already resolved modules
      */
     private void resolveAugmentsTargetPath(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            SchemaContext context) {
+            final SchemaContext context) {
         // collect augments from all loaded modules
         final List<AugmentationSchemaBuilder> allAugments = new ArrayList<>();
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
@@ -865,7 +867,7 @@ public final class YangParserImpl implements YangContextParser {
                 newPath.add(new QName(ns, rev, localPrefix, qn.getLocalName()));
             }
         }
-        augment.setTargetNodeSchemaPath(new SchemaPath(newPath, true));
+        augment.setTargetNodeSchemaPath(SchemaPath.create(newPath, true));
 
         for (DataSchemaNodeBuilder childNode : augment.getChildNodeBuilders()) {
             correctPathForAugmentNodes(childNode, augment.getTargetNodeSchemaPath());
@@ -881,8 +883,8 @@ public final class YangParserImpl implements YangContextParser {
      * @param parentPath
      *            schema path of parent node
      */
-    private void correctPathForAugmentNodes(DataSchemaNodeBuilder node, SchemaPath parentPath) {
-        SchemaPath newPath = ParserUtils.createSchemaPath(parentPath, node.getQName());
+    private void correctPathForAugmentNodes(final DataSchemaNodeBuilder node, final SchemaPath parentPath) {
+        SchemaPath newPath = parentPath.createChild(node.getQName());
         node.setPath(newPath);
         if (node instanceof DataNodeContainerBuilder) {
             for (DataSchemaNodeBuilder child : ((DataNodeContainerBuilder) node).getChildNodeBuilders()) {
@@ -904,7 +906,7 @@ public final class YangParserImpl implements YangContextParser {
      * @param augments
      *            augments to check
      */
-    private void checkAugmentMandatoryNodes(Collection<AugmentationSchemaBuilder> augments) {
+    private void checkAugmentMandatoryNodes(final Collection<AugmentationSchemaBuilder> augments) {
         for (AugmentationSchemaBuilder augment : augments) {
             String augmentPrefix = augment.getTargetPath().getPath().get(0).getPrefix();
             ModuleBuilder module = ParserUtils.getParentModule(augment);
@@ -1270,7 +1272,7 @@ public final class YangParserImpl implements YangContextParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUses(UsesNodeBuilder usesNode,
+    private void resolveUses(final UsesNodeBuilder usesNode,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
         if (!usesNode.isResolved()) {
             DataNodeContainerBuilder parent = usesNode.getParent();
@@ -1307,7 +1309,7 @@ public final class YangParserImpl implements YangContextParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUsesWithContext(UsesNodeBuilder usesNode) {
+    private void resolveUsesWithContext(final UsesNodeBuilder usesNode) {
         final int line = usesNode.getLine();
         DataNodeContainerBuilder parent = usesNode.getParent();
         ModuleBuilder module = ParserUtils.getParentModule(parent);
index 0990f0c95fa204c9e447c9f9454ce236d76c4d69..cc4ac33d3afee232f834b229efdeb5cf1d557f95 100644 (file)
@@ -7,14 +7,33 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
-import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.*;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.checkMissingBody;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.createActualSchemaPath;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.createListKey;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.getConfig;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.getIdentityrefBase;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseConstraints;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseDefault;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseRefine;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseSchemaNodeArgs;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseStatus;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseTypeWithBody;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseUnits;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseUnknownTypeWithBody;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseUserOrdered;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseYinValue;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.stringFromNode;
 
+import com.google.common.base.Strings;
 import java.net.URI;
-import java.text.*;
-import java.util.*;
-
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Stack;
 import org.antlr.v4.runtime.tree.ParseTree;
-import org.opendaylight.yangtools.antlrv4.code.gen.*;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Contact_stmtContext;
@@ -45,19 +64,37 @@ import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Type_body_stmtsCon
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yang_version_stmtContext;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParserBaseListener;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.util.BaseTypes;
 import org.opendaylight.yangtools.yang.model.util.YangTypesConverter;
-import org.opendaylight.yangtools.yang.parser.builder.api.*;
-import org.opendaylight.yangtools.yang.parser.builder.impl.*;
+import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
+import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.AnyXmlBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.DeviationBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ExtensionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.FeatureBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.IdentitySchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.LeafListSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ListSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.NotificationBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.RpcDefinitionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.util.RefineHolder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Strings;
-
 public final class YangParserListenerImpl extends YangParserBaseListener {
     private static final Logger LOGGER = LoggerFactory.getLogger(YangParserListenerImpl.class);
     private static final String AUGMENT_STR = "augment";
@@ -87,7 +124,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterModule_stmt(YangParser.Module_stmtContext ctx) {
         moduleName = stringFromNode(ctx);
-        LOGGER.debug("entering module " + moduleName);
+        LOGGER.trace("entering module " + moduleName);
         enterLog("module", moduleName, 0);
         actualPath.push(new Stack<QName>());
 
@@ -119,7 +156,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
 
     @Override public void enterSubmodule_stmt(YangParser.Submodule_stmtContext ctx) {
         moduleName = stringFromNode(ctx);
-        LOGGER.debug("entering submodule " + moduleName);
+        LOGGER.trace("entering submodule " + moduleName);
         enterLog("submodule", moduleName, 0);
         actualPath.push(new Stack<QName>());
 
index fe32493b120efbe97cd3df5a3b7f426a8c6c4e51..41066939c79ac1fed046a8702a64316d01a589dd 100644 (file)
@@ -145,7 +145,7 @@ public class URLSchemaContextResolver implements AdvancedSchemaSourceProvider<In
             }
             currentSourceContext = context;
         } catch (Exception e) {
-            LOG.error("Could not create schema context for {} ",context.getValidSources());
+            LOG.error("Could not create schema context for {} ", context.getValidSources(), e);
         }
         return Optional.absent();
     }
index eccd60dd1a99c3a1d49747129c9fed793f86b0da..fe0e81e43e22debf9286b50402c4d6dc24ee0674 100644 (file)
@@ -9,11 +9,9 @@ package org.opendaylight.yangtools.yang.parser.impl.util;
 
 import java.io.InputStream;
 import java.util.Collections;
-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 org.opendaylight.yangtools.yang.common.QName;
@@ -22,16 +20,12 @@ import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider;
 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
-import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
 import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableMultimap;
 import com.google.common.collect.ImmutableSet;
 
@@ -43,10 +37,10 @@ public class YangSourceContext implements AdvancedSchemaSourceProvider<InputStre
     private final ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependencies;
     private AdvancedSchemaSourceProvider<InputStream> sourceProvider;
 
-    private YangSourceContext(ImmutableSet<SourceIdentifier> validSourcesSet,
-            ImmutableSet<SourceIdentifier> missingSourcesSet,
-            ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap,
-            AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
+    YangSourceContext(final ImmutableSet<SourceIdentifier> validSourcesSet,
+            final ImmutableSet<SourceIdentifier> missingSourcesSet,
+            final ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap,
+            final AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
         validSources = validSourcesSet;
         missingSources = missingSourcesSet;
         missingDependencies = missingDependenciesMap;
@@ -66,12 +60,12 @@ public class YangSourceContext implements AdvancedSchemaSourceProvider<InputStre
     }
 
     @Override
-    public Optional<InputStream> getSchemaSource(String moduleName, Optional<String> revision) {
+    public Optional<InputStream> getSchemaSource(final String moduleName, final Optional<String> revision) {
         return getSchemaSource(SourceIdentifier.create(moduleName, revision));
     }
 
     @Override
-    public Optional<InputStream> getSchemaSource(SourceIdentifier sourceIdentifier) {
+    public Optional<InputStream> getSchemaSource(final SourceIdentifier sourceIdentifier) {
         if (validSources.contains(sourceIdentifier)) {
             return getDelegateChecked().getSchemaSource(sourceIdentifier);
         }
@@ -90,30 +84,30 @@ public class YangSourceContext implements AdvancedSchemaSourceProvider<InputStre
         }
     }
 
-    public static final YangSourceContext createFrom(Iterable<QName> capabilities,
-            SchemaSourceProvider<InputStream> schemaSourceProvider) {
+    public static final YangSourceContext createFrom(final Iterable<QName> capabilities,
+            final SchemaSourceProvider<InputStream> schemaSourceProvider) {
         YangSourceContextResolver resolver = new YangSourceFromCapabilitiesResolver(capabilities, schemaSourceProvider);
         return resolver.resolveContext();
     }
 
-    public static final YangSourceContext createFrom(Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
+    public static final YangSourceContext createFrom(final Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
         YangSourceContextResolver resolver = new YangSourceFromDependencyInfoResolver(moduleDependencies);
         return resolver.resolveContext();
     }
 
-    public static final SchemaContext toSchemaContext(YangSourceContext context) {
+    public static final SchemaContext toSchemaContext(final YangSourceContext context) {
         List<InputStream> inputStreams = getValidInputStreams(context);
         YangParserImpl parser = new YangParserImpl();
         Set<Module> models = parser.parseYangModelsFromStreams(inputStreams);
         return parser.resolveSchemaContext(models);
     }
 
-    public static List<InputStream> getValidInputStreams(YangSourceContext context) {
+    public static List<InputStream> getValidInputStreams(final YangSourceContext context) {
         return getValidInputStreams(context, context.sourceProvider);
     }
 
-    public static List<InputStream> getValidInputStreams(YangSourceContext context,
-            AdvancedSchemaSourceProvider<InputStream> provider) {
+    public static List<InputStream> getValidInputStreams(final YangSourceContext context,
+            final AdvancedSchemaSourceProvider<InputStream> provider) {
         final HashSet<SourceIdentifier> sourcesToLoad = new HashSet<>();
         sourcesToLoad.addAll(context.getValidSources());
         for (SourceIdentifier source : context.getValidSources()) {
@@ -131,193 +125,4 @@ public class YangSourceContext implements AdvancedSchemaSourceProvider<InputStre
         }
         return ret.build();
     }
-
-    public static abstract class YangSourceContextResolver {
-
-        private static final Logger LOG = LoggerFactory.getLogger(YangSourceContextResolver.class);
-
-        private final AdvancedSchemaSourceProvider<InputStream> sourceProvider;
-
-        public AdvancedSchemaSourceProvider<InputStream> getSourceProvider() {
-            return sourceProvider;
-        }
-
-        private final HashMap<SourceIdentifier, ResolutionState> alreadyProcessed = new HashMap<>();
-
-        private final ImmutableSet.Builder<SourceIdentifier> missingSources = ImmutableSet.builder();
-
-        private ImmutableMultimap.Builder<SourceIdentifier, ModuleImport> missingDependencies = ImmutableMultimap
-                .builder();
-
-        private final ImmutableSet.Builder<SourceIdentifier> validSources = ImmutableSet.builder();
-
-        public YangSourceContextResolver() {
-            sourceProvider = null;
-        }
-
-        public YangSourceContextResolver(AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
-            super();
-            this.sourceProvider = sourceProvicer;
-        }
-
-        public abstract YangSourceContext resolveContext();
-
-        public ResolutionState resolveSource(String name, Optional<String> formattedRevision) {
-            return resolveSource(new SourceIdentifier(name, formattedRevision));
-        }
-
-        public ResolutionState resolveSource(SourceIdentifier identifier) {
-
-            if (alreadyProcessed.containsKey(identifier)) {
-                return alreadyProcessed.get(identifier);
-            }
-            LOG.trace("Resolving source: {}", identifier);
-            ResolutionState potentialState = ResolutionState.EVERYTHING_OK;
-            try {
-                Optional<YangModelDependencyInfo> potentialInfo = getDependencyInfo(identifier);
-                if (potentialInfo.isPresent()) {
-                    YangModelDependencyInfo info = potentialInfo.get();
-                    checkValidSource(identifier, info);
-                    for (ModuleImport dependency : info.getDependencies()) {
-                        LOG.trace("Source: {} Resolving dependency: {}", identifier, dependency);
-                        ResolutionState dependencyState = resolveDependency(dependency);
-                        if (dependencyState != ResolutionState.EVERYTHING_OK) {
-                            potentialState = ResolutionState.MISSING_DEPENDENCY;
-                            missingDependencies.put(identifier, dependency);
-                        }
-                    }
-                } else {
-                    missingSources.add(identifier);
-                    return ResolutionState.MISSING_SOURCE;
-                }
-            } catch (Exception e) {
-                potentialState = ResolutionState.OTHER_ERROR;
-            }
-            updateResolutionState(identifier, potentialState);
-            return potentialState;
-        }
-
-        public abstract Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier);
-
-        private boolean checkValidSource(SourceIdentifier identifier, YangModelDependencyInfo info) {
-            if (!identifier.getName().equals(info.getName())) {
-                LOG.warn("Incorrect model returned. Identifier name was: {}, source contained: {}",
-                        identifier.getName(), info.getName());
-                throw new IllegalStateException("Incorrect source was returned");
-            }
-            return true;
-        }
-
-        private void updateResolutionState(SourceIdentifier identifier, ResolutionState potentialState) {
-            alreadyProcessed.put(identifier, potentialState);
-            switch (potentialState) {
-            case MISSING_SOURCE:
-                missingSources.add(identifier);
-                break;
-            case EVERYTHING_OK:
-                validSources.add(identifier);
-                break;
-            default:
-                break;
-            }
-        }
-
-        private ResolutionState resolveDependency(ModuleImport dependency) {
-            String name = dependency.getModuleName();
-            Optional<String> formattedRevision = Optional
-                    .fromNullable(QName.formattedRevision(dependency.getRevision()));
-            return resolveSource(new SourceIdentifier(name, formattedRevision));
-        }
-
-        protected YangSourceContext createSourceContext() {
-
-            ImmutableSet<SourceIdentifier> missingSourcesSet = missingSources.build();
-            ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap = missingDependencies.build();
-            ImmutableSet<SourceIdentifier> validSourcesSet = validSources.build();
-
-            return new YangSourceContext(validSourcesSet, missingSourcesSet, missingDependenciesMap, sourceProvider);
-
-        }
-    }
-
-    private enum ResolutionState {
-        MISSING_SOURCE, MISSING_DEPENDENCY, OTHER_ERROR, EVERYTHING_OK
-    }
-
-    public static final class YangSourceFromCapabilitiesResolver extends YangSourceContextResolver {
-
-        private Iterable<QName> capabilities;
-
-        public YangSourceFromCapabilitiesResolver(Iterable<QName> capabilities,
-                SchemaSourceProvider<InputStream> schemaSourceProvider) {
-            super(SchemaSourceProviders.toAdvancedSchemaSourceProvider(schemaSourceProvider));
-            this.capabilities = capabilities;
-        }
-
-        @Override
-        public YangSourceContext resolveContext() {
-            for (QName capability : capabilities) {
-                resolveCapability(capability);
-            }
-            return createSourceContext();
-        }
-
-        private void resolveCapability(QName capability) {
-            super.resolveSource(capability.getLocalName(), Optional.fromNullable(capability.getFormattedRevision()));
-        }
-
-        @Override
-        public Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier) {
-            Optional<InputStream> source = getSchemaSource(identifier);
-            if (source.isPresent()) {
-                return Optional.of(YangModelDependencyInfo.fromInputStream(source.get()));
-            }
-            return Optional.absent();
-        }
-
-        private Optional<InputStream> getSchemaSource(SourceIdentifier identifier) {
-            return getSourceProvider().getSchemaSource(identifier.getName(),
-                    Optional.fromNullable(identifier.getRevision()));
-        }
-
-    }
-
-    public static final class YangSourceFromDependencyInfoResolver extends YangSourceContextResolver {
-
-        private final Map<SourceIdentifier, YangModelDependencyInfo> dependencyInfo;
-
-        public YangSourceFromDependencyInfoResolver(Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
-            dependencyInfo = ImmutableMap.copyOf(moduleDependencies);
-        }
-
-        @Override
-        public Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier) {
-            if (identifier.getRevision() != null) {
-                return Optional.fromNullable(dependencyInfo.get(identifier));
-            }
-            YangModelDependencyInfo potential = dependencyInfo.get(identifier);
-            if (potential == null) {
-                for (Entry<SourceIdentifier, YangModelDependencyInfo> newPotential : dependencyInfo.entrySet()) {
-                    String newPotentialName = newPotential.getKey().getName();
-
-                    if (newPotentialName.equals(identifier.getName())) {
-                        String newPotentialRevision = newPotential.getKey().getRevision();
-                        if (potential == null || 1 == newPotentialRevision.compareTo(potential.getFormattedRevision())) {
-                            potential = newPotential.getValue();
-                        }
-                    }
-                }
-            }
-            return Optional.fromNullable(potential);
-        }
-
-        @Override
-        public YangSourceContext resolveContext() {
-            for (SourceIdentifier source : dependencyInfo.keySet()) {
-                resolveSource(source);
-            }
-            return createSourceContext();
-        }
-    }
-
 }
diff --git a/yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceContextResolver.java b/yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceContextResolver.java
new file mode 100644 (file)
index 0000000..50f4a3e
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * 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/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.parser.impl.util;
+
+import java.io.InputStream;
+import java.util.HashMap;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ModuleImport;
+import org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+
+public abstract class YangSourceContextResolver {
+
+    enum ResolutionState {
+        MISSING_SOURCE,
+        MISSING_DEPENDENCY,
+        OTHER_ERROR,
+        EVERYTHING_OK,
+    }
+
+    private static final Logger LOG = LoggerFactory.getLogger(YangSourceContextResolver.class);
+    private final HashMap<SourceIdentifier, YangSourceContextResolver.ResolutionState> alreadyProcessed = new HashMap<>();
+    private final ImmutableSet.Builder<SourceIdentifier> missingSources = ImmutableSet.builder();
+    private final ImmutableMultimap.Builder<SourceIdentifier, ModuleImport> missingDependencies =
+            ImmutableMultimap.builder();
+    private final ImmutableSet.Builder<SourceIdentifier> validSources = ImmutableSet.builder();
+    private final AdvancedSchemaSourceProvider<InputStream> sourceProvider;
+
+    public YangSourceContextResolver() {
+        sourceProvider = null;
+    }
+
+    public YangSourceContextResolver(final AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
+        super();
+        this.sourceProvider = sourceProvicer;
+    }
+
+    public abstract YangSourceContext resolveContext();
+    public abstract Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier);
+
+    public AdvancedSchemaSourceProvider<InputStream> getSourceProvider() {
+        return sourceProvider;
+    }
+
+    public YangSourceContextResolver.ResolutionState resolveSource(final String name, final Optional<String> formattedRevision) {
+        return resolveSource(new SourceIdentifier(name, formattedRevision));
+    }
+
+    public YangSourceContextResolver.ResolutionState resolveSource(final SourceIdentifier identifier) {
+
+        if (alreadyProcessed.containsKey(identifier)) {
+            return alreadyProcessed.get(identifier);
+        }
+        LOG.trace("Resolving source: {}", identifier);
+        YangSourceContextResolver.ResolutionState potentialState = YangSourceContextResolver.ResolutionState.EVERYTHING_OK;
+        try {
+            Optional<YangModelDependencyInfo> potentialInfo = getDependencyInfo(identifier);
+            if (potentialInfo.isPresent()) {
+                YangModelDependencyInfo info = potentialInfo.get();
+                checkValidSource(identifier, info);
+                for (ModuleImport dependency : info.getDependencies()) {
+                    LOG.trace("Source: {} Resolving dependency: {}", identifier, dependency);
+                    YangSourceContextResolver.ResolutionState dependencyState = resolveDependency(dependency);
+                    if (dependencyState != YangSourceContextResolver.ResolutionState.EVERYTHING_OK) {
+                        potentialState = YangSourceContextResolver.ResolutionState.MISSING_DEPENDENCY;
+                        missingDependencies.put(identifier, dependency);
+                    }
+                }
+            } else {
+                missingSources.add(identifier);
+                return YangSourceContextResolver.ResolutionState.MISSING_SOURCE;
+            }
+        } catch (Exception e) {
+            potentialState = YangSourceContextResolver.ResolutionState.OTHER_ERROR;
+        }
+        updateResolutionState(identifier, potentialState);
+        return potentialState;
+    }
+
+    private boolean checkValidSource(final SourceIdentifier identifier, final YangModelDependencyInfo info) {
+        if (!identifier.getName().equals(info.getName())) {
+            LOG.warn("Incorrect model returned. Identifier name was: {}, source contained: {}",
+                    identifier.getName(), info.getName());
+            throw new IllegalStateException("Incorrect source was returned");
+        }
+        return true;
+    }
+
+    private void updateResolutionState(final SourceIdentifier identifier, final YangSourceContextResolver.ResolutionState potentialState) {
+        alreadyProcessed.put(identifier, potentialState);
+        switch (potentialState) {
+        case MISSING_SOURCE:
+            missingSources.add(identifier);
+            break;
+        case EVERYTHING_OK:
+            validSources.add(identifier);
+            break;
+        default:
+            break;
+        }
+    }
+
+    private YangSourceContextResolver.ResolutionState resolveDependency(final ModuleImport dependency) {
+        String name = dependency.getModuleName();
+        Optional<String> formattedRevision = Optional
+                .fromNullable(QName.formattedRevision(dependency.getRevision()));
+        return resolveSource(new SourceIdentifier(name, formattedRevision));
+    }
+
+    protected YangSourceContext createSourceContext() {
+        ImmutableSet<SourceIdentifier> missingSourcesSet = missingSources.build();
+        ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap = missingDependencies.build();
+        ImmutableSet<SourceIdentifier> validSourcesSet = validSources.build();
+        return new YangSourceContext(validSourcesSet, missingSourcesSet, missingDependenciesMap, sourceProvider);
+    }
+}
diff --git a/yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceFromCapabilitiesResolver.java b/yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceFromCapabilitiesResolver.java
new file mode 100644 (file)
index 0000000..92d3fbd
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * 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/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.parser.impl.util;
+
+import java.io.InputStream;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
+import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
+
+import com.google.common.base.Optional;
+
+public final class YangSourceFromCapabilitiesResolver extends YangSourceContextResolver {
+
+    private final Iterable<QName> capabilities;
+
+    public YangSourceFromCapabilitiesResolver(final Iterable<QName> capabilities,
+            final SchemaSourceProvider<InputStream> schemaSourceProvider) {
+        super(SchemaSourceProviders.toAdvancedSchemaSourceProvider(schemaSourceProvider));
+        this.capabilities = capabilities;
+    }
+
+    @Override
+    public YangSourceContext resolveContext() {
+        for (QName capability : capabilities) {
+            resolveCapability(capability);
+        }
+        return createSourceContext();
+    }
+
+    private void resolveCapability(final QName capability) {
+        super.resolveSource(capability.getLocalName(), Optional.fromNullable(capability.getFormattedRevision()));
+    }
+
+    @Override
+    public Optional<YangModelDependencyInfo> getDependencyInfo(final SourceIdentifier identifier) {
+        Optional<InputStream> source = getSchemaSource(identifier);
+        if (source.isPresent()) {
+            return Optional.of(YangModelDependencyInfo.fromInputStream(source.get()));
+        }
+        return Optional.absent();
+    }
+
+    private Optional<InputStream> getSchemaSource(final SourceIdentifier identifier) {
+        return getSourceProvider().getSchemaSource(identifier.getName(),
+                Optional.fromNullable(identifier.getRevision()));
+    }
+
+}
diff --git a/yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceFromDependencyInfoResolver.java b/yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/util/YangSourceFromDependencyInfoResolver.java
new file mode 100644 (file)
index 0000000..9893c6c
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * 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/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.parser.impl.util;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+
+public final class YangSourceFromDependencyInfoResolver extends YangSourceContextResolver {
+
+    private final Map<SourceIdentifier, YangModelDependencyInfo> dependencyInfo;
+
+    public YangSourceFromDependencyInfoResolver(final Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
+        dependencyInfo = ImmutableMap.copyOf(moduleDependencies);
+    }
+
+    @Override
+    public Optional<YangModelDependencyInfo> getDependencyInfo(final SourceIdentifier identifier) {
+        if (identifier.getRevision() != null) {
+            return Optional.fromNullable(dependencyInfo.get(identifier));
+        }
+        YangModelDependencyInfo potential = dependencyInfo.get(identifier);
+        if (potential == null) {
+            for (Entry<SourceIdentifier, YangModelDependencyInfo> newPotential : dependencyInfo.entrySet()) {
+                String newPotentialName = newPotential.getKey().getName();
+
+                if (newPotentialName.equals(identifier.getName())) {
+                    String newPotentialRevision = newPotential.getKey().getRevision();
+                    if (potential == null || 1 == newPotentialRevision.compareTo(potential.getFormattedRevision())) {
+                        potential = newPotential.getValue();
+                    }
+                }
+            }
+        }
+        return Optional.fromNullable(potential);
+    }
+
+    @Override
+    public YangSourceContext resolveContext() {
+        for (SourceIdentifier source : dependencyInfo.keySet()) {
+            resolveSource(source);
+        }
+        return createSourceContext();
+    }
+}
index 4ab49fea230e960cbc475d6d932a03096ba4d7aa..311d506e0fa583b3f1fbfee65439d3774eefcda9 100644 (file)
@@ -491,7 +491,7 @@ public final class CopyUtils {
             }
         }
 
-        SchemaPath newSchemaPath = new SchemaPath(newPath, true);
+        SchemaPath newSchemaPath = SchemaPath.create(newPath, true);
         return new DataBean(newQName, newSchemaPath);
     }
 
index 4c4b64a37cf1eeeeed0d0625a0e4c32ed58285a3..3db3065d55e1adc2c3e0392cb72892ff09f3883b 100644 (file)
@@ -7,8 +7,12 @@
  */
 package org.opendaylight.yangtools.yang.parser.util;
 
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
 import java.net.URI;
-import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -19,6 +23,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@@ -28,12 +33,6 @@ import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
 /**
  * Creates a module dependency graph from provided {@link ModuleBuilder}s and
  * provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
@@ -51,31 +50,35 @@ public final class ModuleDependencySort {
     private ModuleDependencySort() {
     }
 
+    /**
+     * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
+     */
+    private static final Function<Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<Node, ModuleBuilder>() {
+        @Override
+        public ModuleBuilder apply(final Node input) {
+            // Cast to ModuleBuilder from Node and return
+            return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
+        }
+    };
+
     /**
      * Topological sort of module builder dependency graph.
      *
      * @return Sorted list of Module builders. Modules can be further processed
      *         in returned order.
      */
-    public static List<ModuleBuilder> sort(ModuleBuilder... builders) {
+    public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
         List<Node> sorted = sortInternal(Arrays.asList(builders));
-        // Cast to ModuleBuilder from Node and return
-        return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
-
-            @Override
-            public ModuleBuilder apply(Node input) {
-                return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
-            }
-        });
+        return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
     }
 
-    public static List<ModuleBuilder> sort(Collection<ModuleBuilder> builders) {
+    public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
         ModuleBuilder[] array = new ModuleBuilder[builders.size()];
         builders.toArray(array);
         return sort(array);
     }
 
-    public static List<ModuleBuilder> sortWithContext(SchemaContext context, ModuleBuilder... builders) {
+    public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
         List<Object> modules = new ArrayList<Object>();
         Collections.addAll(modules, builders);
         modules.addAll(context.getModules());
@@ -85,7 +88,7 @@ public final class ModuleDependencySort {
         return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
 
             @Override
-            public ModuleBuilder apply(Node input) {
+            public ModuleBuilder apply(final Node input) {
                 if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
                     return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
                 } else {
@@ -101,19 +104,19 @@ public final class ModuleDependencySort {
      * @return Sorted list of Modules. Modules can be further processed in
      *         returned order.
      */
-    public static List<Module> sort(Module... modules) {
+    public static List<Module> sort(final Module... modules) {
         List<Node> sorted = sortInternal(Arrays.asList(modules));
         // Cast to Module from Node and return
         return Lists.transform(sorted, new Function<Node, Module>() {
 
             @Override
-            public Module apply(Node input) {
+            public Module apply(final Node input) {
                 return (Module) ((ModuleNodeImpl) input).getReference();
             }
         });
     }
 
-    private static List<Node> sortInternal(List<?> modules) {
+    private static List<Node> sortInternal(final List<?> modules) {
         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
 
         Set<Node> nodes = Sets.newHashSet();
@@ -127,7 +130,7 @@ public final class ModuleDependencySort {
     }
 
     @VisibleForTesting
-    static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(List<?> builders) {
+    static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final List<?> builders) {
         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
 
         processModules(moduleGraph, builders);
@@ -139,7 +142,7 @@ public final class ModuleDependencySort {
     /**
      * Extract module:revision from module builders
      */
-    private static void processDependencies(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
+    private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
         Map<URI, Object> allNS = new HashMap<>();
 
         // Create edges in graph
@@ -219,8 +222,8 @@ public final class ModuleDependencySort {
     /**
      * Get imported module by its name and revision from moduleGraph
      */
-    private static ModuleNodeImpl getModuleByNameAndRevision(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
-            String fromName, Date fromRevision, String toName, Date toRevision) {
+    private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
+            final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
         ModuleNodeImpl to = null;
 
         if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
@@ -229,7 +232,7 @@ public final class ModuleDependencySort {
             if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
                     && toRevision.equals(DEFAULT_REVISION)) {
                 to = moduleGraph.get(toName).values().iterator().next();
-                LOGGER.debug(String
+                LOGGER.trace(String
                         .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
                                 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
                                 formatRevDate(to.getRevision())));
@@ -246,7 +249,7 @@ public final class ModuleDependencySort {
         return to;
     }
 
-    private static void ex(String message) {
+    private static void ex(final String message) {
         throw new YangValidationException(message);
     }
 
@@ -254,7 +257,7 @@ public final class ModuleDependencySort {
      * Extract dependencies from module builders or modules to fill dependency
      * graph
      */
-    private static void processModules(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
+    private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
 
         // Process nodes
         for (Object mb : builders) {
@@ -290,8 +293,8 @@ public final class ModuleDependencySort {
         }
     }
 
-    private static String formatRevDate(Date rev) {
-        return rev.equals(DEFAULT_REVISION) ? "default" : new SimpleDateFormat("yyyy-MM-dd").format(rev);
+    private static String formatRevDate(final Date rev) {
+        return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
     }
 
     @VisibleForTesting
@@ -300,7 +303,7 @@ public final class ModuleDependencySort {
         private final Date revision;
         private final Object originalObject;
 
-        public ModuleNodeImpl(String name, Date revision, Object builder) {
+        public ModuleNodeImpl(final String name, final Date revision, final Object builder) {
             this.name = name;
             this.revision = revision;
             this.originalObject = builder;
@@ -324,7 +327,7 @@ public final class ModuleDependencySort {
         }
 
         @Override
-        public boolean equals(Object obj) {
+        public boolean equals(final Object obj) {
             if (this == obj) {
                 return true;
             }
index fd5bd9d2d86930c6e1fe91012c1df65d5848c865..9d7e599c418d4fe6fdbeafd22d77f3cb7569f163 100644 (file)
@@ -8,15 +8,14 @@
 
 package org.opendaylight.yangtools.yang.parser.util;
 
-import org.apache.commons.io.IOUtils;
-
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import org.apache.commons.io.IOUtils;
 
 public class NamedByteArrayInputStream extends ByteArrayInputStream implements NamedInputStream {
     private final String toString;
-    private NamedByteArrayInputStream(byte[] buf, String toString) {
+    public NamedByteArrayInputStream(byte[] buf, String toString) {
         super(buf);
         this.toString = toString;
     }
index 059b368590f3ecc95100eac0d77b76d685d62d1c..c4e79e6710388bf1e2401e8c91e89f90c798f0c2 100644 (file)
@@ -20,7 +20,7 @@ import java.util.Stack;
 import org.antlr.v4.runtime.ParserRuleContext;
 import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.TerminalNode;
-import org.opendaylight.yangtools.antlrv4.code.gen.*;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
@@ -154,7 +154,7 @@ public final class ParserListenerUtils {
         return result;
     }
 
-    public static String stringFromStringContext(StringContext context) {
+    public static String stringFromStringContext(final StringContext context) {
         StringBuilder str = new StringBuilder();
         for (TerminalNode stringNode : context.STRING()) {
             String result = stringNode.getText();
@@ -291,8 +291,7 @@ public final class ParserListenerUtils {
      * @return SchemaPath object
      */
     public static SchemaPath createActualSchemaPath(final Stack<QName> actualPath) {
-        final List<QName> path = new ArrayList<>(actualPath);
-        return new SchemaPath(path, true);
+        return SchemaPath.create(actualPath, true);
     }
 
     /**
@@ -413,7 +412,7 @@ public final class ParserListenerUtils {
         private String description;
         private String reference;
         private Status status;
-        private List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
+        private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
         private String name;
         private Integer value;
 
@@ -470,7 +469,7 @@ public final class ParserListenerUtils {
         }
 
         @Override
-        public boolean equals(Object obj) {
+        public boolean equals(final Object obj) {
             if (this == obj) {
                 return true;
             }
@@ -789,7 +788,7 @@ public final class ParserListenerUtils {
      * @return 'fraction-digits' value if present in given context, null
      *         otherwise
      */
-    private static Integer getFractionDigits(Type_body_stmtsContext ctx, String moduleName) {
+    private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
         Integer result = null;
         for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree dec64specChild = ctx.getChild(i);
@@ -809,7 +808,7 @@ public final class ParserListenerUtils {
      *            name of current module
      * @return fraction-digits value as Integer
      */
-    private static Integer parseFractionDigits(Decimal64_specificationContext ctx, String moduleName) {
+    private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
         Integer result = null;
         for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree fdChild = ctx.getChild(i);
@@ -838,8 +837,8 @@ public final class ParserListenerUtils {
      *            current module name
      * @return List of Bit objects created from this context
      */
-    private static List<BitsTypeDefinition.Bit> getBits(Type_body_stmtsContext ctx, Stack<QName> actualPath,
-            String moduleName) {
+    private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final Stack<QName> actualPath,
+            final String moduleName) {
         final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
         for (int j = 0; j < ctx.getChildCount(); j++) {
             ParseTree bitsSpecChild = ctx.getChild(j);
@@ -873,8 +872,8 @@ public final class ParserListenerUtils {
      *            current module name
      * @return Bit object parsed from this context
      */
-    private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, long highestPosition,
-            Stack<QName> actualPath, final String moduleName) {
+    private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
+            final Stack<QName> actualPath, final String moduleName) {
         String name = stringFromNode(ctx);
         Long position = null;
 
@@ -922,7 +921,7 @@ public final class ParserListenerUtils {
      *            Ordered_by_stmtContext
      * @return true, if ordered-by contains value 'user', false otherwise
      */
-    public static boolean parseUserOrdered(Ordered_by_stmtContext ctx) {
+    public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
         boolean result = false;
         for (int j = 0; j < ctx.getChildCount(); j++) {
             ParseTree orderArg = ctx.getChild(j);
@@ -987,7 +986,7 @@ public final class ParserListenerUtils {
         return result;
     }
 
-    private static boolean getParentConfig(Builder node) {
+    private static boolean getParentConfig(final Builder node) {
         Builder parent = node.getParent();
         boolean config = false;
 
@@ -1225,7 +1224,7 @@ public final class ParserListenerUtils {
 
         List<QName> path = new ArrayList<>(actualPath);
         path.add(new QName(namespace, revision, prefix, typeName));
-        SchemaPath schemaPath = new SchemaPath(path, true);
+        SchemaPath schemaPath = SchemaPath.create(path, true);
 
         QName qname = schemaPath.getPath().get(schemaPath.getPath().size() - 1);
         ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
@@ -1238,28 +1237,28 @@ public final class ParserListenerUtils {
         return typeBuilder.build();
     }
 
-    private static SchemaPath createTypePath(Stack<QName> actual, String typeName) {
+    private static SchemaPath createTypePath(final Stack<QName> actual, final String typeName) {
         QName last = actual.peek();
         QName typeQName = new QName(last.getNamespace(), last.getRevision(), last.getPrefix(), typeName);
         List<QName> path = new ArrayList<>(actual);
         path.add(typeQName);
-        return new SchemaPath(path, true);
+        return SchemaPath.create(path, true);
     }
 
-    private static SchemaPath createBaseTypePath(Stack<QName> actual, String typeName) {
+    private static SchemaPath createBaseTypePath(final Stack<QName> actual, final String typeName) {
         List<QName> path = new ArrayList<>(actual);
         path.add(BaseTypes.constructQName(typeName));
-        return new SchemaPath(path, true);
+        return SchemaPath.create(path, true);
     }
 
-    private static SchemaPath createExtendedBaseTypePath(Stack<QName> actual, URI namespace, Date revision,
-            String prefix, String typeName) {
+    private static SchemaPath createExtendedBaseTypePath(final Stack<QName> actual, final URI namespace, final Date revision,
+            final String prefix, final String typeName) {
         QName extTypeName = new QName(namespace, revision, prefix, typeName);
         QName baseTypeName = BaseTypes.constructQName(typeName);
         List<QName> path = new ArrayList<>(actual);
         path.add(extTypeName);
         path.add(baseTypeName);
-        return new SchemaPath(path, true);
+        return SchemaPath.create(path, true);
     }
 
     /**
@@ -1269,7 +1268,7 @@ public final class ParserListenerUtils {
      *            type body
      * @return identityref base value as String
      */
-    public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
+    public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
         String result = null;
         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree child = ctx.getChild(i);
@@ -1293,7 +1292,7 @@ public final class ParserListenerUtils {
      *            type body context
      * @return require-instance value
      */
-    private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
+    private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
         for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree child = ctx.getChild(i);
             if (child instanceof Instance_identifier_specificationContext) {
@@ -1320,7 +1319,7 @@ public final class ParserListenerUtils {
      *            type body context
      * @return leafref path as String
      */
-    private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
+    private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
         for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree child = ctx.getChild(i);
             if (child instanceof Leafref_specificationContext) {
@@ -1416,7 +1415,7 @@ public final class ParserListenerUtils {
         }
     }
 
-    private static Integer parseMinElements(Min_elements_stmtContext ctx, String moduleName) {
+    private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
         Integer result = null;
         try {
             for (int i = 0; i < ctx.getChildCount(); i++) {
@@ -1434,7 +1433,7 @@ public final class ParserListenerUtils {
         }
     }
 
-    private static Integer parseMaxElements(Max_elements_stmtContext ctx, String moduleName) {
+    private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
         Integer result = null;
         try {
             for (int i = 0; i < ctx.getChildCount(); i++) {
@@ -1459,7 +1458,7 @@ public final class ParserListenerUtils {
      *            context to parse
      * @return true if value is 'true', false otherwise
      */
-    public static boolean parseYinValue(Argument_stmtContext ctx) {
+    public static boolean parseYinValue(final Argument_stmtContext ctx) {
         boolean yinValue = false;
         outer: for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree yin = ctx.getChild(i);
@@ -1520,7 +1519,7 @@ public final class ParserListenerUtils {
      *            name of current module
      * @return RefineHolder object representing this refine statement
      */
-    public static RefineHolder parseRefine(Refine_stmtContext refineCtx, String moduleName) {
+    public static RefineHolder parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
         final String refineTarget = stringFromNode(refineCtx);
         final RefineHolder refine = new RefineHolder(moduleName, refineCtx.getStart().getLine(), refineTarget);
         for (int i = 0; i < refineCtx.getChildCount(); i++) {
@@ -1549,7 +1548,7 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    private static void parseRefineDefault(RefineHolder refine, ParseTree refineStmt) {
+    private static void parseRefineDefault(final RefineHolder refine, final ParseTree refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Description_stmtContext) {
@@ -1565,7 +1564,7 @@ public final class ParserListenerUtils {
         }
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(final RefineHolder refine, final Refine_leaf_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Default_stmtContext) {
@@ -1588,7 +1587,7 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine, Refine_container_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(final RefineHolder refine, final Refine_container_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Must_stmtContext) {
@@ -1601,7 +1600,7 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine, Refine_list_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(final RefineHolder refine, final Refine_list_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Must_stmtContext) {
@@ -1618,7 +1617,7 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_list_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(final RefineHolder refine, final Refine_leaf_list_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Must_stmtContext) {
@@ -1635,7 +1634,7 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine, Refine_choice_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(final RefineHolder refine, final Refine_choice_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Default_stmtContext) {
@@ -1654,7 +1653,7 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine, Refine_anyxml_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(final RefineHolder refine, final Refine_anyxml_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Must_stmtContext) {
@@ -1673,13 +1672,13 @@ public final class ParserListenerUtils {
         return refine;
     }
 
-    public static String getArgumentString(org.antlr.v4.runtime.ParserRuleContext ctx) {
+    public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
         List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
         checkState(!potentialValues.isEmpty());
         return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
     }
 
-    public static <T extends ParserRuleContext> Optional<T> getFirstContext(ParserRuleContext context,Class<T> contextType) {
+    public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
         List<T> potential = context.getRuleContexts(contextType);
         if(potential.isEmpty()) {
             return Optional.absent();
index bd227125df7d57a4acf241f9699475a889c8ddb9..82d7014cfbf2fced74340464f753055b27d72341 100644 (file)
@@ -7,10 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.parser.util;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Collections2;
-import com.google.common.io.ByteSource;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -21,10 +18,12 @@ import java.util.Arrays;
 import java.util.Collection;
 import java.util.Date;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeMap;
+
 import org.apache.commons.io.IOUtils;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
@@ -71,25 +70,27 @@ import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuil
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Collections2;
+import com.google.common.io.ByteSource;
+
 public final class ParserUtils {
 
     private static final Logger LOG = LoggerFactory.getLogger(ParserUtils.class);
+    private static final Splitter SLASH_SPLITTER = Splitter.on('/');
+    private static final Splitter COLON_SPLITTER = Splitter.on(':');
 
     private ParserUtils() {
     }
 
-    public static Collection<ByteSource> streamsToByteSources(Collection<InputStream> streams) {
-        return Collections2.transform(streams, new Function<InputStream, ByteSource>() {
-            @Override
-            public ByteSource apply(final InputStream input) {
-                return new ByteSource() {
-                    @Override
-                    public InputStream openStream() throws IOException {
-                        return NamedByteArrayInputStream.create(input);
-                    }
-                };
-            }
-        });
+    public static Collection<ByteSource> streamsToByteSources(final Collection<InputStream> streams) throws IOException {
+        Collection<ByteSource> result = new HashSet<>();
+        for (InputStream stream : streams) {
+            result.add(new ByteSourceImpl(stream));
+        }
+        return result;
     }
 
     public static ByteSource fileToByteSource(final File file) {
@@ -101,7 +102,7 @@ public final class ParserUtils {
         };
     }
 
-    public static Collection<ByteSource> filesToByteSources(Collection<File> streams) throws FileNotFoundException {
+    public static Collection<ByteSource> filesToByteSources(final Collection<File> streams) throws FileNotFoundException {
         return Collections2.transform(streams, new Function<File, ByteSource>() {
             @Override
             public ByteSource apply(final File input) {
@@ -121,7 +122,7 @@ public final class ParserUtils {
      * @param sourceToBuilder
      *            source to module mapping
      */
-    public static void setSourceToBuilder(Map<ByteSource, ModuleBuilder> sourceToBuilder) throws IOException {
+    public static void setSourceToBuilder(final Map<ByteSource, ModuleBuilder> sourceToBuilder) throws IOException {
         for (Map.Entry<ByteSource, ModuleBuilder> entry : sourceToBuilder.entrySet()) {
             ModuleBuilder builder = entry.getValue();
             ByteSource source = entry.getKey();
@@ -152,11 +153,14 @@ public final class ParserUtils {
      * @param qname
      *            one or more qnames added to base path
      * @return new SchemaPath from given path and qname
+     *
+     * @deprecated Use {@link SchemaPath#createChild(QName...)} instead.
      */
-    public static SchemaPath createSchemaPath(SchemaPath schemaPath, QName... qname) {
+    @Deprecated
+    public static SchemaPath createSchemaPath(final SchemaPath schemaPath, final QName... qname) {
         List<QName> path = new ArrayList<>(schemaPath.getPath());
         path.addAll(Arrays.asList(qname));
-        return new SchemaPath(path, schemaPath.isAbsolute());
+        return SchemaPath.create(path, schemaPath.isAbsolute());
     }
 
     /**
@@ -168,7 +172,7 @@ public final class ParserUtils {
      *            prefix associated with import
      * @return ModuleImport based on given prefix
      */
-    public static ModuleImport getModuleImport(ModuleBuilder builder, String prefix) {
+    public static ModuleImport getModuleImport(final ModuleBuilder builder, final String prefix) {
         for (ModuleImport mi : builder.getModuleImports()) {
             if (mi.getPrefix().equals(prefix)) {
                 return mi;
@@ -191,8 +195,8 @@ public final class ParserUtils {
      *            current line in yang model
      * @return module builder if found, null otherwise
      */
-    public static ModuleBuilder findModuleFromBuilders(Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder module, String prefix, int line) {
+    public static ModuleBuilder findModuleFromBuilders(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final ModuleBuilder module, final String prefix, final int line) {
         ModuleBuilder dependentModule = null;
         Date dependentModuleRevision = null;
 
@@ -234,8 +238,8 @@ public final class ParserUtils {
      *            current line in yang model
      * @return module based on given prefix if found in context, null otherwise
      */
-    public static Module findModuleFromContext(SchemaContext context, ModuleBuilder currentModule, String prefix,
-            int line) {
+    public static Module findModuleFromContext(final SchemaContext context, final ModuleBuilder currentModule, final String prefix,
+            final int line) {
         if (context == null) {
             throw new YangParseException(currentModule.getName(), line, "Cannot find module with prefix '" + prefix
                     + "'.");
@@ -275,23 +279,25 @@ public final class ParserUtils {
      *            XPath as String
      * @return SchemaPath from given String
      */
-    public static SchemaPath parseXPathString(String xpathString) {
-        boolean absolute = xpathString.startsWith("/");
-        String[] splittedPath = xpathString.split("/");
-        List<QName> path = new ArrayList<QName>();
-        QName name;
-        for (String pathElement : splittedPath) {
+    public static SchemaPath parseXPathString(final String xpathString) {
+        final boolean absolute = xpathString.indexOf('/') == 0;
+
+        final List<QName> path = new ArrayList<QName>();
+        for (String pathElement : SLASH_SPLITTER.split(xpathString)) {
             if (pathElement.length() > 0) {
-                String[] splittedElement = pathElement.split(":");
-                if (splittedElement.length == 1) {
-                    name = new QName(null, null, null, splittedElement[0]);
+                final Iterator<String> it = COLON_SPLITTER.split(pathElement).iterator();
+                final String s = it.next();
+
+                final QName name;
+                if (it.hasNext()) {
+                    name = new QName(null, null, s, it.next());
                 } else {
-                    name = new QName(null, null, splittedElement[0], splittedElement[1]);
+                    name = new QName(null, null, null, s);
                 }
                 path.add(name);
             }
         }
-        return new SchemaPath(path, absolute);
+        return SchemaPath.create(path, absolute);
     }
 
     /**
@@ -302,7 +308,7 @@ public final class ParserUtils {
      * @param target
      *            augmentation target node
      */
-    public static void fillAugmentTarget(AugmentationSchemaBuilder augment, Builder target) {
+    public static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final Builder target) {
         if (target instanceof DataNodeContainerBuilder) {
             fillAugmentTarget(augment, (DataNodeContainerBuilder) target);
         } else if (target instanceof ChoiceBuilder) {
@@ -323,7 +329,7 @@ public final class ParserUtils {
      * @param target
      *            augmentation target node
      */
-    private static void fillAugmentTarget(AugmentationSchemaBuilder augment, DataNodeContainerBuilder target) {
+    private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final DataNodeContainerBuilder target) {
         for (DataSchemaNodeBuilder child : augment.getChildNodeBuilders()) {
             DataSchemaNodeBuilder childCopy = CopyUtils.copy(child, target, false);
             if (augment.getParent() instanceof UsesNodeBuilder) {
@@ -349,7 +355,7 @@ public final class ParserUtils {
      * @param target
      *            augmentation target choice node
      */
-    private static void fillAugmentTarget(AugmentationSchemaBuilder augment, ChoiceBuilder target) {
+    private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final ChoiceBuilder target) {
         for (DataSchemaNodeBuilder builder : augment.getChildNodeBuilders()) {
             DataSchemaNodeBuilder childCopy = CopyUtils.copy(builder, target, false);
             if (augment.getParent() instanceof UsesNodeBuilder) {
@@ -371,7 +377,7 @@ public final class ParserUtils {
      *
      * @param node
      */
-    private static void setNodeAugmenting(DataSchemaNodeBuilder node) {
+    private static void setNodeAugmenting(final DataSchemaNodeBuilder node) {
         node.setAugmenting(true);
         if (node instanceof DataNodeContainerBuilder) {
             DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
@@ -391,7 +397,7 @@ public final class ParserUtils {
      *
      * @param node
      */
-    public static void setNodeAddedByUses(GroupingMember node) {
+    public static void setNodeAddedByUses(final GroupingMember node) {
         node.setAddedByUses(true);
         if (node instanceof DataNodeContainerBuilder) {
             DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
@@ -414,7 +420,7 @@ public final class ParserUtils {
      * @param config
      *            new config value
      */
-    public static void setNodeConfig(DataSchemaNodeBuilder node, Boolean config) {
+    public static void setNodeConfig(final DataSchemaNodeBuilder node, final Boolean config) {
         if (node instanceof ContainerSchemaNodeBuilder || node instanceof LeafSchemaNodeBuilder
                 || node instanceof LeafListSchemaNodeBuilder || node instanceof ListSchemaNodeBuilder
                 || node instanceof ChoiceBuilder || node instanceof AnyXmlBuilder) {
@@ -433,7 +439,7 @@ public final class ParserUtils {
         }
     }
 
-    public static DataSchemaNodeBuilder findSchemaNode(List<QName> path, SchemaNodeBuilder parentNode) {
+    public static DataSchemaNodeBuilder findSchemaNode(final List<QName> path, final SchemaNodeBuilder parentNode) {
         DataSchemaNodeBuilder node = null;
         SchemaNodeBuilder parent = parentNode;
         int i = 0;
@@ -464,7 +470,7 @@ public final class ParserUtils {
         return node;
     }
 
-    public static SchemaNodeBuilder findSchemaNodeInModule(List<QName> pathToNode, ModuleBuilder module) {
+    public static SchemaNodeBuilder findSchemaNodeInModule(final List<QName> pathToNode, final ModuleBuilder module) {
         List<QName> path = new ArrayList<>(pathToNode);
         QName first = path.remove(0);
 
@@ -506,7 +512,7 @@ public final class ParserUtils {
      *            path to augment target
      * @return true if augmentation process succeed, false otherwise
      */
-    public static boolean processAugmentation(AugmentationSchemaBuilder augment, ModuleBuilder firstNodeParent) {
+    public static boolean processAugmentation(final AugmentationSchemaBuilder augment, final ModuleBuilder firstNodeParent) {
         List<QName> path = augment.getTargetPath().getPath();
         Builder targetNode = findSchemaNodeInModule(path, firstNodeParent);
         if (targetNode == null) {
@@ -519,27 +525,31 @@ public final class ParserUtils {
         return true;
     }
 
-    public static IdentitySchemaNodeBuilder findBaseIdentity(Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder module, String baseString, int line) {
-        IdentitySchemaNodeBuilder result = null;
-        if (baseString.contains(":")) {
-            String[] splittedBase = baseString.split(":");
-            if (splittedBase.length > 2) {
+    public static IdentitySchemaNodeBuilder findBaseIdentity(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final ModuleBuilder module, final String baseString, final int line) {
+
+        // FIXME: optimize indexOf() away?
+        if (baseString.indexOf(':') != -1) {
+            final Iterator<String> it = COLON_SPLITTER.split(baseString).iterator();
+            final String prefix = it.next();
+            final String name = it.next();
+
+            if (it.hasNext()) {
                 throw new YangParseException(module.getName(), line, "Failed to parse identityref base: " + baseString);
             }
-            String prefix = splittedBase[0];
-            String name = splittedBase[1];
+
             ModuleBuilder dependentModule = findModuleFromBuilders(modules, module, prefix, line);
-            if (dependentModule != null) {
-                result = findIdentity(dependentModule.getAddedIdentities(), name);
+            if (dependentModule == null) {
+                return null;
             }
+
+            return findIdentity(dependentModule.getAddedIdentities(), name);
         } else {
-            result = findIdentity(module.getAddedIdentities(), baseString);
+            return findIdentity(module.getAddedIdentities(), baseString);
         }
-        return result;
     }
 
-    public static IdentitySchemaNodeBuilder findIdentity(Set<IdentitySchemaNodeBuilder> identities, String name) {
+    public static IdentitySchemaNodeBuilder findIdentity(final Set<IdentitySchemaNodeBuilder> identities, final String name) {
         for (IdentitySchemaNodeBuilder identity : identities) {
             if (identity.getQName().getLocalName().equals(name)) {
                 return identity;
@@ -554,7 +564,7 @@ public final class ParserUtils {
      * @param node
      * @return builder of module where this node is defined
      */
-    public static ModuleBuilder getParentModule(Builder node) {
+    public static ModuleBuilder getParentModule(final Builder node) {
         if (node instanceof ModuleBuilder) {
             return (ModuleBuilder) node;
         }
@@ -570,8 +580,8 @@ public final class ParserUtils {
         return parentModule;
     }
 
-    public static Set<DataSchemaNodeBuilder> wrapChildNodes(String moduleName, int line, Set<DataSchemaNode> nodes,
-            SchemaPath parentPath, URI ns, Date rev, String pref) {
+    public static Set<DataSchemaNodeBuilder> wrapChildNodes(final String moduleName, final int line, final Set<DataSchemaNode> nodes,
+            final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
         Set<DataSchemaNodeBuilder> result = new HashSet<>();
 
         for (DataSchemaNode node : nodes) {
@@ -582,11 +592,10 @@ public final class ParserUtils {
         return result;
     }
 
-    public static DataSchemaNodeBuilder wrapChildNode(String moduleName, int line, DataSchemaNode node,
-            SchemaPath parentPath, QName qname) {
-        List<QName> path = new ArrayList<>(parentPath.getPath());
-        path.add(qname);
-        SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+    public static DataSchemaNodeBuilder wrapChildNode(final String moduleName, final int line, final DataSchemaNode node,
+            final SchemaPath parentPath, final QName qname) {
+
+        final SchemaPath schemaPath = parentPath.createChild(qname);
 
         if (node instanceof AnyXmlSchemaNode) {
             return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
@@ -608,44 +617,57 @@ public final class ParserUtils {
         }
     }
 
-    public static Set<GroupingBuilder> wrapGroupings(String moduleName, int line, Set<GroupingDefinition> nodes,
-            SchemaPath parentPath, URI ns, Date rev, String pref) {
+    public static Set<GroupingBuilder> wrapGroupings(final String moduleName, final int line, final Set<GroupingDefinition> nodes,
+            final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
         Set<GroupingBuilder> result = new HashSet<>();
         for (GroupingDefinition node : nodes) {
             QName qname = new QName(ns, rev, pref, node.getQName().getLocalName());
-            List<QName> path = new ArrayList<>(parentPath.getPath());
-            path.add(qname);
-            SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+            SchemaPath schemaPath = parentPath.createChild(qname);
             result.add(new GroupingBuilderImpl(moduleName, line, qname, schemaPath, node));
         }
         return result;
     }
 
-    public static Set<TypeDefinitionBuilder> wrapTypedefs(String moduleName, int line, DataNodeContainer dataNode,
-            SchemaPath parentPath, URI ns, Date rev, String pref) {
+    public static Set<TypeDefinitionBuilder> wrapTypedefs(final String moduleName, final int line, final DataNodeContainer dataNode,
+            final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
         Set<TypeDefinition<?>> nodes = dataNode.getTypeDefinitions();
         Set<TypeDefinitionBuilder> result = new HashSet<>();
         for (TypeDefinition<?> node : nodes) {
             QName qname = new QName(ns, rev, pref, node.getQName().getLocalName());
             List<QName> path = new ArrayList<>(parentPath.getPath());
             path.add(qname);
-            SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+            SchemaPath schemaPath = SchemaPath.create(path, parentPath.isAbsolute());
             result.add(new TypeDefinitionBuilderImpl(moduleName, line, qname, schemaPath, ((ExtendedType) node)));
         }
         return result;
     }
 
-    public static List<UnknownSchemaNodeBuilder> wrapUnknownNodes(String moduleName, int line,
-            List<UnknownSchemaNode> nodes, SchemaPath parentPath, URI ns, Date rev, String pref) {
+    public static List<UnknownSchemaNodeBuilder> wrapUnknownNodes(final String moduleName, final int line,
+            final List<UnknownSchemaNode> nodes, final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
         List<UnknownSchemaNodeBuilder> result = new ArrayList<>();
         for (UnknownSchemaNode node : nodes) {
             QName qname = new QName(ns, rev, pref, node.getQName().getLocalName());
             List<QName> path = new ArrayList<>(parentPath.getPath());
             path.add(qname);
-            SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+            SchemaPath schemaPath = SchemaPath.create(path, parentPath.isAbsolute());
             result.add(new UnknownSchemaNodeBuilder(moduleName, line, qname, schemaPath, node));
         }
         return result;
     }
 
+    private static final class ByteSourceImpl extends ByteSource {
+        private final String toString;
+        private final ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+        private ByteSourceImpl(InputStream input) throws IOException {
+            toString = input.toString();
+            IOUtils.copy(input, output);
+        }
+
+        @Override
+        public InputStream openStream() throws IOException {
+            return new NamedByteArrayInputStream(output.toByteArray(), toString);
+        }
+    }
+
 }
index a6619dbbcc09881cd9a4f283b8268c9cdad6fb04..062fc2f5a26df4f1a7a0caef8c53077e2cdc8baf 100644 (file)
@@ -7,9 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.validator;
 
-import java.text.DateFormat;
 import java.text.ParseException;
-import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.List;
 import java.util.Set;
@@ -19,6 +17,7 @@ import java.util.regex.Pattern;
 import org.antlr.v4.runtime.ParserRuleContext;
 import org.antlr.v4.runtime.tree.ParseTree;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yang_version_stmtContext;
+import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
 
 import com.google.common.collect.Sets;
@@ -36,8 +35,8 @@ final class BasicValidations {
     private BasicValidations() {
     }
 
-    static void checkNotPresentBoth(ParseTree parent, Class<? extends ParseTree> childType1,
-            Class<? extends ParseTree> childType2) {
+    static void checkNotPresentBoth(final ParseTree parent, final Class<? extends ParseTree> childType1,
+            final Class<? extends ParseTree> childType2) {
         if (BasicValidations.checkPresentChildOfTypeSafe(parent, childType1, true)
                 && BasicValidations.checkPresentChildOfTypeSafe(parent, childType2, false)) {
             ValidationUtil.ex(ValidationUtil.f("(In (sub)module:%s) Both %s and %s statement present in %s:%s",
@@ -47,7 +46,7 @@ final class BasicValidations {
         }
     }
 
-    static void checkOnlyPermittedValues(ParseTree ctx, Set<String> permittedValues) {
+    static void checkOnlyPermittedValues(final ParseTree ctx, final Set<String> permittedValues) {
         String mandatory = ValidationUtil.getName(ctx);
         String rootParentName = ValidationUtil.getRootParentName(ctx);
 
@@ -59,7 +58,7 @@ final class BasicValidations {
         }
     }
 
-    static void checkUniquenessInNamespace(ParseTree stmt, Set<String> uniques) {
+    static void checkUniquenessInNamespace(final ParseTree stmt, final Set<String> uniques) {
         String name = ValidationUtil.getName(stmt);
         String rootParentName = ValidationUtil.getRootParentName(stmt);
 
@@ -74,13 +73,13 @@ final class BasicValidations {
      * Check if only one module or submodule is present in session(one yang
      * file)
      */
-    static void checkOnlyOneModulePresent(String moduleName, String globalId) {
+    static void checkOnlyOneModulePresent(final String moduleName, final String globalId) {
         if (globalId != null) {
             ValidationUtil.ex(ValidationUtil.f("Multiple (sub)modules per file"));
         }
     }
 
-    static void checkPresentYangVersion(ParseTree ctx, String moduleName) {
+    static void checkPresentYangVersion(final ParseTree ctx, final String moduleName) {
         if (!checkPresentChildOfTypeSafe(ctx, Yang_version_stmtContext.class, true)) {
             ValidationUtil.ex(ValidationUtil.f(
                     "Yang version statement not present in module:%s, Validating as yang version:%s", moduleName,
@@ -88,25 +87,25 @@ final class BasicValidations {
         }
     }
 
-    static void checkDateFormat(ParseTree stmt, DateFormat format) {
+    static void checkDateFormat(final ParseTree stmt) {
         try {
-            format.parse(ValidationUtil.getName(stmt));
+            SimpleDateFormatUtil.getRevisionFormat().parse(ValidationUtil.getName(stmt));
         } catch (ParseException e) {
             String exceptionMessage = ValidationUtil.f(
                     "(In (sub)module:%s) %s:%s, invalid date format expected date format is:%s",
                     ValidationUtil.getRootParentName(stmt), ValidationUtil.getSimpleStatementName(stmt.getClass()),
-                    ValidationUtil.getName(stmt), new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
+                    ValidationUtil.getName(stmt), SimpleDateFormatUtil.getRevisionFormat().format(new Date()));
             ValidationUtil.ex(exceptionMessage);
         }
     }
 
     private static Pattern identifierPattern = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_.-]*");
 
-    static void checkIdentifier(ParseTree statement) {
+    static void checkIdentifier(final ParseTree statement) {
         checkIdentifierInternal(statement, ValidationUtil.getName(statement));
     }
 
-    static void checkIdentifierInternal(ParseTree statement, String name) {
+    static void checkIdentifierInternal(final ParseTree statement, final String name) {
         if (!identifierPattern.matcher(name).matches()) {
 
             String message = ValidationUtil.f("%s statement identifier:%s is not in required format:%s",
@@ -124,11 +123,11 @@ final class BasicValidations {
 
     private static Pattern prefixedIdentifierPattern = Pattern.compile("(.+):(.+)");
 
-    static void checkPrefixedIdentifier(ParseTree statement) {
+    static void checkPrefixedIdentifier(final ParseTree statement) {
         checkPrefixedIdentifierInternal(statement, ValidationUtil.getName(statement));
     }
 
-    private static void checkPrefixedIdentifierInternal(ParseTree statement, String id) {
+    private static void checkPrefixedIdentifierInternal(final ParseTree statement, final String id) {
         Matcher matcher = prefixedIdentifierPattern.matcher(id);
 
         if (matcher.matches()) {
@@ -146,7 +145,7 @@ final class BasicValidations {
         }
     }
 
-    static void checkSchemaNodeIdentifier(ParseTree statement) {
+    static void checkSchemaNodeIdentifier(final ParseTree statement) {
         String id = ValidationUtil.getName(statement);
 
         try {
@@ -166,8 +165,8 @@ final class BasicValidations {
         String getMessage();
     }
 
-    static void checkPresentChildOfTypeInternal(ParseTree parent, Set<Class<? extends ParseTree>> expectedChildType,
-            MessageProvider message, boolean atMostOne) {
+    static void checkPresentChildOfTypeInternal(final ParseTree parent, final Set<Class<? extends ParseTree>> expectedChildType,
+            final MessageProvider message, final boolean atMostOne) {
         if (!checkPresentChildOfTypeSafe(parent, expectedChildType, atMostOne)) {
             String str = atMostOne ? "(Expected exactly one statement) " + message.getMessage() : message.getMessage();
             ValidationUtil.ex(str);
@@ -175,7 +174,7 @@ final class BasicValidations {
     }
 
     static void checkPresentChildOfType(final ParseTree parent, final Class<? extends ParseTree> expectedChildType,
-            boolean atMostOne) {
+            final boolean atMostOne) {
 
         // Construct message in checkPresentChildOfTypeInternal only if
         // validaiton fails, not in advance
@@ -208,10 +207,10 @@ final class BasicValidations {
      */
     private static class MessageProviderForSetOfChildTypes implements MessageProvider {
 
-        private Set<Class<? extends ParseTree>> expectedChildTypes;
-        private ParseTree parent;
+        private final Set<Class<? extends ParseTree>> expectedChildTypes;
+        private final ParseTree parent;
 
-        public MessageProviderForSetOfChildTypes(Set<Class<? extends ParseTree>> expectedChildTypes, ParseTree parent) {
+        public MessageProviderForSetOfChildTypes(final Set<Class<? extends ParseTree>> expectedChildTypes, final ParseTree parent) {
             this.expectedChildTypes = expectedChildTypes;
             this.parent = parent;
         }
@@ -235,7 +234,7 @@ final class BasicValidations {
     };
 
     static void checkPresentChildOfTypes(final ParseTree parent,
-            final Set<Class<? extends ParseTree>> expectedChildTypes, boolean atMostOne) {
+            final Set<Class<? extends ParseTree>> expectedChildTypes, final boolean atMostOne) {
 
         // Construct message in checkPresentChildOfTypeInternal only if
         // validaiton fails, not in advance
@@ -243,23 +242,23 @@ final class BasicValidations {
         checkPresentChildOfTypeInternal(parent, expectedChildTypes, message, atMostOne);
     }
 
-    static boolean checkPresentChildOfTypeSafe(ParseTree parent, Set<Class<? extends ParseTree>> expectedChildType,
-            boolean atMostOne) {
+    static boolean checkPresentChildOfTypeSafe(final ParseTree parent, final Set<Class<? extends ParseTree>> expectedChildType,
+            final boolean atMostOne) {
 
         int foundChildrenOfType = ValidationUtil.countPresentChildrenOfType(parent, expectedChildType);
 
         return atMostOne ? foundChildrenOfType == 1 ? true : false : foundChildrenOfType != 0 ? true : false;
     }
 
-    static boolean checkPresentChildOfTypeSafe(ParseTree parent, Class<? extends ParseTree> expectedChildType,
-            boolean atMostOne) {
+    static boolean checkPresentChildOfTypeSafe(final ParseTree parent, final Class<? extends ParseTree> expectedChildType,
+            final boolean atMostOne) {
 
         int foundChildrenOfType = ValidationUtil.countPresentChildrenOfType(parent, expectedChildType);
 
         return atMostOne ? foundChildrenOfType == 1 ? true : false : foundChildrenOfType != 0 ? true : false;
     }
 
-    static List<String> getAndCheckUniqueKeys(ParseTree ctx) {
+    static List<String> getAndCheckUniqueKeys(final ParseTree ctx) {
         String key = ValidationUtil.getName(ctx);
         ParseTree parent = ctx.getParent();
         String rootParentName = ValidationUtil.getRootParentName(ctx);
index 967769a619d13102e298954a5b86cfe535b3246f..5de58554294fc32a127c8f13f2f0e567ac771c05 100644 (file)
@@ -9,12 +9,11 @@ package org.opendaylight.yangtools.yang.validator;
 
 import java.net.URI;
 import java.net.URISyntaxException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
+import java.util.HashSet;
 import java.util.Set;
 
 import org.antlr.v4.runtime.tree.ParseTree;
-import org.opendaylight.yangtools.antlrv4.code.gen.*;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Anyxml_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Augment_stmtContext;
@@ -58,6 +57,7 @@ import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Typedef_stmtContex
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Unique_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Uses_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParserBaseListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -70,21 +70,12 @@ import com.google.common.collect.Sets;
  */
 final class YangModelBasicValidationListener extends YangParserBaseListener {
     private static final Logger LOGGER = LoggerFactory.getLogger(YangModelBasicValidationListener.class);
-    private final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
-
-    private final Set<String> uniquePrefixes;
-    private final Set<String> uniqueImports;
-    private final Set<String> uniqueIncludes;
+    private final Set<String> uniquePrefixes = new HashSet<>();
+    private final Set<String> uniqueImports = new HashSet<>();
+    private final Set<String> uniqueIncludes = new HashSet<>();
 
     private String globalModuleId;
 
-    YangModelBasicValidationListener() {
-        super();
-        uniquePrefixes = Sets.newHashSet();
-        uniqueImports = Sets.newHashSet();
-        uniqueIncludes = Sets.newHashSet();
-    }
-
     /**
      * Constraints:
      * <ol>
@@ -95,7 +86,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterModule_stmt(Module_stmtContext ctx) {
+    public void enterModule_stmt(final Module_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -116,7 +107,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterSubmodule_stmt(Submodule_stmtContext ctx) {
+    public void enterSubmodule_stmt(final Submodule_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -135,7 +126,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterSubmodule_header_stmts(Submodule_header_stmtsContext ctx) {
+    public void enterSubmodule_header_stmts(final Submodule_header_stmtsContext ctx) {
         BasicValidations.checkPresentChildOfType(ctx, Belongs_to_stmtContext.class, true);
 
         // check Yang version present, if not log
@@ -154,7 +145,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterModule_header_stmts(Module_header_stmtsContext ctx) {
+    public void enterModule_header_stmts(final Module_header_stmtsContext ctx) {
         String moduleName = ValidationUtil.getRootParentName(ctx);
 
         BasicValidations.checkPresentChildOfType(ctx, Namespace_stmtContext.class, true);
@@ -175,8 +166,8 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterRevision_stmt(Revision_stmtContext ctx) {
-        BasicValidations.checkDateFormat(ctx, SIMPLE_DATE_FORMAT);
+    public void enterRevision_stmt(final Revision_stmtContext ctx) {
+        BasicValidations.checkDateFormat(ctx);
 
     }
 
@@ -188,7 +179,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterBelongs_to_stmt(Belongs_to_stmtContext ctx) {
+    public void enterBelongs_to_stmt(final Belongs_to_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
 
         BasicValidations.checkPresentChildOfType(ctx, Prefix_stmtContext.class, true);
@@ -201,7 +192,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterNamespace_stmt(Namespace_stmtContext ctx) {
+    public void enterNamespace_stmt(final Namespace_stmtContext ctx) {
         String namespaceName = ValidationUtil.getName(ctx);
         String rootParentName = ValidationUtil.getRootParentName(ctx);
 
@@ -223,7 +214,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterImport_stmt(Import_stmtContext ctx) {
+    public void enterImport_stmt(final Import_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -240,8 +231,8 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterRevision_date_stmt(Revision_date_stmtContext ctx) {
-        BasicValidations.checkDateFormat(ctx, SIMPLE_DATE_FORMAT);
+    public void enterRevision_date_stmt(final Revision_date_stmtContext ctx) {
+        BasicValidations.checkDateFormat(ctx);
     }
 
     /**
@@ -253,7 +244,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterInclude_stmt(Include_stmtContext ctx) {
+    public void enterInclude_stmt(final Include_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -267,7 +258,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterYang_version_stmt(YangParser.Yang_version_stmtContext ctx) {
+    public void enterYang_version_stmt(final YangParser.Yang_version_stmtContext ctx) {
         String version = ValidationUtil.getName(ctx);
         String rootParentName = ValidationUtil.getRootParentName(ctx);
         if (!version.equals(BasicValidations.SUPPORTED_YANG_VERSION)) {
@@ -285,7 +276,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterPrefix_stmt(Prefix_stmtContext ctx) {
+    public void enterPrefix_stmt(final Prefix_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -300,7 +291,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterTypedef_stmt(Typedef_stmtContext ctx) {
+    public void enterTypedef_stmt(final Typedef_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -314,7 +305,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterType_stmt(Type_stmtContext ctx) {
+    public void enterType_stmt(final Type_stmtContext ctx) {
         BasicValidations.checkPrefixedIdentifier(ctx);
     }
 
@@ -325,7 +316,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterContainer_stmt(Container_stmtContext ctx) {
+    public void enterContainer_stmt(final Container_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -338,7 +329,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterLeaf_stmt(Leaf_stmtContext ctx) {
+    public void enterLeaf_stmt(final Leaf_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
 
         BasicValidations.checkPresentChildOfType(ctx, Type_stmtContext.class, true);
@@ -354,7 +345,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterLeaf_list_stmt(Leaf_list_stmtContext ctx) {
+    public void enterLeaf_list_stmt(final Leaf_list_stmtContext ctx) {
 
         BasicValidations.checkIdentifier(ctx);
 
@@ -370,7 +361,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterOrdered_by_arg(Ordered_by_argContext ctx) {
+    public void enterOrdered_by_arg(final Ordered_by_argContext ctx) {
         BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_ORDER_BY_ARGS);
     }
 
@@ -381,7 +372,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterList_stmt(List_stmtContext ctx) {
+    public void enterList_stmt(final List_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
         // TODO check: "if config==true then key must be present" could be
         // performed
@@ -394,7 +385,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterKey_stmt(Key_stmtContext ctx) {
+    public void enterKey_stmt(final Key_stmtContext ctx) {
         BasicValidations.getAndCheckUniqueKeys(ctx);
     }
 
@@ -405,7 +396,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterUnique_stmt(Unique_stmtContext ctx) {
+    public void enterUnique_stmt(final Unique_stmtContext ctx) {
         BasicValidations.getAndCheckUniqueKeys(ctx);
     }
 
@@ -417,7 +408,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterChoice_stmt(Choice_stmtContext ctx) {
+    public void enterChoice_stmt(final Choice_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
 
         BasicValidations.checkNotPresentBoth(ctx, Mandatory_stmtContext.class, Default_stmtContext.class);
@@ -431,7 +422,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterCase_stmt(Case_stmtContext ctx) {
+    public void enterCase_stmt(final Case_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -444,7 +435,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterMandatory_arg(Mandatory_argContext ctx) {
+    public void enterMandatory_arg(final Mandatory_argContext ctx) {
         BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_BOOLEAN_ARGS);
     }
 
@@ -455,7 +446,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterAnyxml_stmt(Anyxml_stmtContext ctx) {
+    public void enterAnyxml_stmt(final Anyxml_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -466,7 +457,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterGrouping_stmt(Grouping_stmtContext ctx) {
+    public void enterGrouping_stmt(final Grouping_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -477,7 +468,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterUses_stmt(Uses_stmtContext ctx) {
+    public void enterUses_stmt(final Uses_stmtContext ctx) {
         BasicValidations.checkPrefixedIdentifier(ctx);
     }
 
@@ -488,7 +479,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterRefine_stmt(Refine_stmtContext ctx) {
+    public void enterRefine_stmt(final Refine_stmtContext ctx) {
         BasicValidations.checkSchemaNodeIdentifier(ctx);
     }
 
@@ -499,7 +490,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterRpc_stmt(Rpc_stmtContext ctx) {
+    public void enterRpc_stmt(final Rpc_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -510,7 +501,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterNotification_stmt(Notification_stmtContext ctx) {
+    public void enterNotification_stmt(final Notification_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -521,7 +512,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterAugment_stmt(Augment_stmtContext ctx) {
+    public void enterAugment_stmt(final Augment_stmtContext ctx) {
         BasicValidations.checkSchemaNodeIdentifier(ctx);
     }
 
@@ -532,7 +523,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterIdentity_stmt(Identity_stmtContext ctx) {
+    public void enterIdentity_stmt(final Identity_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -543,7 +534,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterBase_stmt(Base_stmtContext ctx) {
+    public void enterBase_stmt(final Base_stmtContext ctx) {
         BasicValidations.checkPrefixedIdentifier(ctx);
 
     }
@@ -555,7 +546,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterYin_element_arg(Yin_element_argContext ctx) {
+    public void enterYin_element_arg(final Yin_element_argContext ctx) {
         BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_BOOLEAN_ARGS);
     }
 
@@ -566,7 +557,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterExtension_stmt(Extension_stmtContext ctx) {
+    public void enterExtension_stmt(final Extension_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -577,7 +568,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterArgument_stmt(Argument_stmtContext ctx) {
+    public void enterArgument_stmt(final Argument_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
     }
 
@@ -588,7 +579,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterFeature_stmt(Feature_stmtContext ctx) {
+    public void enterFeature_stmt(final Feature_stmtContext ctx) {
         BasicValidations.checkIdentifier(ctx);
 
     }
@@ -600,7 +591,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterIf_feature_stmt(If_feature_stmtContext ctx) {
+    public void enterIf_feature_stmt(final If_feature_stmtContext ctx) {
         BasicValidations.checkPrefixedIdentifier(ctx);
     }
 
@@ -612,7 +603,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterDeviation_stmt(Deviation_stmtContext ctx) {
+    public void enterDeviation_stmt(final Deviation_stmtContext ctx) {
         BasicValidations.checkSchemaNodeIdentifier(ctx);
 
         Set<Class<? extends ParseTree>> types = Sets.newHashSet();
@@ -628,7 +619,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterConfig_arg(Config_argContext ctx) {
+    public void enterConfig_arg(final Config_argContext ctx) {
         BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_BOOLEAN_ARGS);
     }
 
@@ -641,7 +632,7 @@ final class YangModelBasicValidationListener extends YangParserBaseListener {
      * </ol>
      */
     @Override
-    public void enterStatus_arg(Status_argContext ctx) {
+    public void enterStatus_arg(final Status_argContext ctx) {
         BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_STATUS_ARGS);
     }
 
index 7d8f4ed66d2de2f06481c7c20508a868994190c7..6c1df4ac09f8dcd583f1d568fe8939917feff2c5 100644 (file)
@@ -7,7 +7,10 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
 import java.io.FileNotFoundException;
 import java.net.URI;
@@ -81,7 +84,7 @@ public class AugmentTest {
         AugmentationSchema augment = augmentations.iterator().next();
         assertNotNull(augment);
 
-        expectedSchemaPath = new SchemaPath(qnames, true);
+        expectedSchemaPath = SchemaPath.create(qnames, true);
         assertEquals(expectedSchemaPath, augment.getTargetPath());
 
         Set<DataSchemaNode> augmentChildren = augment.getChildNodes();
@@ -104,20 +107,20 @@ public class AugmentTest {
         QName qname = new QName(fooNS, fooRev, foo, "ds0ChannelNumber");
         qnames.add(qname);
         assertEquals(qname, ds0ChannelNumber.getQName());
-        expectedSchemaPath = new SchemaPath(qnames, true);
+        expectedSchemaPath = SchemaPath.create(qnames, true);
         assertEquals(expectedSchemaPath, ds0ChannelNumber.getPath());
         assertFalse(ds0ChannelNumber.isAugmenting());
         // type of leaf ds0ChannelNumber
         QName typeQName = BaseTypes.constructQName("string");
         List<QName> typePath = Collections.singletonList(typeQName);
-        expectedSchemaPath = new SchemaPath(typePath, true);
+        expectedSchemaPath = SchemaPath.create(typePath, true);
         assertEquals(expectedSchemaPath, ds0ChannelNumber.getType().getPath());
 
         // leaf interface-id
         qname = new QName(fooNS, fooRev, foo, "interface-id");
         assertEquals(qname, interfaceId.getQName());
         qnames.set(3, qname);
-        expectedSchemaPath = new SchemaPath(qnames, true);
+        expectedSchemaPath = SchemaPath.create(qnames, true);
         assertEquals(expectedSchemaPath, interfaceId.getPath());
         assertFalse(interfaceId.isAugmenting());
 
@@ -125,7 +128,7 @@ public class AugmentTest {
         qname = new QName(fooNS, fooRev, foo, "schemas");
         assertEquals(qname, schemas.getQName());
         qnames.set(3, qname);
-        expectedSchemaPath = new SchemaPath(qnames, true);
+        expectedSchemaPath = SchemaPath.create(qnames, true);
         assertEquals(expectedSchemaPath, schemas.getPath());
         assertFalse(schemas.isAugmenting());
 
@@ -133,7 +136,7 @@ public class AugmentTest {
         qname = new QName(fooNS, fooRev, foo, "odl");
         assertEquals(qname, odl.getQName());
         qnames.set(3, qname);
-        expectedSchemaPath = new SchemaPath(qnames, true);
+        expectedSchemaPath = SchemaPath.create(qnames, true);
         assertEquals(expectedSchemaPath, odl.getPath());
         assertFalse(odl.isAugmenting());
 
@@ -188,7 +191,7 @@ public class AugmentTest {
         ContainerSchemaNode augmentHolder = (ContainerSchemaNode) ifEntry.getDataChildByName("augment-holder");
         TestUtils.checkIsAugmenting(augmentHolder, true);
         assertEquals(q2, augmentHolder.getQName());
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, augmentHolder.getPath());
 
         // foo.yang
@@ -207,28 +210,28 @@ public class AugmentTest {
         QName qname = new QName(fooNS, fooRev, foo, "ds0ChannelNumber");
         assertEquals(qname, ds0ChannelNumber.getQName());
         qnames.add(qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, ds0ChannelNumber.getPath());
 
         // leaf interface-id
         qname = new QName(fooNS, fooRev, foo, "interface-id");
         assertEquals(qname, interfaceId.getQName());
         qnames.set(3, qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, interfaceId.getPath());
 
         // container schemas
         qname = new QName(fooNS, fooRev, foo, "schemas");
         assertEquals(qname, schemas.getQName());
         qnames.set(3, qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, schemas.getPath());
 
         // choice odl
         qname = new QName(fooNS, fooRev, foo, "odl");
         assertEquals(qname, odl.getQName());
         qnames.set(3, qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, odl.getPath());
     }
 
@@ -281,7 +284,7 @@ public class AugmentTest {
         QName qname = new QName(fooNS, fooRev, foo, "id");
         assertEquals(qname, id.getQName());
         qnames.add(qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, id.getPath());
         Set<DataSchemaNode> idChildren = id.getChildNodes();
         assertEquals(1, idChildren.size());
@@ -290,7 +293,7 @@ public class AugmentTest {
         qname = new QName(fooNS, fooRev, foo, "node1");
         assertEquals(qname, node1.getQName());
         qnames.set(4, qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, node1.getPath());
         Set<DataSchemaNode> node1Children = node1.getChildNodes();
         assertTrue(node1Children.isEmpty());
@@ -299,7 +302,7 @@ public class AugmentTest {
         qname = new QName(fooNS, fooRev, foo, "node2");
         assertEquals(qname, node2.getQName());
         qnames.set(4, qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, node2.getPath());
         Set<DataSchemaNode> node2Children = node2.getChildNodes();
         assertTrue(node2Children.isEmpty());
@@ -308,7 +311,7 @@ public class AugmentTest {
         qname = new QName(fooNS, fooRev, foo, "node3");
         assertEquals(qname, node3.getQName());
         qnames.set(4, qname);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, node3.getPath());
         Set<DataSchemaNode> node3Children = node3.getChildNodes();
         assertEquals(1, node3Children.size());
@@ -325,7 +328,7 @@ public class AugmentTest {
         qnames.add(new QName(fooNS, fooRev, foo, "id"));
         LeafSchemaNode caseIdChild = (LeafSchemaNode) idChildren.iterator().next();
         assertNotNull(caseIdChild);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, caseIdChild.getPath());
 
         // case node3 child
@@ -333,7 +336,7 @@ public class AugmentTest {
         qnames.set(5, new QName(fooNS, fooRev, foo, "node3"));
         ContainerSchemaNode caseNode3Child = (ContainerSchemaNode) node3Children.iterator().next();
         assertNotNull(caseNode3Child);
-        expectedPath = new SchemaPath(qnames, true);
+        expectedPath = SchemaPath.create(qnames, true);
         assertEquals(expectedPath, caseNode3Child.getPath());
     }
 
@@ -398,7 +401,7 @@ public class AugmentTest {
         // case attach
         qnames[3] = new QName(NS_FOO, revision, "f", "attach");
         assertEquals(qnames[3], attach.getQName());
-        expectedPath = new SchemaPath(Arrays.asList(qnames), true);
+        expectedPath = SchemaPath.create(Arrays.asList(qnames), true);
         assertEquals(expectedPath, attach.getPath());
         Set<DataSchemaNode> attachChildren = attach.getChildNodes();
         assertEquals(1, attachChildren.size());
@@ -406,7 +409,7 @@ public class AugmentTest {
         // case create
         qnames[3] = new QName(NS_FOO, revision, "f", "create");
         assertEquals(qnames[3], create.getQName());
-        expectedPath = new SchemaPath(Arrays.asList(qnames), true);
+        expectedPath = SchemaPath.create(Arrays.asList(qnames), true);
         assertEquals(expectedPath, create.getPath());
         Set<DataSchemaNode> createChildren = create.getChildNodes();
         assertEquals(1, createChildren.size());
@@ -414,7 +417,7 @@ public class AugmentTest {
         // case attach
         qnames[3] = new QName(NS_FOO, revision, "f", "destroy");
         assertEquals(qnames[3], destroy.getQName());
-        expectedPath = new SchemaPath(Arrays.asList(qnames), true);
+        expectedPath = SchemaPath.create(Arrays.asList(qnames), true);
         assertEquals(expectedPath, destroy.getPath());
         Set<DataSchemaNode> destroyChildren = destroy.getChildNodes();
         assertEquals(1, destroyChildren.size());
index 2f23d12e377178f4bdf5a7f7fcdf2d36ecf7412f..18a73d55e7243f0a96d36e1eaf42b8480bb1731e 100644 (file)
@@ -9,13 +9,32 @@ package org.opendaylight.yangtools.yang.parser.impl;
 
 import static org.junit.Assert.assertEquals;
 
-import java.io.*;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
 import java.net.URI;
-import java.text.*;
-import java.util.*;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.ModuleImport;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
 
 final class TestUtils {
@@ -24,7 +43,7 @@ final class TestUtils {
     }
 
 
-    public static Set<Module> loadModules(URI resourceDirectory) throws FileNotFoundException {
+    public static Set<Module> loadModules(final URI resourceDirectory) throws FileNotFoundException {
         final YangModelParser parser = new YangParserImpl();
         final File testDir = new File(resourceDirectory);
         final String[] fileList = testDir.list();
@@ -38,7 +57,7 @@ final class TestUtils {
         return parser.parseYangModels(testFiles);
     }
 
-    public static Set<Module> loadModules(List<InputStream> input) throws IOException {
+    public static Set<Module> loadModules(final List<InputStream> input) throws IOException {
         final YangModelParser parser = new YangParserImpl();
         final Set<Module> modules = new HashSet<>(parser.parseYangModelsFromStreams(input));
         for (InputStream stream : input) {
@@ -83,7 +102,7 @@ final class TestUtils {
         return modules;
     }
 
-    public static Module findModule(Set<Module> modules, String moduleName) {
+    public static Module findModule(final Set<Module> modules, final String moduleName) {
         Module result = null;
         for (Module module : modules) {
             if (module.getName().equals(moduleName)) {
@@ -94,7 +113,7 @@ final class TestUtils {
         return result;
     }
 
-    public static ModuleImport findImport(Set<ModuleImport> imports, String prefix) {
+    public static ModuleImport findImport(final Set<ModuleImport> imports, final String prefix) {
         ModuleImport result = null;
         for (ModuleImport moduleImport : imports) {
             if (moduleImport.getPrefix().equals(prefix)) {
@@ -105,7 +124,7 @@ final class TestUtils {
         return result;
     }
 
-    public static TypeDefinition<?> findTypedef(Set<TypeDefinition<?>> typedefs, String name) {
+    public static TypeDefinition<?> findTypedef(final Set<TypeDefinition<?>> typedefs, final String name) {
         TypeDefinition<?> result = null;
         for (TypeDefinition<?> td : typedefs) {
             if (td.getQName().getLocalName().equals(name)) {
@@ -116,15 +135,15 @@ final class TestUtils {
         return result;
     }
 
-    public static SchemaPath createPath(boolean absolute, URI namespace, Date revision, String prefix, String... names) {
+    public static SchemaPath createPath(final boolean absolute, final URI namespace, final Date revision, final String prefix, final String... names) {
         List<QName> path = new ArrayList<>();
         for (String name : names) {
             path.add(new QName(namespace, revision, prefix, name));
         }
-        return new SchemaPath(path, absolute);
+        return SchemaPath.create(path, absolute);
     }
 
-    public static Date createDate(String date) {
+    public static Date createDate(final String date) {
         Date result;
         final DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
         try {
@@ -144,7 +163,7 @@ final class TestUtils {
      * @param expected
      *            expected value
      */
-    public static void checkIsAugmenting(DataSchemaNode node, boolean expected) {
+    public static void checkIsAugmenting(final DataSchemaNode node, final boolean expected) {
         assertEquals(expected, node.isAugmenting());
         if (node instanceof DataNodeContainer) {
             for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
@@ -166,7 +185,7 @@ final class TestUtils {
      * @param expected
      *            expected value
      */
-    public static void checkIsAddedByUses(DataSchemaNode node, boolean expected) {
+    public static void checkIsAddedByUses(final DataSchemaNode node, final boolean expected) {
         assertEquals(expected, node.isAddedByUses());
         if (node instanceof DataNodeContainer) {
             for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
@@ -179,7 +198,7 @@ final class TestUtils {
         }
     }
 
-    public static void checkIsAddedByUses(GroupingDefinition node, boolean expected) {
+    public static void checkIsAddedByUses(final GroupingDefinition node, final boolean expected) {
         assertEquals(expected, node.isAddedByUses());
         if (node instanceof DataNodeContainer) {
             for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
@@ -192,7 +211,7 @@ final class TestUtils {
         }
     }
 
-    public static List<Module> findModules(Set<Module> modules, String moduleName) {
+    public static List<Module> findModules(final Set<Module> modules, final String moduleName) {
         List<Module> result = new ArrayList<>();
         for (Module module : modules) {
             if (module.getName().equals(moduleName)) {
index c713f759f1c9e79089067acd45e2a716ea2538ab..c6a010297111159efff9d12f789e9071335fb952 100644 (file)
@@ -7,7 +7,10 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
 import java.io.FileNotFoundException;
 import java.net.URI;
@@ -126,7 +129,7 @@ public class UsesAugmentTest {
         assertNotNull(pcreq);
         QName expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "pcreq");
         path.offer(expectedQName);
-        SchemaPath expectedPath = new SchemaPath(path, true);
+        SchemaPath expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, pcreq.getPath());
         Set<DataSchemaNode> childNodes = pcreq.getChildNodes();
         assertEquals(4, childNodes.size());
@@ -135,11 +138,11 @@ public class UsesAugmentTest {
         assertNotNull(version);
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "version");
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, version.getPath());
         expectedQName = new QName(GD_NS, GD_REV, GD_PREF, "protocol-version");
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(Lists.newArrayList(expectedQName), true);
+        expectedPath = SchemaPath.create(Lists.newArrayList(expectedQName), true);
         assertEquals(expectedPath, version.getType().getPath());
         assertEquals(Uint8.getInstance(), version.getType().getBaseType());
         assertTrue(version.isAddedByUses());
@@ -151,11 +154,11 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, type.getPath());
         expectedQName = new QName(GD_NS, GD_REV, GD_PREF, "int-ext");
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(Lists.newArrayList(expectedQName), true);
+        expectedPath = SchemaPath.create(Lists.newArrayList(expectedQName), true);
         assertEquals(expectedPath, type.getType().getPath());
         UnionType union = (UnionType)type.getType().getBaseType();
         assertEquals(BaseTypes.schemaPath(BaseTypes.constructQName("union")), union.getPath());
@@ -168,7 +171,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, requests.getPath());
         assertFalse(requests.isAddedByUses());
         childNodes = requests.getChildNodes();
@@ -178,7 +181,7 @@ public class UsesAugmentTest {
         assertNotNull(rp);
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "rp");
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, rp.getPath());
         assertFalse(rp.isAddedByUses());
         childNodes = rp.getChildNodes();
@@ -189,7 +192,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
         assertEquals(expectedQName, processingRule.getQName());
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -200,7 +203,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -211,11 +214,11 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, priority.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, priority.getPath());
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "uint8");
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         // TODO
         //assertEquals(expectedPath, priority.getType().getPath());
         assertEquals(Uint8.getInstance(), priority.getType().getBaseType());
@@ -228,7 +231,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, box.getPath());
         assertTrue(box.isAddedByUses());
         // * |-- |-- |-- |-- container order
@@ -237,7 +240,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "order");
         assertEquals(expectedQName, order.getQName());
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, order.getPath());
         assertTrue(order.isAddedByUses());
         assertTrue(order.isAugmenting());
@@ -248,7 +251,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "delete");
         assertEquals(expectedQName, delete.getQName());
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, delete.getPath());
         assertEquals(Uint32.getInstance(), delete.getType());
         assertTrue(delete.isAddedByUses());
@@ -259,7 +262,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, setup.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, setup.getPath());
         assertEquals(Uint32.getInstance(), setup.getType());
         assertTrue(setup.isAddedByUses());
@@ -273,7 +276,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath = new SchemaPath(path, true);
+        expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, pke.getPath());
         assertFalse(pke.isAddedByUses());
         // * |-- |-- |-- path-key
@@ -282,7 +285,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "path-key");
         assertEquals(expectedQName, pathKey.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, pathKey.getPath());
         assertFalse(pathKey.isAddedByUses());
         assertEquals(3, pathKey.getChildNodes().size());
@@ -292,7 +295,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
         assertEquals(expectedQName, processingRule.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -303,7 +306,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -314,7 +317,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, pathKeys.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, pathKeys.getPath());
         assertTrue(pathKeys.isAddedByUses());
         childNodes = pathKeys.getChildNodes();
@@ -325,7 +328,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "version");
         assertEquals(expectedQName, version.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, version.getPath());
         assertTrue(version.getType() instanceof ExtendedType);
         assertEquals(Uint8.getInstance(), version.getType().getBaseType());
@@ -338,7 +341,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, type.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, type.getPath());
         assertTrue(type.getType() instanceof ExtendedType);
         assertTrue(type.isAddedByUses());
@@ -353,7 +356,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, sc.getPath());
         assertFalse(sc.isAddedByUses());
         // * |-- |-- |-- container p2p
@@ -362,7 +365,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "p2p");
         assertEquals(expectedQName, p2p.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, p2p.getPath());
         assertFalse(p2p.isAddedByUses());
         // * |-- |-- |-- |-- container endpoints
@@ -371,7 +374,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "endpoints");
         assertEquals(expectedQName, endpoints.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, endpoints.getPath());
         assertFalse(endpoints.isAddedByUses());
         // * |-- |-- |-- |-- |-- leaf processing-rule
@@ -380,7 +383,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
         assertEquals(expectedQName, processingRule.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -391,7 +394,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -402,7 +405,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, box.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, box.getPath());
         assertTrue(box.isAddedByUses());
         // * |-- |-- |-- |-- |-- choice address-family
@@ -412,7 +415,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, af.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, af.getPath());
         assertTrue(af.isAddedByUses());
         // * |-- |-- |-- |-- container reported-route
@@ -423,7 +426,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, reportedRoute.getPath());
         assertFalse(reportedRoute.isAddedByUses());
         // * |-- |-- |-- |-- |-- leaf processing-rule
@@ -432,7 +435,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
         assertEquals(expectedQName, processingRule.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -443,7 +446,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -454,7 +457,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, subobjects.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, subobjects.getPath());
         assertTrue(subobjects.isAddedByUses());
         // * |-- |-- |-- |-- |-- container bandwidth
@@ -464,7 +467,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, bandwidth.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, bandwidth.getPath());
         assertFalse(bandwidth.isAddedByUses());
         // * |-- |-- |-- |-- container bandwidth
@@ -475,7 +478,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, bandwidth.getPath());
         assertTrue(bandwidth.isAddedByUses());
         // * |-- |-- |-- |-- |-- leaf processing-rule
@@ -484,7 +487,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
         assertEquals(expectedQName, processingRule.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -495,7 +498,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -506,7 +509,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, bandwidth.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, bandwidthInner.getPath());
         assertTrue(bandwidthInner.isAddedByUses());
         // * |-- list svec
@@ -520,7 +523,7 @@ public class UsesAugmentTest {
         path.pollLast();
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, svec.getPath());
         assertFalse(svec.isAddedByUses());
         // * |-- |-- leaf link-diverse
@@ -529,7 +532,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "link-diverse");
         assertEquals(expectedQName, linkDiverse.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, linkDiverse.getPath());
         assertEquals(BooleanType.getInstance(), linkDiverse.getType());
         assertTrue(linkDiverse.isAddedByUses());
@@ -540,7 +543,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, processingRule.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -551,7 +554,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -562,7 +565,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, metric.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, metric.getPath());
         assertFalse(metric.isAddedByUses());
         // * |-- |-- |-- leaf metric-type
@@ -571,7 +574,7 @@ public class UsesAugmentTest {
         expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "metric-type");
         assertEquals(expectedQName, metricType.getQName());
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, metricType.getPath());
         assertEquals(Uint8.getInstance(), metricType.getType());
         assertTrue(metricType.isAddedByUses());
@@ -582,7 +585,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, box.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, box.getPath());
         assertTrue(box.isAddedByUses());
         // * |-- |-- |-- leaf processing-rule
@@ -592,7 +595,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, processingRule.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, processingRule.getPath());
         assertEquals(BooleanType.getInstance(), processingRule.getType());
         assertTrue(processingRule.isAddedByUses());
@@ -603,7 +606,7 @@ public class UsesAugmentTest {
         assertEquals(expectedQName, ignore.getQName());
         path.pollLast();
         path.offer(expectedQName);
-        expectedPath= new SchemaPath(path, true);
+        expectedPath= SchemaPath.create(path, true);
         assertEquals(expectedPath, ignore.getPath());
         assertEquals(BooleanType.getInstance(), ignore.getType());
         assertTrue(ignore.isAddedByUses());
@@ -624,7 +627,7 @@ public class UsesAugmentTest {
         assertNotNull(intExt);
 
         List<QName> path = Lists.newArrayList(new QName(GD_NS, GD_REV, GD_PREF, "int-ext"));
-        SchemaPath expectedPath = new SchemaPath(path, true);
+        SchemaPath expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, intExt.getPath());
 
         UnionType union = (UnionType)intExt.getBaseType();
@@ -642,7 +645,7 @@ public class UsesAugmentTest {
         assertNotNull(pv);
 
         QName q1 = BaseTypes.constructQName("union");
-        expectedPath = new SchemaPath(Lists.newArrayList(q1), true);
+        expectedPath = SchemaPath.create(Lists.newArrayList(q1), true);
         assertEquals(expectedPath, union.getPath());
     }
 
index dfbcc74e47a04c5d033f71bda753067596651757..ac6a8287522696d9b68ce91d7159bc289a3bcc5f 100644 (file)
@@ -7,7 +7,11 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 
 import java.net.URI;
 import java.text.DateFormat;
@@ -21,7 +25,18 @@ import java.util.Set;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
 
 public class YangParserSimpleTest {
     private final URI snNS = URI.create("urn:opendaylight:simple-nodes");
@@ -180,7 +195,7 @@ public class YangParserSimpleTest {
     private Date rev;
     private final String prefix = "sn";
 
-    private SchemaPath createPath(String... names) {
+    private SchemaPath createPath(final String... names) {
         try {
             rev = new SimpleDateFormat("yyyy-MM-dd").parse("2013-07-30");
         } catch (ParseException e) {
@@ -191,7 +206,7 @@ public class YangParserSimpleTest {
         for (String name : names) {
             path.add(new QName(ns, rev, prefix, name));
         }
-        return new SchemaPath(path, true);
+        return SchemaPath.create(path, true);
     }
 
 }
index 9002afdcd224f50e9c9c6b9b4d36c4a2144bd3f3..daf2ee03693c151f07dc069ccb0d7485b8e0a238 100644 (file)
@@ -7,6 +7,32 @@
  */
 package org.opendaylight.yangtools.yang.parser.impl;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -45,32 +71,6 @@ import org.opendaylight.yangtools.yang.model.util.StringType;
 import org.opendaylight.yangtools.yang.model.util.Uint32;
 import org.opendaylight.yangtools.yang.model.util.UnionType;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
 public class YangParserTest {
     public static final String FS = File.separator;
 
@@ -693,7 +693,7 @@ public class YangParserTest {
         List<QName> path = new ArrayList<>();
         path.add(new QName(barNS, barRev, "br", "interfaces"));
         path.add(new QName(barNS, barRev, "br", "ifEntry"));
-        SchemaPath expectedPath = new SchemaPath(path, true);
+        SchemaPath expectedPath = SchemaPath.create(path, true);
 
         assertEquals(expectedPath, dev.getTargetPath());
         assertEquals(Deviate.ADD, dev.getDeviate());
@@ -913,7 +913,7 @@ public class YangParserTest {
         assertSetEquals(newModules, ctx.getModules());
     }
 
-    private void checkOrder(Collection<Module> modules) {
+    private void checkOrder(final Collection<Module> modules) {
         Iterator<Module> it = modules.iterator();
         Module m = it.next();
         assertEquals("m2", m.getName());
@@ -933,7 +933,7 @@ public class YangParserTest {
         assertEquals("m1", m.getName());
     }
 
-    private void assertSetEquals(Set<Module> s1, Set<Module> s2) {
+    private void assertSetEquals(final Set<Module> s1, final Set<Module> s2) {
         assertEquals(s1, s2);
         Iterator<Module> it = s1.iterator();
         for (Module m : s2) {
index e49867527021ef6611bbddf83f18e6adab28f04e..f7ed184300a639069854b8cde0e3edac25b2aa86 100644 (file)
@@ -27,8 +27,23 @@ import java.util.Set;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Deviation;
 import org.opendaylight.yangtools.yang.model.api.Deviation.Deviate;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+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.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
 import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
@@ -206,7 +221,7 @@ public class YangParserWithContextTest {
         QName qname = new QName(URI.create("urn:opendaylight.baz"), simpleDateFormat.parse("2013-02-27"), "baz",
                 "target");
         path.add(qname);
-        SchemaPath expectedPath = new SchemaPath(path, true);
+        SchemaPath expectedPath = SchemaPath.create(path, true);
         assertEquals(expectedPath, usesNode.getGroupingPath());
 
         // test refine
@@ -397,7 +412,7 @@ public class YangParserWithContextTest {
         List<QName> path = new ArrayList<>();
         path.add(new QName(expectedNS, expectedRev, "bar", "interfaces"));
         path.add(new QName(expectedNS, expectedRev, "bar", "ifEntry"));
-        SchemaPath expectedPath = new SchemaPath(path, true);
+        SchemaPath expectedPath = SchemaPath.create(path, true);
 
         assertEquals(expectedPath, dev.getTargetPath());
         assertEquals(Deviate.ADD, dev.getDeviate());
index 7a7524e028e840ffd200d5b27420aba85c01a494..acbf81935946531b0425e3e73f3f4e04abf3fc60 100644 (file)
@@ -13,11 +13,15 @@ import static org.junit.Assert.assertTrue;
 
 import java.net.URI;
 import java.net.URISyntaxException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
 
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
 
@@ -55,7 +59,7 @@ public class BitImplTest {
         List<QName> qnamesA = new ArrayList<>();
         qnamesA.add(qnameA1);
         qnamesA.add(qnameA2);
-        SchemaPath schemaPathA = new SchemaPath(qnamesA, true);
+        SchemaPath schemaPathA = SchemaPath.create(qnamesA, true);
 
         QName qnameB = new QName(uriB, new Date(5000000), "some name");
 
@@ -64,7 +68,7 @@ public class BitImplTest {
         List<QName> qnamesB = new ArrayList<>();
         qnamesB.add(qnameB1);
         qnamesB.add(qnameB2);
-        SchemaPath schemaPathB = new SchemaPath(qnamesB, true);
+        SchemaPath schemaPathB = SchemaPath.create(qnamesB, true);
 
         BitImpl biB = null;
         BitImpl biA = new BitImpl(55L, qnameA, schemaPathA, "description", "reference", Status.CURRENT, null);
index 3783f416915403e58efffc9c30f5266947563a81..e71b8e66bf0406ea7072a33a78bc28969d74fea9 100644 (file)
@@ -161,7 +161,7 @@ public class RefineHolderTest {
         rh1.setReference("reference");
     }
 
-    private URI getUri(String uri) {
+    private URI getUri(final String uri) {
         URI simpleUri = null;
         boolean instantionated = false;
         try {
@@ -188,7 +188,7 @@ public class RefineHolderTest {
         List<QName> qnamesB = new ArrayList<>();
         qnamesA.add(qnameA);
         qnamesB.add(qnameB);
-        SchemaPath schemaPathB = new SchemaPath(qnamesB, true);
+        SchemaPath schemaPathB = SchemaPath.create(qnamesB, true);
 
         UnknownSchemaNodeBuilder usnb = new UnknownSchemaNodeBuilder("usnb", 151, new QName(simpleUri, "tst"), schemaPathB);
         UnknownSchemaNodeBuilder usnb1 = new UnknownSchemaNodeBuilder("usnb", 151, new QName(simpleUri, "tst"), schemaPathB);