Merge "fix failure during connecting device when channelActive happens later than...
[netconf.git] / netconf / yanglib / src / main / java / org / opendaylight / yanglib / impl / YangLibServiceImpl.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.yanglib.impl;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.io.ByteStreams;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.io.IOException;
15 import java.nio.charset.Charset;
16 import java.util.concurrent.ExecutionException;
17 import org.opendaylight.yanglib.api.YangLibService;
18 import org.opendaylight.yangtools.yang.common.Revision;
19 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
20 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
21 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
22 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Provides schema sources from yang library.
28  */
29 public class YangLibServiceImpl implements YangLibService {
30     private static final Logger LOG = LoggerFactory.getLogger(YangLibServiceImpl.class);
31
32     private static volatile SchemaRepository schemaRepository;
33
34     public YangLibServiceImpl() {
35
36     }
37
38     public static void setSchemaRepository(final SchemaRepository schemaRepository) {
39         LOG.debug("Setting schema repository {}", schemaRepository);
40         YangLibServiceImpl.schemaRepository = schemaRepository;
41     }
42
43     @Override
44     public String getSchema(final String name, final String revision) {
45         Preconditions.checkNotNull(schemaRepository, "Schema repository is not initialized");
46         LOG.debug("Attempting load for schema source {}:{}", name, revision);
47         final SourceIdentifier sourceId = RevisionSourceIdentifier.create(name,
48             revision.isEmpty() ? null : Revision.of(revision));
49
50         final ListenableFuture<YangTextSchemaSource> sourceFuture = schemaRepository.getSchemaSource(sourceId,
51             YangTextSchemaSource.class);
52
53         try {
54             final YangTextSchemaSource source = sourceFuture.get();
55             return new String(ByteStreams.toByteArray(source.openStream()), Charset.defaultCharset());
56         } catch (InterruptedException | ExecutionException | IOException e) {
57             throw new IllegalStateException("Unable to get schema " + sourceId, e);
58         }
59     }
60 }