Mass-migrate binding-dom-codec to IllegalArgumentCodec
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / 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.mdsal.binding.dom.codec.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.Iterables;
13 import java.util.ArrayList;
14 import java.util.List;
15 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
16 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
17 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20
21 // FIXME: this is not really an IllegalArgumentCodec, as it can legally return null from deserialize()
22 final class InstanceIdentifierCodec implements IllegalArgumentCodec<YangInstanceIdentifier, InstanceIdentifier<?>> {
23     private final BindingCodecContext context;
24
25     InstanceIdentifierCodec(final BindingCodecContext context) {
26         this.context = requireNonNull(context);
27     }
28
29     @Override
30     public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
31         final List<PathArgument> domArgs = new ArrayList<>();
32         context.getCodecContextNode(input, domArgs);
33         return YangInstanceIdentifier.create(domArgs);
34     }
35
36     @Override
37     public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
38         final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
39         final BindingDataObjectCodecTreeNode<?> codec = context.getCodecContextNode(input, builder);
40         if (codec == null) {
41             return null;
42         }
43         if (codec instanceof ListNodeCodecContext && Iterables.getLast(builder) instanceof InstanceIdentifier.Item) {
44             // We ended up in list, but without key, which means it represent list as a whole,
45             // which is not binding representable.
46             return null;
47         }
48         return InstanceIdentifier.create(builder);
49     }
50 }