e4cdb1ef7023dd9f7c97cf63adb5a58760ced65a
[yangtools.git] /
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.model.spi.source;
9
10 import static java.util.Objects.requireNonNull;
11
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.net.URL;
17 import java.nio.charset.Charset;
18 import java.nio.charset.StandardCharsets;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.opendaylight.yangtools.concepts.Delegator;
22 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
23
24 /**
25  * A {@link YangTextSource} backed by a {@link URL}.
26  */
27 @NonNullByDefault
28 public class URLYangTextSource extends YangTextSource implements Delegator<URL> {
29     private final URL url;
30     private final Charset charset;
31
32     public URLYangTextSource(final SourceIdentifier sourceId, final URL url, final Charset charset) {
33         super(sourceId);
34         this.url = requireNonNull(url);
35         this.charset = requireNonNull(charset);
36     }
37
38     /**
39      * Utility constructor. The {@link SourceIdentifier} is derived from {@link URL#getPath()} and the character set is
40      * assumed to be UTF-8.
41      *
42      * @param url backing {@link URL}
43      */
44     public URLYangTextSource(final URL url) {
45         this(SourceIdentifier.ofYangFileName(extractFileName(url.getPath())), url, StandardCharsets.UTF_8);
46     }
47
48     @Override
49     public final Reader openStream() throws IOException {
50         return new InputStreamReader(url.openStream(), charset);
51     }
52
53     @Override
54     public final @NonNull String symbolicName() {
55         return url.toString();
56     }
57
58     @Override
59     public final URL getDelegate() {
60         return url;
61     }
62
63     @Override
64     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
65         return super.addToStringAttributes(toStringHelper).add("url", url);
66     }
67
68     private static String extractFileName(final String path) {
69         return path.substring(path.lastIndexOf('/') + 1);
70     }
71 }