Add 'features/protocol-framework/' from commit 'cb42405784db97d0ce2c5991d12a89b46d185949'
[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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.io.ByteStreams;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import java.io.IOException;
16 import org.opendaylight.yanglib.api.YangLibService;
17 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
18 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
19 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
20 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
21 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26  * Provides schema sources from yang library.
27  */
28 public class YangLibServiceImpl implements YangLibService {
29     private static final Logger LOG = LoggerFactory.getLogger(YangLibServiceImpl.class);
30
31     private volatile SchemaRepository schemaRepository;
32
33     public YangLibServiceImpl() {
34
35     }
36
37     public void setSchemaRepository(final SchemaRepository schemaRepository) {
38         LOG.debug("Setting schema repository {}", schemaRepository);
39         this.schemaRepository = schemaRepository;
40     }
41
42     @Override
43     public String getSchema(final String name, final String revision) {
44         Preconditions.checkNotNull(schemaRepository, "Schema repository is not initialized");
45         LOG.debug("Attempting load for schema source {}:{}", name, revision);
46         final SourceIdentifier sourceId =
47                 RevisionSourceIdentifier.create(name, Optional.fromNullable(revision.equals("") ? null : revision));
48
49         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> sourceFuture =
50                 schemaRepository.getSchemaSource(sourceId, YangTextSchemaSource.class);
51
52         try {
53             final YangTextSchemaSource source = sourceFuture.checkedGet();
54             return new String(ByteStreams.toByteArray(source.openStream()));
55         } catch (SchemaSourceException | IOException e) {
56             throw new IllegalStateException("Unable to get schema" + sourceId, e);
57         }
58     }
59 }