Merge changes from topic 'keyauth-refactor'
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / NetconfKeystoreAdapter.java
1 /*
2  * Copyright (c) 2017 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.netconf.sal.connect.netconf.sal;
10
11 import java.util.Collection;
12 import java.util.Collections;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.Optional;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
20 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.keystore.entry.KeyCredential;
24 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 public class NetconfKeystoreAdapter implements ClusteredDataTreeChangeListener<Keystore> {
29
30     private static final Logger LOG = LoggerFactory.getLogger(NetconfKeystoreAdapter.class);
31
32     private final InstanceIdentifier<Keystore> keystoreIid = InstanceIdentifier.create(Keystore.class);
33
34     private final DataBroker dataBroker;
35     private final Map<String, KeyCredential> pairs = Collections.synchronizedMap(new HashMap<>());
36
37     public NetconfKeystoreAdapter(final DataBroker dataBroker) {
38         this.dataBroker = dataBroker;
39
40         dataBroker.registerDataTreeChangeListener(
41                 new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, keystoreIid), this);
42     }
43
44     public Optional<KeyCredential> getKeypairFromId(final String keyId) {
45         final KeyCredential keypair = pairs.get(keyId);
46         return Optional.ofNullable(keypair);
47     }
48
49     @Override
50     public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Keystore>> changes) {
51         LOG.debug("Keystore updated: {}", changes);
52         final Keystore dataAfter = changes.iterator().next().getRootNode().getDataAfter();
53
54         pairs.clear();
55         if (dataAfter != null) {
56             dataAfter.getKeyCredential().forEach(pair -> pairs.put(pair.getKey().getKeyId(), pair));
57         }
58     }
59 }