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 com.google.common.io.CharSource;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Optional;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.yang.common.UnresolvedQName;
20 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
21 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
24 * A {@link YangTextSchemaSource} backed by a string literal.
26 final class LiteralYangTextSchemaSource extends YangTextSchemaSource {
27 private final @NonNull String sourceString;
29 private LiteralYangTextSchemaSource(final SourceIdentifier identifier, final String sourceString,
30 final String symbolicName) {
32 this.sourceString = requireNonNull(sourceString);
36 * Create a new {@link YangTextSchemaSource} backed by a String input.
38 * @param sourceString YANG file as a String
39 * @return A new instance.
40 * @throws NullPointerException if {@code sourceString} is {@code null}
41 * @throws IllegalArgumentException if {@code sourceString} does not a valid YANG body, given a rather restrictive
42 * view of what is valid.
44 static @NonNull LiteralYangTextSchemaSource ofLiteral(final String sourceString) {
45 // First line of a YANG file looks as follows:
46 // `module module-name {`
47 // therefore in order to extract the name of the module from a plain string, we are interested in the second
48 // word of the first line
49 final String[] firstLine = sourceString.substring(0, sourceString.indexOf("{")).strip().split(" ");
50 final String moduleOrSubmoduleString = firstLine[0].strip();
51 checkArgument(moduleOrSubmoduleString.equals("module") || moduleOrSubmoduleString.equals("submodule"));
53 final String arg = firstLine[1].strip();
54 final var localName = UnresolvedQName.tryLocalName(arg);
55 checkArgument(localName != null);
56 return new LiteralYangTextSchemaSource(new SourceIdentifier(localName), sourceString, arg);
60 public InputStream openStream() throws IOException {
61 return CharSource.wrap(sourceString).asByteSource(StandardCharsets.UTF_8).openStream();
65 public Optional<String> getSymbolicName() {
66 return Optional.of(getIdentifier().name().getLocalName());