Do not leak SpotBugs from yang-binding
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / DoNotLeakSpotbugs.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.yang.binding;
9
10 import static java.util.Objects.requireNonNull;
11
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.util.Collection;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.eclipse.jdt.annotation.Nullable;
16
17 /**
18  * Utility methods to hide operations that incur SpotBugs wrath used by public classes where we do not want to leak
19  * {@link SuppressFBWarnings}.
20  */
21 final class DoNotLeakSpotbugs {
22     private DoNotLeakSpotbugs() {
23         // Hidden on purpose
24     }
25
26     @SuppressFBWarnings(value = "DCN_NULLPOINTER_EXCEPTION", justification = "Internal NPE->IAE conversion")
27     static void checkCollectionField(final @NonNull Class<?> requiredClass, final @NonNull String fieldName,
28             final @Nullable Collection<?> collection) {
29         if (collection != null) {
30             try {
31                 collection.forEach(item -> requiredClass.cast(requireNonNull(item)));
32             } catch (ClassCastException | NullPointerException e) {
33                 throw new IllegalArgumentException(
34                     "Invalid input item for property \"" + requireNonNull(fieldName) + "\"", e);
35             }
36         }
37     }
38 }