2 * Copyright (c) 2023 PANTHEON.tech s.r.o. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.test.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import java.io.StringReader;
14 import java.util.Optional;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.yangtools.yang.common.UnresolvedQName;
17 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
18 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
21 * A {@link YangTextSchemaSource} backed by a string literal.
23 final class LiteralYangTextSchemaSource extends YangTextSchemaSource {
24 private final @NonNull String sourceString;
26 private LiteralYangTextSchemaSource(final SourceIdentifier identifier, final String sourceString,
27 final String symbolicName) {
29 this.sourceString = requireNonNull(sourceString);
33 * Create a new {@link YangTextSchemaSource} backed by a String input.
35 * @param sourceString YANG file as a String
36 * @return A new instance.
37 * @throws NullPointerException if {@code sourceString} is {@code null}
38 * @throws IllegalArgumentException if {@code sourceString} does not a valid YANG body, given a rather restrictive
39 * view of what is valid.
41 static @NonNull LiteralYangTextSchemaSource ofLiteral(final String sourceString) {
42 // First line of a YANG file looks as follows:
43 // `module module-name {`
44 // therefore in order to extract the name of the module from a plain string, we are interested in the second
45 // word of the first line
46 final String[] firstLine = sourceString.substring(0, sourceString.indexOf("{")).strip().split(" ");
47 final String moduleOrSubmoduleString = firstLine[0].strip();
48 checkArgument(moduleOrSubmoduleString.equals("module") || moduleOrSubmoduleString.equals("submodule"));
50 final String arg = firstLine[1].strip();
51 final var localName = UnresolvedQName.tryLocalName(arg);
52 checkArgument(localName != null);
53 return new LiteralYangTextSchemaSource(new SourceIdentifier(localName), sourceString, arg);
57 public StringReader openStream() {
58 return new StringReader(sourceString);
62 public Optional<String> getSymbolicName() {
63 return Optional.of(getIdentifier().name().getLocalName());