BUG-8004: handle implicit RPC input
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / InstanceIdentifierCodec.java
1 /*
2  * Copyright (c) 2015 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 package org.opendaylight.yangtools.binding.data.codec.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Iterables;
12 import java.util.ArrayList;
13 import java.util.List;
14 import org.opendaylight.yangtools.concepts.Codec;
15 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18
19 final class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
20     private final BindingCodecContext context;
21
22     InstanceIdentifierCodec(final BindingCodecContext context) {
23         this.context = Preconditions.checkNotNull(context);
24     }
25
26     @Override
27     public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
28         final List<PathArgument> domArgs = new ArrayList<>();
29         context.getCodecContextNode(input, domArgs);
30         return YangInstanceIdentifier.create(domArgs);
31     }
32
33     @Override
34     public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
35         final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
36         final NodeCodecContext<?> codec = context.getCodecContextNode(input, builder);
37         if (codec == null) {
38             return null;
39         }
40         if (codec instanceof ListNodeCodecContext && Iterables.getLast(builder) instanceof InstanceIdentifier.Item) {
41             // We ended up in list, but without key, which means it represent list as a whole,
42             // which is not binding representable.
43             return null;
44         }
45         return InstanceIdentifier.create(builder);
46     }
47 }