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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.io.ByteStreams;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.io.IOException;
16 import java.io.InputStream;
18 import java.nio.charset.Charset;
20 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
21 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
22 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
23 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
24 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Provides YANG schema sources from yang library.
31 public final class YangLibrarySchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
33 private static final Logger LOG = LoggerFactory.getLogger(YangLibrarySchemaYangSourceProvider.class);
35 private final Map<SourceIdentifier, URL> availableSources;
36 private final RemoteDeviceId id;
38 public YangLibrarySchemaYangSourceProvider(
39 final RemoteDeviceId id, final Map<SourceIdentifier, URL> availableSources) {
41 this.availableSources = Preconditions.checkNotNull(availableSources);
45 public ListenableFuture<? extends YangTextSchemaSource> getSource(
46 final SourceIdentifier sourceIdentifier) {
47 Preconditions.checkNotNull(sourceIdentifier);
48 Preconditions.checkArgument(availableSources.containsKey(sourceIdentifier));
49 return download(sourceIdentifier);
52 private ListenableFuture<? extends YangTextSchemaSource> download(final SourceIdentifier sourceIdentifier) {
53 final URL url = availableSources.get(sourceIdentifier);
54 try (InputStream in = url.openStream()) {
55 final String schemaContent = new String(ByteStreams.toByteArray(in), Charset.defaultCharset());
56 final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource =
57 new NetconfRemoteSchemaYangSourceProvider
58 .NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
59 LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url);
60 return Futures.immediateFuture(yangSource);
61 } catch (IOException e) {
62 LOG.warn("Unable to download source {} from a yang library's url {}", sourceIdentifier, url, e);
63 return Futures.immediateFailedFuture(new SchemaSourceException(
64 "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));