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 org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.yangtools.yang.common.UnresolvedQName;
16 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
17 import org.opendaylight.yangtools.yang.model.spi.source.YangTextSource;
20 * A {@link YangTextSource} backed by a string literal.
22 final class LiteralYangTextSource extends YangTextSource {
23 private final @NonNull String sourceString;
25 private LiteralYangTextSource(final SourceIdentifier identifier, final String sourceString,
26 final String symbolicName) {
28 this.sourceString = requireNonNull(sourceString);
32 * Create a new {@link YangTextSource} backed by a String input.
34 * @param sourceString YANG file as a String
35 * @return A new instance.
36 * @throws NullPointerException if {@code sourceString} is {@code null}
37 * @throws IllegalArgumentException if {@code sourceString} does not a valid YANG body, given a rather restrictive
38 * view of what is valid.
40 static @NonNull LiteralYangTextSource ofLiteral(final String sourceString) {
41 // First line of a YANG file looks as follows:
42 // `module module-name {`
43 // therefore in order to extract the name of the module from a plain string, we are interested in the second
44 // word of the first line
45 final String[] firstLine = sourceString.substring(0, sourceString.indexOf("{")).strip().split(" ");
46 final String moduleOrSubmoduleString = firstLine[0].strip();
47 checkArgument(moduleOrSubmoduleString.equals("module") || moduleOrSubmoduleString.equals("submodule"));
49 final String arg = firstLine[1].strip();
50 final var localName = UnresolvedQName.tryLocalName(arg);
51 checkArgument(localName != null);
52 return new LiteralYangTextSource(new SourceIdentifier(localName), sourceString, arg);
56 public StringReader openStream() {
57 return new StringReader(sourceString);
61 public String symbolicName() {
62 return sourceId().name().getLocalName();