2 * Copyright (c) 2015 Cisco Systems, Inc. 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.netconf.sal.connect.netconf.schema;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.Optional;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.io.ByteStreams;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import java.io.IOException;
19 import java.io.InputStream;
21 import java.nio.charset.Charset;
23 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource;
24 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
25 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
26 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
27 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
28 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Provides YANG schema sources from yang library.
35 public final class YangLibrarySchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
37 private static final Logger LOG = LoggerFactory.getLogger(YangLibrarySchemaYangSourceProvider.class);
39 private final Map<SourceIdentifier, URL> availableSources;
40 private final RemoteDeviceId id;
42 public YangLibrarySchemaYangSourceProvider(final RemoteDeviceId id,
43 final Map<SourceIdentifier, URL> availableSources) {
45 this.availableSources = ImmutableMap.copyOf(availableSources);
49 public ListenableFuture<? extends YangTextSchemaSource> getSource(final SourceIdentifier sourceIdentifier) {
50 final URL url = availableSources.get(requireNonNull(sourceIdentifier));
51 checkArgument(url != null);
52 try (InputStream in = url.openStream()) {
53 // FIXME: defaultCharset() seems to be wrong here
54 final String schemaContent = new String(ByteStreams.toByteArray(in), Charset.defaultCharset());
55 final NetconfYangTextSchemaSource yangSource = new NetconfYangTextSchemaSource(id, sourceIdentifier,
56 Optional.of(schemaContent));
57 LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url);
58 return Futures.immediateFuture(yangSource);
59 } catch (IOException e) {
60 LOG.warn("Unable to download source {} from a yang library's url {}", sourceIdentifier, url, e);
61 return Futures.immediateFailedFuture(new SchemaSourceException(
62 "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));