Eliminate use of String.split()
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / impl / YangParserImpl.java
index fe57b76dab8ec87b515220e21435149f6e486992..cea011edcbd4652a155d15b8185ad1d457e637a8 100644 (file)
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
+ * 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.parser.impl;
 
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.fillAugmentTarget;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findBaseIdentity;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findModuleFromBuilders;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findModuleFromContext;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findSchemaNode;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findSchemaNodeInModule;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.processAugmentation;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.setNodeAddedByUses;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapChildNode;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapChildNodes;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapGroupings;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapTypedefs;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapUnknownNodes;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveType;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeUnion;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeUnionWithContext;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeWithContext;
+
+import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.HashBiMap;
+import com.google.common.io.ByteSource;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import javax.annotation.concurrent.Immutable;
+
 import org.antlr.v4.runtime.ANTLRInputStream;
 import org.antlr.v4.runtime.CommonTokenStream;
 import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
-import org.apache.commons.io.IOUtils;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangLexer;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.YangContext;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 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.YangModelParser;
+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;
 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.ExtensionBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
 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.DeviationBuilder;
-import org.opendaylight.yangtools.yang.parser.builder.impl.ExtensionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.GroupingUtils;
 import org.opendaylight.yangtools.yang.parser.builder.impl.IdentitySchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.IdentityrefTypeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
-import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder.ModuleImpl;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleImpl;
 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.Comparators;
-import org.opendaylight.yangtools.yang.parser.util.GroupingSort;
-import org.opendaylight.yangtools.yang.parser.util.GroupingUtils;
+import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilderImpl;
+import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
 import org.opendaylight.yangtools.yang.parser.util.NamedByteArrayInputStream;
+import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
 import org.opendaylight.yangtools.yang.parser.util.NamedInputStream;
-import org.opendaylight.yangtools.yang.parser.util.ParserUtils;
 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
-import org.opendaylight.yangtools.yang.validator.YangModelBasicValidator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.fillAugmentTarget;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findBaseIdentity;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findBaseIdentityFromContext;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findModuleFromBuilders;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findModuleFromContext;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findSchemaNode;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findSchemaNodeInModule;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.processAugmentation;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.setNodeAddedByUses;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapChildNode;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapChildNodes;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapGroupings;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapTypedefs;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapUnknownNodes;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveType;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeUnion;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeUnionWithContext;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeWithContext;
-
-
-public final class YangParserImpl implements YangModelParser {
+@Immutable
+public final class YangParserImpl implements YangContextParser {
     private static final Logger LOG = LoggerFactory.getLogger(YangParserImpl.class);
-
     private static final String FAIL_DEVIATION_TARGET = "Failed to find deviation target.";
+    private static final Splitter COLON_SPLITTER = Splitter.on(':');
+    private static final YangParserImpl INSTANCE = new YangParserImpl();
+
+    public static YangParserImpl getInstance() {
+        return INSTANCE;
+    }
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModels(final File yangFile, final File directory) {
+        try {
+            return parseFile(yangFile, directory).getModules();
+        } 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,
+    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");
 
         final String yangFileName = yangFile.getName();
-        final String[] fileList = directory.list();
-        checkNotNull(fileList, directory + " not found");
+        final String[] fileList = checkNotNull(directory.list(), directory + " not found or is not a directory");
 
-        FileInputStream yangFileStream = null;
-        LinkedHashMap<InputStream, File> streamToFileMap = new LinkedHashMap<>();
-        try {
-            yangFileStream = new FileInputStream(yangFile);
-            streamToFileMap.put(yangFileStream, yangFile);
-        } catch (FileNotFoundException e) {
-            LOG.warn("Exception while reading yang file: " + yangFile.getName(), e);
-        }
+        Map<ByteSource, File> sourceToFile = new LinkedHashMap<>();
+        ByteSource mainFileSource = BuilderUtils.fileToByteSource(yangFile);
+        sourceToFile.put(mainFileSource, yangFile);
 
         for (String fileName : fileList) {
             if (fileName.equals(yangFileName)) {
                 continue;
             }
             File dependency = new File(directory, fileName);
-            try {
-                if (dependency.isFile()) {
-                    streamToFileMap.put(new FileInputStream(dependency), dependency);
-                }
-            } catch (FileNotFoundException e) {
-                LOG.warn("Exception while reading yang file: " + fileName, e);
+            if (dependency.isFile()) {
+                sourceToFile.put(BuilderUtils.fileToByteSource(dependency), dependency);
             }
         }
 
-        Map<InputStream, ModuleBuilder> parsedBuilders = parseBuilders(new ArrayList<>(streamToFileMap.keySet()),
-                new HashMap<ModuleBuilder, InputStream>());
-        ModuleBuilder main = parsedBuilders.get(yangFileStream);
+        Map<ByteSource, ModuleBuilder> sourceToBuilder = parseSourcesToBuilders(sourceToFile.keySet());
+        ModuleBuilder main = sourceToBuilder.get(mainFileSource);
 
         List<ModuleBuilder> moduleBuilders = new ArrayList<>();
         moduleBuilders.add(main);
-        filterImports(main, new ArrayList<>(parsedBuilders.values()), moduleBuilders);
-        Collection<ModuleBuilder> result = resolveSubmodules(moduleBuilders);
+        filterImports(main, new ArrayList<>(sourceToBuilder.values()), moduleBuilders);
+        Collection<ModuleBuilder> resolved = resolveSubmodules(moduleBuilders);
 
         // module builders sorted by dependencies
-        ModuleBuilder[] builders = new ModuleBuilder[result.size()];
-        result.toArray(builders);
-        List<ModuleBuilder> sortedBuilders = ModuleDependencySort.sort(builders);
+        List<ModuleBuilder> sortedBuilders = ModuleDependencySort.sort(resolved);
         LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> modules = orderModules(sortedBuilders);
         Collection<Module> unsorted = build(modules).values();
-        return new LinkedHashSet<>(ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+        Set<Module> result = new LinkedHashSet<>(
+                ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+        return resolveSchemaContext(result);
     }
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModels(final List<File> yangFiles) {
+        return parseFiles(yangFiles).getModules();
+    }
+
+    @Override
+    public SchemaContext parseFiles(final Collection<File> yangFiles) {
         Collection<Module> unsorted = parseYangModelsMapped(yangFiles).values();
-        return new LinkedHashSet<>(ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+        Set<Module> sorted = new LinkedHashSet<>(
+                ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+        return resolveSchemaContext(sorted);
     }
 
     @Override
+    @Deprecated
     public Set<Module> parseYangModels(final List<File> yangFiles, final SchemaContext context) {
-        if (yangFiles == null) {
-            return Collections.emptySet();
+        try {
+            return parseFiles(yangFiles, context).getModules();
+        } catch (IOException | YangSyntaxErrorException e) {
+            throw new YangParseException("Failed to parse yang data", e);
         }
+    }
 
-        final Map<InputStream, File> inputStreams = new HashMap<>();
-        for (final File yangFile : yangFiles) {
-            try {
-                inputStreams.put(new FileInputStream(yangFile), yangFile);
-            } catch (FileNotFoundException e) {
-                LOG.warn("Exception while reading yang file: " + yangFile.getName(), e);
-            }
+    @Override
+    public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException,
+    YangSyntaxErrorException {
+        if (yangFiles == null) {
+            return resolveSchemaContext(Collections.<Module> emptySet());
         }
 
-        List<InputStream> yangModelStreams = new ArrayList<>(inputStreams.keySet());
-        Map<ModuleBuilder, InputStream> builderToStreamMap = new HashMap<>();
-        Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangModelStreams,
-                builderToStreamMap, null);
+        Collection<ByteSource> sources = BuilderUtils.filesToByteSources(yangFiles);
+        return parseSources(sources, context);
+    }
 
-        for (InputStream is : inputStreams.keySet()) {
-            try {
-                is.close();
-            } catch (IOException e) {
-                LOG.debug("Failed to close stream.");
-            }
+    @Override
+    @Deprecated
+    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
+        try {
+            Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(yangModelStreams);
+            return parseSources(sources).getModules();
+        } catch (IOException | YangSyntaxErrorException e) {
+            throw new YangParseException("Failed to parse yang data", e);
         }
+    }
 
-        final Collection<Module> unsorted = buildWithContext(modules, context).values();
-        if (context != null) {
-            for (Module m : context.getModules()) {
-                if (!unsorted.contains(m)) {
-                    unsorted.add(m);
-                }
-            }
-        }
-        return new LinkedHashSet<>(ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+    @Override
+    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()])));
+        return resolveSchemaContext(sorted);
     }
 
     @Override
-    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
-        Collection<Module> unsorted = parseYangModelsFromStreamsMapped(yangModelStreams).values();
-        return new LinkedHashSet<>(ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+    @Deprecated
+    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, final SchemaContext context) {
+        try {
+            Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(yangModelStreams);
+            return parseSources(sources, context).getModules();
+        } catch (IOException | YangSyntaxErrorException e) {
+            throw new YangParseException("Failed to parse yang data", e);
+        }
     }
 
     @Override
-    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, SchemaContext context) {
-        if (yangModelStreams == null) {
-            return Collections.emptySet();
+    public SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context)
+            throws IOException, YangSyntaxErrorException {
+        if (sources == null) {
+            return resolveSchemaContext(Collections.<Module> emptySet());
         }
 
-        final Map<ModuleBuilder, InputStream> builderToStreamMap = new HashMap<>();
-        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangModelStreams,
-                builderToStreamMap, context);
+        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(sources, context);
         final Set<Module> unsorted = new LinkedHashSet<>(buildWithContext(modules, context).values());
         if (context != null) {
             for (Module m : context.getModules()) {
@@ -224,169 +247,154 @@ public final class YangParserImpl implements YangModelParser {
                 }
             }
         }
-        return new LinkedHashSet<>(ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+        Set<Module> result = new LinkedHashSet<>(
+                ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
+        return resolveSchemaContext(result);
     }
 
     @Override
-    public Map<File, Module> parseYangModelsMapped(List<File> yangFiles) {
-        if (yangFiles == null) {
+    public Map<File, Module> parseYangModelsMapped(final Collection<File> yangFiles) {
+        if (yangFiles == null || yangFiles.isEmpty()) {
             return Collections.emptyMap();
         }
 
-        final Map<InputStream, File> inputStreams = new HashMap<>();
-        for (final File yangFile : yangFiles) {
-            try {
-
-                inputStreams.put(new FileInputStream(yangFile), yangFile);
-            } catch (FileNotFoundException e) {
-                LOG.warn("Exception while reading yang file: " + yangFile.getName(), e);
-            }
+        Map<ByteSource, File> byteSourceToFile = new HashMap<>();
+        for (final File file : yangFiles) {
+            ByteSource source = new ByteSource() {
+                @Override
+                public InputStream openStream() throws IOException {
+                    return new NamedFileInputStream(file, file.getPath());
+                }
+            };
+            byteSourceToFile.put(source, file);
         }
 
-        List<InputStream> yangModelStreams = new ArrayList<>(inputStreams.keySet());
-        Map<ModuleBuilder, InputStream> builderToStreamMap = new HashMap<>();
-        Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangModelStreams, builderToStreamMap,
-                null);
-
-        for (InputStream is : inputStreams.keySet()) {
-            try {
-                is.close();
-            } catch (IOException e) {
-                LOG.debug("Failed to close stream.");
-            }
+        Map<ByteSource, Module> byteSourceToModule;
+        try {
+            byteSourceToModule = parseYangModelSources(byteSourceToFile.keySet());
+        } catch (IOException | YangSyntaxErrorException e) {
+            throw new YangParseException("Failed to parse yang data", e);
         }
-
         Map<File, Module> result = new LinkedHashMap<>();
-        Map<ModuleBuilder, Module> builderToModuleMap = build(modules);
-        Set<ModuleBuilder> keyset = builderToModuleMap.keySet();
-        List<ModuleBuilder> sorted = ModuleDependencySort.sort(keyset.toArray(new ModuleBuilder[keyset.size()]));
-        for (ModuleBuilder key : sorted) {
-            result.put(inputStreams.get(builderToStreamMap.get(key)), builderToModuleMap.get(key));
+        for (Map.Entry<ByteSource, Module> entry : byteSourceToModule.entrySet()) {
+            result.put(byteSourceToFile.get(entry.getKey()), entry.getValue());
         }
         return result;
     }
 
-    // TODO: fix exception handling
     @Override
-    public Map<InputStream, Module> parseYangModelsFromStreamsMapped(final List<InputStream> yangModelStreams) {
-        if (yangModelStreams == null) {
+    public Map<InputStream, Module> parseYangModelsFromStreamsMapped(final Collection<InputStream> yangModelStreams) {
+        if (yangModelStreams == null || yangModelStreams.isEmpty()) {
             return Collections.emptyMap();
         }
 
-
-        // copy input streams so that they can be read more than once
-        Map<InputStream/*array backed copy */, InputStream/* original for returning*/> arrayBackedToOriginalInputStreams = new HashMap<>();
-        for (final InputStream originalIS : yangModelStreams) {
-            InputStream arrayBackedIs;
-            try {
-                arrayBackedIs = NamedByteArrayInputStream.create(originalIS);
-            } catch (IOException e) {
-                // FIXME: throw IOException here
-                throw new IllegalStateException("Can not get yang as String from " + originalIS, e);
-            }
-            arrayBackedToOriginalInputStreams.put(arrayBackedIs, originalIS);
-        }
-
-        // it would be better if all code from here used string representation of yang sources instead of input streams
-        Map<ModuleBuilder, InputStream> builderToStreamMap = new HashMap<>(); // FIXME: do not modify input parameter
-        Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(new ArrayList<>(arrayBackedToOriginalInputStreams.keySet()),
-                builderToStreamMap,
-                null);
-
-
-        // TODO move deeper
-        for(TreeMap<Date, ModuleBuilder> value : modules.values()) {
-            Collection<ModuleBuilder> values = value.values();
-            for(ModuleBuilder builder: values) {
-                InputStream is = builderToStreamMap.get(builder);
-                try {
-                    is.reset();
-                } catch (IOException e) {
-                    // this cannot happen because it is ByteArrayInputStream
-                    throw new IllegalStateException("Possible error in code", e);
-                }
-                String content;
-                try {
-                    content = IOUtils.toString(is);
-                } catch (IOException e) {
-                    // this cannot happen because it is ByteArrayInputStream
-                    throw new IllegalStateException("Possible error in code", e);
+        Map<ByteSource, InputStream> sourceToStream = new HashMap<>();
+        for (final InputStream stream : yangModelStreams) {
+            ByteSource source = new ByteSource() {
+                @Override
+                public InputStream openStream() throws IOException {
+                    return NamedByteArrayInputStream.create(stream);
                 }
-                builder.setSource(content);
-            }
+            };
+            sourceToStream.put(source, stream);
         }
 
-
-        Map<ModuleBuilder, Module> builderToModuleMap = build(modules);
-
-        Set<ModuleBuilder> keyset = builderToModuleMap.keySet();
-        List<ModuleBuilder> sorted = ModuleDependencySort.sort(keyset.toArray(new ModuleBuilder[keyset.size()]));
+        Map<ByteSource, Module> sourceToModule;
+        try {
+            sourceToModule = parseYangModelSources(sourceToStream.keySet());
+        } catch (IOException | YangSyntaxErrorException e) {
+            throw new YangParseException("Failed to parse yang data", e);
+        }
         Map<InputStream, Module> result = new LinkedHashMap<>();
-        for (ModuleBuilder key : sorted) {
-            Module value = checkNotNull(builderToModuleMap.get(key), "Cannot get module for %s", key);
-            InputStream arrayBackedIS = checkNotNull(builderToStreamMap.get(key), "Cannot get is for %s", key);
-            InputStream originalIS = arrayBackedToOriginalInputStreams.get(arrayBackedIS);
-            result.put(originalIS, value);
+        for (Map.Entry<ByteSource, Module> entry : sourceToModule.entrySet()) {
+            result.put(sourceToStream.get(entry.getKey()), entry.getValue());
         }
         return result;
     }
 
     @Override
     public SchemaContext resolveSchemaContext(final Set<Module> modules) {
-        // after merging parse method with this one, add support for getting submodule sources.
+        // after merging parse method with this one, add support for getting
+        // submodule sources.
         Map<ModuleIdentifier, String> identifiersToSources = new HashMap<>();
-        for(Module module: modules) {
+        for (Module module : modules) {
             ModuleImpl moduleImpl = (ModuleImpl) module;
             identifiersToSources.put(module, moduleImpl.getSource());
         }
         return new SchemaContextImpl(modules, identifiersToSources);
     }
 
-    // FIXME: why a list is required?
-    // FIXME: streamToBuilderMap is output of this method, not input
-    private Map<InputStream, ModuleBuilder> parseModuleBuilders(List<InputStream> inputStreams,
-            Map<ModuleBuilder, InputStream> streamToBuilderMap) {
-        Map<InputStream, ModuleBuilder> modules = parseBuilders(inputStreams, streamToBuilderMap);
-        Map<InputStream, ModuleBuilder> result = resolveSubmodules(modules);
+    private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException,
+    YangSyntaxErrorException {
+        if (sources == null || sources.isEmpty()) {
+            return Collections.emptyMap();
+        }
+
+        Map<ByteSource, ModuleBuilder> sourceToBuilder = resolveSources(sources);
+        // sort and check for duplicates
+        List<ModuleBuilder> sorted = ModuleDependencySort.sort(sourceToBuilder.values());
+        Map<String, TreeMap<Date, ModuleBuilder>> modules = orderModules(sorted);
+        Map<ModuleBuilder, Module> builderToModule = build(modules);
+        Map<ModuleBuilder, ByteSource> builderToSource = HashBiMap.create(sourceToBuilder).inverse();
+        sorted = ModuleDependencySort.sort(builderToModule.keySet());
+
+        Map<ByteSource, Module> result = new LinkedHashMap<>();
+        for (ModuleBuilder moduleBuilder : sorted) {
+            Module value = checkNotNull(builderToModule.get(moduleBuilder), "Cannot get module for %s", moduleBuilder);
+            result.put(builderToSource.get(moduleBuilder), value);
+        }
+
         return result;
     }
 
-    // FIXME: why a list is required?
-    // FIXME: streamToBuilderMap is output of this method, not input
-    private Map<InputStream, ModuleBuilder> parseBuilders(List<InputStream> inputStreams,
-            Map<ModuleBuilder, InputStream> streamToBuilderMap) {
+    /**
+     * Parse streams and resolve submodules.
+     *
+     * @param streams
+     *            collection of streams to parse
+     * @return map, where key is source stream and value is module builder
+     *         parsed from stream
+     * @throws YangSyntaxErrorException
+     */
+    // TODO: remove ByteSource result after removing YangModelParser
+    private Map<ByteSource, ModuleBuilder> resolveSources(final Collection<ByteSource> streams)
+            throws IOException, YangSyntaxErrorException {
+        Map<ByteSource, ModuleBuilder> builders = parseSourcesToBuilders(streams);
+        return resolveSubmodules(builders);
+    }
+
+    private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(final Collection<ByteSource> sources)
+            throws IOException, YangSyntaxErrorException {
         final ParseTreeWalker walker = new ParseTreeWalker();
-        final Map<InputStream, ParseTree> trees = parseStreams(inputStreams);
-        final Map<InputStream, ModuleBuilder> builders = new LinkedHashMap<>();
+        final Map<ByteSource, ParseTree> sourceToTree = parseYangSources(sources);
+        final Map<ByteSource, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
 
         // validate yang
-        new YangModelBasicValidator(walker).validate(new ArrayList<>(trees.values()));
+        new YangModelBasicValidator(walker).validate(sourceToTree.values());
 
         YangParserListenerImpl yangModelParser;
-        for (Map.Entry<InputStream, ParseTree> entry : trees.entrySet()) {
-            InputStream is = entry.getKey();
-            String path = null;
-            if (is instanceof NamedInputStream) {
-                path = is.toString();
+        for (Map.Entry<ByteSource, ParseTree> entry : sourceToTree.entrySet()) {
+            ByteSource source = entry.getKey();
+            String path = null; // TODO refactor to Optional
+            //TODO refactor so that path can be retrieved without opening stream: NamedInputStream -> NamedByteSource ?
+            try(InputStream stream = source.openStream()) {
+                if (stream instanceof NamedInputStream) {
+                    path = stream.toString();
+                }
             }
             yangModelParser = new YangParserListenerImpl(path);
             walker.walk(yangModelParser, entry.getValue());
             ModuleBuilder moduleBuilder = yangModelParser.getModuleBuilder();
-
-            // We expect the order of trees and streams has to be the same
-            // FIXME: input parameters should be treated as immutable
-            streamToBuilderMap.put(moduleBuilder, entry.getKey());
-
-            builders.put(entry.getKey(), moduleBuilder);
+            moduleBuilder.setSource(source);
+            sourceToBuilder.put(source, moduleBuilder);
         }
-
-        return builders;
+        return sourceToBuilder;
     }
 
-    private Map<InputStream, ModuleBuilder> resolveSubmodules(Map<InputStream, ModuleBuilder> builders) {
-        Map<InputStream, ModuleBuilder> modules = new HashMap<>();
+    private Map<ByteSource, ModuleBuilder> resolveSubmodules(final Map<ByteSource, ModuleBuilder> builders) {
+        Map<ByteSource, ModuleBuilder> modules = new HashMap<>();
         Set<ModuleBuilder> submodules = new HashSet<>();
-        for (Map.Entry<InputStream, ModuleBuilder> entry : builders.entrySet()) {
+        for (Map.Entry<ByteSource, ModuleBuilder> entry : builders.entrySet()) {
             ModuleBuilder moduleBuilder = entry.getValue();
             if (moduleBuilder.isSubmodule()) {
                 submodules.add(moduleBuilder);
@@ -406,7 +414,15 @@ public final class YangParserImpl implements YangModelParser {
         return modules;
     }
 
-    private Collection<ModuleBuilder> resolveSubmodules(Collection<ModuleBuilder> builders) {
+    /**
+     * Traverse collection of builders, find builders representing submodule and
+     * add this submodule to its parent module.
+     *
+     * @param builders
+     *            collection of builders containing modules and submodules
+     * @return collection of module builders
+     */
+    private Collection<ModuleBuilder> resolveSubmodules(final Collection<ModuleBuilder> builders) {
         Collection<ModuleBuilder> modules = new HashSet<>();
         Set<ModuleBuilder> submodules = new HashSet<>();
         for (ModuleBuilder moduleBuilder : builders) {
@@ -427,7 +443,7 @@ public final class YangParserImpl implements YangModelParser {
         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());
@@ -435,7 +451,7 @@ public final class YangParserImpl implements YangModelParser {
         module.getAugmentBuilders().addAll(submodule.getAugmentBuilders());
         module.getAllAugments().addAll(submodule.getAllAugments());
         module.getChildNodeBuilders().addAll(submodule.getChildNodeBuilders());
-        module.getChildNodes().addAll(submodule.getChildNodes());
+        module.getChildNodes().putAll(submodule.getChildNodes());
         module.getGroupings().addAll(submodule.getGroupings());
         module.getGroupingBuilders().addAll(submodule.getGroupingBuilders());
         module.getTypeDefinitions().addAll(submodule.getTypeDefinitions());
@@ -460,11 +476,10 @@ public final class YangParserImpl implements YangModelParser {
         module.getAllUnknownNodes().addAll(submodule.getAllUnknownNodes());
     }
 
-    // FIXME: why a list is required?
-    // FIXME: streamToBuilderMap is output of this method, not input
-    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(final List<InputStream> yangFileStreams,
-            final Map<ModuleBuilder, InputStream> streamToBuilderMap, final SchemaContext context) {
-        Map<InputStream, ModuleBuilder> parsedBuilders = parseModuleBuilders(yangFileStreams, streamToBuilderMap);
+    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
+            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);
 
@@ -485,7 +500,7 @@ public final class YangParserImpl implements YangModelParser {
      *            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) {
@@ -506,7 +521,19 @@ public final class YangParserImpl implements YangModelParser {
         return result;
     }
 
-    private void filterImports(ModuleBuilder main, List<ModuleBuilder> other, List<ModuleBuilder> filtered) {
+    /**
+     * Find {@code main} dependencies from {@code other} and add them to
+     * {@code filtered}.
+     *
+     * @param main
+     *            main yang module
+     * @param other
+     *            all loaded modules
+     * @param filtered
+     *            collection to fill up
+     */
+    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
@@ -543,34 +570,38 @@ public final class YangParserImpl implements YangModelParser {
         }
     }
 
-    // FIXME: why a list is required?
-    private Map<InputStream, ParseTree> parseStreams(final List<InputStream> yangStreams) {
-        final Map<InputStream, ParseTree> trees = new HashMap<>();
-        for (InputStream yangStream : yangStreams) {
-            trees.put(yangStream, parseStream(yangStream));
+    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));
         }
         return trees;
     }
 
-    private ParseTree parseStream(final InputStream yangStream) {
-        ParseTree result = null;
-        try {
-            final ANTLRInputStream input = new ANTLRInputStream(yangStream);
+    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();
-        } catch (IOException e) {
-            // TODO: fix this ASAP
-            LOG.warn("Exception while reading yang file: " + yangStream, e);
+
+            return result;
         }
-        return result;
     }
 
+    /**
+     * Mini parser: This parsing context does not validate full YANG module, only
+     * parses header up to the revisions and imports.
+     * @see org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo
+     */
     public static YangContext parseStreamWithoutErrorListeners(final InputStream yangStream) {
         YangContext result = null;
         try {
@@ -614,6 +645,7 @@ public final class YangParserImpl implements YangModelParser {
         resolveUsesForGroupings(modules, null);
         resolveUsesForNodes(modules, null);
         resolveAugments(modules, null);
+        resolveIdentities(modules);
         resolveDeviations(modules);
 
         // build
@@ -659,6 +691,7 @@ public final class YangParserImpl implements YangModelParser {
         resolveUsesForGroupings(modules, context);
         resolveUsesForNodes(modules, context);
         resolveAugments(modules, context);
+        resolveIdentitiesWithContext(modules, context);
         resolveDeviationsWithContext(modules, context);
 
         // build
@@ -684,7 +717,6 @@ public final class YangParserImpl implements YangModelParser {
             for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
                 final ModuleBuilder module = childEntry.getValue();
                 resolveUnknownNodes(modules, module);
-                resolveIdentities(modules, module);
                 resolveDirtyNodes(modules, module);
             }
         }
@@ -704,7 +736,6 @@ public final class YangParserImpl implements YangModelParser {
             for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
                 final ModuleBuilder module = childEntry.getValue();
                 resolveUnknownNodesWithContext(modules, module, context);
-                resolveIdentitiesWithContext(modules, module, context);
                 resolveDirtyNodesWithContext(modules, module, context);
             }
         }
@@ -744,7 +775,7 @@ public final class YangParserImpl implements YangModelParser {
     }
 
     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) {
@@ -775,7 +806,7 @@ public final class YangParserImpl implements YangModelParser {
      *            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()) {
@@ -801,9 +832,8 @@ public final class YangParserImpl implements YangModelParser {
      */
     private void setCorrectAugmentTargetPath(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final AugmentationSchemaBuilder augment, final SchemaContext context) {
-        ModuleBuilder module = ParserUtils.getParentModule(augment);
+        ModuleBuilder module = BuilderUtils.getParentModule(augment);
         SchemaPath oldSchemaPath = augment.getTargetPath();
-        List<QName> oldPath = oldSchemaPath.getPath();
         List<QName> newPath = new ArrayList<>();
 
         Builder parent = augment.getParent();
@@ -811,49 +841,44 @@ public final class YangParserImpl implements YangModelParser {
             DataNodeContainerBuilder usesParent = ((UsesNodeBuilder) parent).getParent();
             newPath.addAll(usesParent.getPath().getPath());
 
-            URI ns;
-            Date revision;
-            String prefix;
-            QName baseQName = usesParent.getQName();
+            final QName baseQName = usesParent.getQName();
+            final QNameModule qnm;
+            final String prefix;
             if (baseQName == null) {
-                ModuleBuilder m = ParserUtils.getParentModule(usesParent);
-                ns = m.getNamespace();
-                revision = m.getRevision();
+                ModuleBuilder m = BuilderUtils.getParentModule(usesParent);
+                qnm = m.getQNameModule();
                 prefix = m.getPrefix();
             } else {
-                ns = baseQName.getNamespace();
-                revision = baseQName.getRevision();
+                qnm = baseQName.getModule();
                 prefix = baseQName.getPrefix();
             }
 
-            for (QName qn : oldSchemaPath.getPath()) {
-                newPath.add(new QName(ns, revision, prefix, qn.getLocalName()));
+            for (QName qn : oldSchemaPath.getPathFromRoot()) {
+                newPath.add(QName.create(qnm, prefix, qn.getLocalName()));
             }
         } else {
+            Iterable<QName> oldPath = oldSchemaPath.getPathFromRoot();
             for (QName qn : oldPath) {
-                URI ns = module.getNamespace();
-                Date rev = module.getRevision();
+                QNameModule qnm = module.getQNameModule();
                 String localPrefix = qn.getPrefix();
-                if (localPrefix != null && !("".equals(localPrefix))) {
-                    ModuleBuilder currentModule = ParserUtils.findModuleFromBuilders(modules, module, localPrefix,
+                if (localPrefix != null && !localPrefix.isEmpty()) {
+                    ModuleBuilder currentModule = BuilderUtils.findModuleFromBuilders(modules, module, localPrefix,
                             augment.getLine());
                     if (currentModule == null) {
-                        Module m = ParserUtils.findModuleFromContext(context, module, localPrefix, augment.getLine());
+                        Module m = BuilderUtils.findModuleFromContext(context, module, localPrefix, augment.getLine());
                         if (m == null) {
                             throw new YangParseException(module.getName(), augment.getLine(), "Module with prefix "
                                     + localPrefix + " not found.");
                         }
-                        ns = m.getNamespace();
-                        rev = m.getRevision();
+                        qnm = m.getQNameModule();
                     } else {
-                        ns = currentModule.getNamespace();
-                        rev = currentModule.getRevision();
+                        qnm = currentModule.getQNameModule();
                     }
                 }
-                newPath.add(new QName(ns, rev, localPrefix, qn.getLocalName()));
+                newPath.add(new QName(qnm.getNamespace(), qnm.getRevision(), localPrefix, qn.getLocalName()));
             }
         }
-        augment.setTargetNodeSchemaPath(new SchemaPath(newPath, augment.getTargetPath().isAbsolute()));
+        augment.setTargetNodeSchemaPath(SchemaPath.create(newPath, true));
 
         for (DataSchemaNodeBuilder childNode : augment.getChildNodeBuilders()) {
             correctPathForAugmentNodes(childNode, augment.getTargetNodeSchemaPath());
@@ -869,8 +894,8 @@ public final class YangParserImpl implements YangModelParser {
      * @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()) {
@@ -878,7 +903,7 @@ public final class YangParserImpl implements YangModelParser {
             }
         }
         if (node instanceof ChoiceBuilder) {
-            for (ChoiceCaseBuilder child : ((ChoiceBuilder)node).getCases()) {
+            for (ChoiceCaseBuilder child : ((ChoiceBuilder) node).getCases()) {
                 correctPathForAugmentNodes(child, node.getPath());
             }
         }
@@ -892,10 +917,10 @@ public final class YangParserImpl implements YangModelParser {
      * @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);
+            String augmentPrefix = augment.getTargetPath().getPathFromRoot().iterator().next().getPrefix();
+            ModuleBuilder module = BuilderUtils.getParentModule(augment);
             String modulePrefix = module.getPrefix();
 
             if (augmentPrefix == null || augmentPrefix.isEmpty() || augmentPrefix.equals(modulePrefix)) {
@@ -974,16 +999,39 @@ public final class YangParserImpl implements YangModelParser {
 
         UsesNodeBuilder usesNode = (UsesNodeBuilder) augment.getParent();
         DataNodeContainerBuilder parentNode = usesNode.getParent();
-        SchemaNodeBuilder targetNode;
-        if (parentNode instanceof ModuleBuilder) {
-            targetNode = findSchemaNodeInModule(augment.getTargetPath().getPath(), (ModuleBuilder) parentNode);
+        Optional<SchemaNodeBuilder> potentialTargetNode;
+        SchemaPath resolvedTargetPath = augment.getTargetNodeSchemaPath();
+        if (parentNode instanceof ModuleBuilder && resolvedTargetPath.isAbsolute()) {
+            // Uses is directly used in module body, we lookup
+            // We lookup in data namespace to find correct augmentation target
+            potentialTargetNode = findSchemaNodeInModule(resolvedTargetPath, (ModuleBuilder) parentNode);
         } else {
-            targetNode = findSchemaNode(augment.getTargetPath().getPath(), (SchemaNodeBuilder) parentNode);
+            // Uses is used in local context (be it data namespace or grouping namespace,
+            // since all nodes via uses are imported to localName, it is safe to
+            // to proceed only with local names.
+            //
+            // Conflicting elements in other namespaces are still not present
+            // since resolveUsesAugment occurs before augmenting from external modules.
+            potentialTargetNode = Optional.<SchemaNodeBuilder> fromNullable(findSchemaNode(augment.getTargetPath()
+                    .getPath(), (SchemaNodeBuilder) parentNode));
+        }
+
+        if (potentialTargetNode.isPresent()) {
+            SchemaNodeBuilder targetNode = potentialTargetNode.get();
+            if (targetNode instanceof AugmentationTargetBuilder) {
+                fillAugmentTarget(augment, targetNode);
+                ((AugmentationTargetBuilder) targetNode).addAugmentation(augment);
+                augment.setResolved(true);
+                return true;
+            } else {
+                throw new YangParseException(module.getName(), augment.getLine(), String.format(
+                        "Failed to resolve augment in uses. Invalid augment target: %s", potentialTargetNode));
+            }
+        } else {
+            throw new YangParseException(module.getName(), augment.getLine(), String.format(
+                    "Failed to resolve augment in uses. Invalid augment target path: %s", augment.getTargetPath()));
         }
 
-        fillAugmentTarget(augment, targetNode);
-        augment.setResolved(true);
-        return true;
     }
 
     /**
@@ -1005,8 +1053,8 @@ public final class YangParserImpl implements YangModelParser {
             return true;
         }
 
-        List<QName> targetPath = augment.getTargetPath().getPath();
-        ModuleBuilder targetModule = findTargetModule(targetPath.get(0), module, modules, context, augment.getLine());
+        QName targetPath = augment.getTargetPath().getPathFromRoot().iterator().next();
+        ModuleBuilder targetModule = findTargetModule(targetPath, module, modules, context, augment.getLine());
         if (targetModule == null) {
             throw new YangParseException(module.getModuleName(), augment.getLine(), "Failed to resolve augment "
                     + augment);
@@ -1033,10 +1081,10 @@ public final class YangParserImpl implements YangModelParser {
      */
     private ModuleBuilder findTargetModule(final QName qname, final ModuleBuilder module,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context, final int line) {
-        ModuleBuilder targetModule = null;
+        ModuleBuilder targetModule;
 
         String prefix = qname.getPrefix();
-        if (prefix == null || prefix.equals("")) {
+        if (prefix == null || prefix.isEmpty()) {
             targetModule = module;
         } else {
             targetModule = findModuleFromBuilders(modules, module, qname.getPrefix(), line);
@@ -1058,6 +1106,29 @@ public final class YangParserImpl implements YangModelParser {
         return targetModule;
     }
 
+    private ModuleBuilder findTargetModule(final String prefix, final ModuleBuilder module,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context, final int line) {
+        ModuleBuilder targetModule;
+
+        if (prefix == null || prefix.equals("")) {
+            targetModule = module;
+        } else {
+            targetModule = findModuleFromBuilders(modules, module, prefix, line);
+        }
+
+        if (targetModule == null && context != null) {
+            Module m = findModuleFromContext(context, module, prefix, line);
+            if (m != null) {
+                targetModule = new ModuleBuilder(m);
+                TreeMap<Date, ModuleBuilder> map = new TreeMap<>();
+                map.put(targetModule.getRevision(), targetModule);
+                modules.put(targetModule.getModuleName(), map);
+            }
+        }
+
+        return targetModule;
+    }
+
     /**
      * Go through identity statements defined in current module and resolve
      * their 'base' statement if present.
@@ -1067,18 +1138,26 @@ public final class YangParserImpl implements YangModelParser {
      * @param module
      *            module being resolved
      */
-    private void resolveIdentities(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
-        final Set<IdentitySchemaNodeBuilder> identities = module.getAddedIdentities();
-        for (IdentitySchemaNodeBuilder identity : identities) {
-            final String baseIdentityName = identity.getBaseIdentityName();
-            final int line = identity.getLine();
-            if (baseIdentityName != null) {
-                IdentitySchemaNodeBuilder baseIdentity = findBaseIdentity(modules, module, baseIdentityName, line);
-                if (baseIdentity == null) {
-                    throw new YangParseException(module.getName(), identity.getLine(), "Failed to find base identity");
-                } else {
-                    identity.setBaseIdentity(baseIdentity);
+    private void resolveIdentities(final Map<String, TreeMap<Date, ModuleBuilder>> modules) {
+        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+            for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
+                ModuleBuilder module = inner.getValue();
+                final Set<IdentitySchemaNodeBuilder> identities = module.getAddedIdentities();
+                for (IdentitySchemaNodeBuilder identity : identities) {
+                    final String baseIdentityName = identity.getBaseIdentityName();
+                    final int line = identity.getLine();
+                    if (baseIdentityName != null) {
+                        IdentitySchemaNodeBuilder baseIdentity = findBaseIdentity(modules, module, baseIdentityName,
+                                line);
+                        if (baseIdentity == null) {
+                            throw new YangParseException(module.getName(), identity.getLine(),
+                                    "Failed to find base identity");
+                        } else {
+                            identity.setBaseIdentity(baseIdentity);
+                        }
+                    }
                 }
+
             }
         }
     }
@@ -1096,19 +1175,35 @@ public final class YangParserImpl implements YangModelParser {
      *            SchemaContext containing already resolved modules
      */
     private void resolveIdentitiesWithContext(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module, final SchemaContext context) {
-        final Set<IdentitySchemaNodeBuilder> identities = module.getAddedIdentities();
-        for (IdentitySchemaNodeBuilder identity : identities) {
-            final String baseIdentityName = identity.getBaseIdentityName();
-            final int line = identity.getLine();
-            if (baseIdentityName != null) {
-                IdentitySchemaNodeBuilder baseIdentity = findBaseIdentity(modules, module, baseIdentityName, line);
-                if (baseIdentity == null) {
-                    IdentitySchemaNode baseId = findBaseIdentityFromContext(modules, module, baseIdentityName, line,
-                            context);
-                    identity.setBaseIdentity(baseId);
-                } else {
-                    identity.setBaseIdentity(baseIdentity);
+            final SchemaContext context) {
+        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+            for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
+                ModuleBuilder module = inner.getValue();
+                final Set<IdentitySchemaNodeBuilder> identities = module.getAddedIdentities();
+                for (IdentitySchemaNodeBuilder identity : identities) {
+                    final String baseIdentityName = identity.getBaseIdentityName();
+                    final int line = identity.getLine();
+                    if (baseIdentityName != null) {
+
+                        IdentitySchemaNodeBuilder result = null;
+                        if (baseIdentityName.indexOf(':') != -1) {
+                            final Iterator<String> split = COLON_SPLITTER.split(baseIdentityName).iterator();
+                            final String prefix = split.next();
+                            final String name = split.next();
+                            if (split.hasNext()) {
+                                throw new YangParseException(module.getName(), line,
+                                        "Failed to parse identityref base: " + baseIdentityName);
+                            }
+
+                            ModuleBuilder dependentModule = findTargetModule(prefix, module, modules, context, line);
+                            if (dependentModule != null) {
+                                result = BuilderUtils.findIdentity(dependentModule.getAddedIdentities(), name);
+                            }
+                        } else {
+                            result = BuilderUtils.findIdentity(module.getAddedIdentities(), baseIdentityName);
+                        }
+                        identity.setBaseIdentity(result);
+                    }
                 }
             }
         }
@@ -1132,7 +1227,7 @@ public final class YangParserImpl implements YangModelParser {
             }
         }
         for (UsesNodeBuilder usesNode : allUses) {
-            ModuleBuilder module = ParserUtils.getParentModule(usesNode);
+            ModuleBuilder module = BuilderUtils.getParentModule(usesNode);
             final GroupingBuilder targetGroupingBuilder = GroupingUtils.getTargetGroupingFromModules(usesNode, modules,
                     module);
             if (targetGroupingBuilder == null) {
@@ -1158,7 +1253,8 @@ public final class YangParserImpl implements YangModelParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUsesForGroupings(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
+    private void resolveUsesForGroupings(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final SchemaContext context) {
         final Set<GroupingBuilder> allGroupings = new HashSet<>();
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
             for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
@@ -1184,7 +1280,8 @@ public final class YangParserImpl implements YangModelParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUsesForNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
+    private void resolveUsesForNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final SchemaContext context) {
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
             for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
                 ModuleBuilder module = inner.getValue();
@@ -1208,11 +1305,11 @@ public final class YangParserImpl implements YangModelParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUses(UsesNodeBuilder usesNode,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
+    private void resolveUses(final UsesNodeBuilder usesNode, final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final SchemaContext context) {
         if (!usesNode.isResolved()) {
             DataNodeContainerBuilder parent = usesNode.getParent();
-            ModuleBuilder module = ParserUtils.getParentModule(parent);
+            ModuleBuilder module = BuilderUtils.getParentModule(parent);
             GroupingBuilder target = GroupingUtils.getTargetGroupingFromModules(usesNode, modules, module);
             if (target == null) {
                 resolveUsesWithContext(usesNode);
@@ -1235,8 +1332,7 @@ public final class YangParserImpl implements YangModelParser {
     }
 
     /**
-     * Copy target grouping child nodes to current location with
-     * new namespace.
+     * Copy target grouping child nodes to current location with new namespace.
      *
      * @param usesNode
      *            uses node to resolve
@@ -1245,55 +1341,49 @@ public final class YangParserImpl implements YangModelParser {
      * @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);
+        ModuleBuilder module = BuilderUtils.getParentModule(parent);
         SchemaPath parentPath;
-        URI ns = null;
-        Date rev = null;
-        String pref = null;
+
+        final QName parentQName;
         if (parent instanceof AugmentationSchemaBuilder || parent instanceof ModuleBuilder) {
-            ns = module.getNamespace();
-            rev = module.getRevision();
-            pref = module.getPrefix();
+            parentQName = QName.create(module.getQNameModule(), module.getPrefix(), "dummy");
             if (parent instanceof AugmentationSchemaBuilder) {
-                parentPath = ((AugmentationSchemaBuilder)parent).getTargetNodeSchemaPath();
+                parentPath = ((AugmentationSchemaBuilder) parent).getTargetNodeSchemaPath();
             } else {
-                parentPath = ((ModuleBuilder)parent).getPath();
+                parentPath = parent.getPath();
             }
         } else {
-            ns = ((DataSchemaNodeBuilder) parent).getQName().getNamespace();
-            rev = ((DataSchemaNodeBuilder) parent).getQName().getRevision();
-            pref = ((DataSchemaNodeBuilder) parent).getQName().getPrefix();
-            parentPath = ((DataSchemaNodeBuilder)parent).getPath();
+            parentQName = parent.getQName();
+            parentPath = parent.getPath();
         }
 
         GroupingDefinition gd = usesNode.getGroupingDefinition();
 
-        Set<DataSchemaNodeBuilder> childNodes = wrapChildNodes(module.getModuleName(), line,
-                gd.getChildNodes(), parentPath, ns, rev, pref);
+        Set<DataSchemaNodeBuilder> childNodes = wrapChildNodes(module.getModuleName(), line, gd.getChildNodes(),
+                parentPath, parentQName);
         parent.getChildNodeBuilders().addAll(childNodes);
         for (DataSchemaNodeBuilder childNode : childNodes) {
             setNodeAddedByUses(childNode);
         }
 
-        Set<TypeDefinitionBuilder> typedefs = wrapTypedefs(module.getModuleName(), line, gd, parentPath, ns,
-                rev, pref);
+        Set<TypeDefinitionBuilder> typedefs = wrapTypedefs(module.getModuleName(), line, gd, parentPath, parentQName);
         parent.getTypeDefinitionBuilders().addAll(typedefs);
         for (TypeDefinitionBuilder typedef : typedefs) {
             setNodeAddedByUses(typedef);
         }
 
-        Set<GroupingBuilder> groupings = wrapGroupings(module.getModuleName(), line, usesNode
-                .getGroupingDefinition().getGroupings(), parentPath, ns, rev, pref);
+        Set<GroupingBuilder> groupings = wrapGroupings(module.getModuleName(), line, usesNode.getGroupingDefinition()
+                .getGroupings(), parentPath, parentQName);
         parent.getGroupingBuilders().addAll(groupings);
         for (GroupingBuilder gb : groupings) {
             setNodeAddedByUses(gb);
         }
 
-        List<UnknownSchemaNodeBuilder> unknownNodes = wrapUnknownNodes(module.getModuleName(), line,
-                gd.getUnknownSchemaNodes(), parentPath, ns, rev, pref);
+        List<UnknownSchemaNodeBuilderImpl> unknownNodes = wrapUnknownNodes(module.getModuleName(), line,
+                gd.getUnknownSchemaNodes(), parentPath, parentQName);
         parent.getUnknownNodes().addAll(unknownNodes);
         for (UnknownSchemaNodeBuilder un : unknownNodes) {
             un.setAddedByUses(true);
@@ -1404,8 +1494,8 @@ public final class YangParserImpl implements YangModelParser {
         for (DeviationBuilder dev : module.getDeviationBuilders()) {
             int line = dev.getLine();
             SchemaPath targetPath = dev.getTargetPath();
-            List<QName> path = targetPath.getPath();
-            QName q0 = path.get(0);
+            Iterable<QName> path = targetPath.getPathFromRoot();
+            QName q0 = path.iterator().next();
             String prefix = q0.getPrefix();
             if (prefix == null) {
                 prefix = module.getPrefix();
@@ -1451,8 +1541,8 @@ public final class YangParserImpl implements YangModelParser {
         for (DeviationBuilder dev : module.getDeviationBuilders()) {
             int line = dev.getLine();
             SchemaPath targetPath = dev.getTargetPath();
-            List<QName> path = targetPath.getPath();
-            QName q0 = path.get(0);
+            Iterable<QName> path = targetPath.getPathFromRoot();
+            QName q0 = path.iterator().next();
             String prefix = q0.getPrefix();
             if (prefix == null) {
                 prefix = module.getPrefix();
@@ -1498,7 +1588,7 @@ public final class YangParserImpl implements YangModelParser {
      *            current module
      */
     private void processDeviation(final DeviationBuilder dev, final ModuleBuilder dependentModuleBuilder,
-            final List<QName> path, final ModuleBuilder module) {
+            final Iterable<QName> path, final ModuleBuilder module) {
         final int line = dev.getLine();
         Builder currentParent = dependentModuleBuilder;