2 * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. 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.model.spi.source;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import java.io.IOException;
14 import java.io.InputStreamReader;
15 import java.io.Reader;
16 import java.nio.charset.Charset;
17 import java.nio.charset.StandardCharsets;
18 import java.nio.file.Files;
19 import java.nio.file.Path;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.opendaylight.yangtools.concepts.Delegator;
23 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
26 * A {@link YangTextSource} backed by a file.
29 public class FileYangTextSource extends YangTextSource implements Delegator<Path> {
30 private final Path path;
31 private final Charset charset;
34 * Default constructor.
36 * @param path Backing path
37 * @param sourceId source identifier
38 * @param charset expected stream character set
39 * @throws NullPointerException if any argument is {@code null}
40 * @throws IllegalArgumentException if the supplied path is not a regular file
42 public FileYangTextSource(final SourceIdentifier sourceId, final Path path, final Charset charset) {
44 if (!Files.isRegularFile(path)) {
45 throw new IllegalArgumentException("Supplied path " + path + " is not a regular file");
47 this.path = requireNonNull(path);
48 this.charset = requireNonNull(charset);
52 * Utility constructor. Derives the {@link SourceIdentifier} from {@link Path} and assumes UTF-8 encoding.
54 * @param path backing path
55 * @throws NullPointerException if {@code path} is {@code null}
57 public FileYangTextSource(final Path path) {
58 // FIXME: do not use .toFile() here
59 this(SourceIdentifier.ofYangFileName(path.toFile().getName()), path, StandardCharsets.UTF_8);
63 public final Path getDelegate() {
68 public final Reader openStream() throws IOException {
69 return new InputStreamReader(Files.newInputStream(path), charset);
73 public final @NonNull String symbolicName() {
74 // FIXME: NEXT: this is forcing internal normalization. I think this boils down to providing Path back, which
75 // is essentially getDelegate() anyway. Perhaps expose it as PathAware?
76 return path.toString();
80 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
81 return super.addToStringAttributes(toStringHelper).add("path", path);