summaryrefslogtreecommitdiffstats
path: root/infra/translate-utils/src/main/java/io/fd/honeycomb/translate/util/RWUtils.java
blob: 5b0a4919edf36519909869e80e14ef8ba3a004ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/*
 * Copyright (c) 2016 Cisco and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.fd.honeycomb.translate.util;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import io.fd.honeycomb.translate.SubtreeManager;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Nonnull;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.Identifiable;
import org.opendaylight.yangtools.yang.binding.Identifier;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;

public final class RWUtils {

    // TODO HONEYCOMB-172 update the utils methods considering Java8. Make sure they still work by wiring a detailed unit test first

    private RWUtils() {}

    /**
     * Collector expecting only a single resulting item from a stream.
     */
    public static<T> Collector<T,?,T> singleItemCollector() {
        return Collectors.collectingAndThen(
                Collectors.toList(),
                list -> {
                    if (list.size() != 1) {
                        throw new IllegalStateException("Unexpected size of list: " + list + ". Single item expected");
                    }
                    return list.get(0);
                }
        );
    }

    /**
     * Find next item in ID after provided type.
     */
    @Nonnull
    public static InstanceIdentifier.PathArgument getNextId(@Nonnull final InstanceIdentifier<? extends DataObject> id,
                                                            @Nonnull final InstanceIdentifier<? extends DataObject> type) {
        final Iterable<InstanceIdentifier.PathArgument> pathArguments = id.getPathArguments();
        final int i = Iterables.indexOf(pathArguments, new Predicate<InstanceIdentifier.PathArgument>() {
            @Override
            public boolean apply(final InstanceIdentifier.PathArgument input) {
                return input.getType().isAssignableFrom(type.getTargetType());
            }
        });
        Preconditions.checkArgument(i >= 0, "Unable to find %s type in %s", type.getTargetType(), id);
        return Iterables.get(pathArguments, i + 1);
    }

    /**
     * Replace last item in ID with a provided IdentifiableItem of the same type.
     */
    @SuppressWarnings("unchecked")
    @Nonnull
    public static <D extends DataObject & Identifiable<K>, K extends Identifier<D>> InstanceIdentifier<D> replaceLastInId(
        @Nonnull final InstanceIdentifier<D> id, final InstanceIdentifier.IdentifiableItem<D, K> currentBdItem) {

        final Iterable<InstanceIdentifier.PathArgument> pathArguments = id.getPathArguments();
        final Iterable<InstanceIdentifier.PathArgument> withoutCurrent =
            Iterables.limit(pathArguments, Iterables.size(pathArguments) - 1);
        final Iterable<InstanceIdentifier.PathArgument> concat =
            Iterables.concat(withoutCurrent, Collections.singleton(currentBdItem));
        return (InstanceIdentifier<D>) InstanceIdentifier.create(concat);
    }

    /**
     * Create IdentifiableItem from target type of provided ID with provided key.
     */
    @Nonnull
    public static <D extends DataObject & Identifiable<K>, K extends Identifier<D>> InstanceIdentifier.IdentifiableItem<D, K> getCurrentIdItem(
        @Nonnull final InstanceIdentifier<D> id, final K key) {
        return new InstanceIdentifier.IdentifiableItem<>(id.getTargetType(), key);
    }

    /**
     * Trim InstanceIdentifier at indexOf(type).
     */
    @SuppressWarnings("unchecked")
    @Nonnull
    public static <D extends DataObject> InstanceIdentifier<D> cutId(@Nonnull final InstanceIdentifier<? extends DataObject> id,
                                                                     @Nonnull final InstanceIdentifier<D> type) {
        final Iterable<InstanceIdentifier.PathArgument> pathArguments = id.getPathArguments();
        final int i = Iterables.indexOf(pathArguments, new Predicate<InstanceIdentifier.PathArgument>() {
            @Override
            public boolean apply(final InstanceIdentifier.PathArgument input) {
                return input.getType().equals(type.getTargetType());
            }
        });
        Preconditions.checkArgument(i >= 0, "ID %s does not contain %s", id, type);
        return (InstanceIdentifier<D>) InstanceIdentifier.create(Iterables.limit(pathArguments, i + 1));
    }

    /**
     * Trim InstanceIdentifier at indexOf(type).
     */
    @Nonnull
    public static <D extends DataObject> InstanceIdentifier<D> cutId(@Nonnull final InstanceIdentifier<? extends DataObject> id,
                                                                     @Nonnull final Class<D> type) {
        return cutId(id, InstanceIdentifier.create(type));
    }

    /**
     * Create an ordered map from a collection, checking for duplicity in the process.
     */
    @Nonnull
    public static <K, V> Map<K, V> uniqueLinkedIndex(@Nonnull final Collection<V> values, @Nonnull final Function<? super V, K> keyFunction) {
        final Map<K, V> objectObjectLinkedHashMap = Maps.newLinkedHashMap();
        for (V value : values) {
            final K key = keyFunction.apply(value);
            Preconditions.checkArgument(objectObjectLinkedHashMap.put(key, value) == null,
                "Duplicate key detected : %s", key);
        }
        return objectObjectLinkedHashMap;
    }

    public static final Function<SubtreeManager<? extends DataObject>, Class<? extends DataObject>>
        MANAGER_CLASS_FUNCTION = new Function<SubtreeManager<? extends DataObject>, Class<? extends DataObject>>() {
        @Override
        public Class<? extends DataObject> apply(final SubtreeManager<? extends DataObject> input) {
            return input.getManagedDataObjectType().getTargetType();
        }
    };

    public static final Function<SubtreeManager<? extends Augmentation<?>>, Class<? extends DataObject>>
        MANAGER_CLASS_AUG_FUNCTION = new Function<SubtreeManager<? extends Augmentation<?>>, Class<? extends DataObject>>() {

        @Override
        @SuppressWarnings("unchecked")
        public Class<? extends DataObject> apply(final SubtreeManager<? extends Augmentation<?>> input) {
            final Class<? extends Augmentation<?>> targetType = input.getManagedDataObjectType().getTargetType();
            Preconditions.checkArgument(DataObject.class.isAssignableFrom(targetType));
            return (Class<? extends DataObject>) targetType;
        }
    };

    /**
     * Transform a keyed instance identifier into a wildcarded one.
     * <p/>
     * ! This has to be called also for wildcarded List instance identifiers
     * due to weird behavior of equals in InstanceIdentifier !
     */
    @SuppressWarnings("unchecked")
    public static <D extends DataObject> InstanceIdentifier<D> makeIidWildcarded(final InstanceIdentifier<D> id) {
        final List<InstanceIdentifier.PathArgument> transformedPathArguments =
                StreamSupport.stream(id.getPathArguments().spliterator(), false)
                        .map(RWUtils::cleanPathArgumentFromKeys)
                        .collect(Collectors.toList());
        return (InstanceIdentifier<D>) InstanceIdentifier.create(transformedPathArguments);
    }

    /**
     * Transform a keyed instance identifier into a wildcarded one, keeping keys except the last item.
     */
    @SuppressWarnings("unchecked")
    public static <D extends DataObject> InstanceIdentifier<D> makeIidLastWildcarded(final InstanceIdentifier<D> id) {
        final InstanceIdentifier.Item<D> wildcardedItem = new InstanceIdentifier.Item<>(id.getTargetType());
        final Iterable<InstanceIdentifier.PathArgument> pathArguments = id.getPathArguments();
        return (InstanceIdentifier<D>) InstanceIdentifier.create(
                Iterables.concat(
                        Iterables.limit(pathArguments, Iterables.size(pathArguments) - 1),
                        Collections.singleton(wildcardedItem)));
    }

    private static InstanceIdentifier.PathArgument cleanPathArgumentFromKeys(final InstanceIdentifier.PathArgument pathArgument) {
        return pathArgument instanceof InstanceIdentifier.IdentifiableItem<?, ?>
                ? new InstanceIdentifier.Item<>(pathArgument.getType())
                : pathArgument;
    }
}