47d4f3de7f0edf45ff12e8d86cea17887b8a909c
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / AbstractCodec.java
1 /*
2  * Copyright (c) 2019 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.concepts;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16
17 /**
18  * An abstract base class enforcing nullness contract around {@link Codec} interface.
19  *
20  * @param <P> Product type
21  * @param <I> Input type
22  * @param <X> Error exception type
23  */
24 @Beta
25 @NonNullByDefault
26 public abstract class AbstractCodec<P, I, X extends Exception> implements Codec<P, I, X> {
27     @Override
28     public final @NonNull I deserialize(@NonNull final P input) throws X {
29         return verifyNotNull(deserializeImpl(requireNonNull(input)), "Codec %s returned null on %s", this, input);
30     }
31
32     @Override
33     public final @NonNull P serialize(@NonNull final I input) throws X {
34         return verifyNotNull(serializeImpl(requireNonNull(input)), "Codec %s returned null on %s", this, input);
35     }
36
37     // implementation is guarded from nulls and verified not to return null
38     protected abstract @NonNull I deserializeImpl(@NonNull P product) throws X;
39
40     // implementation is guarded from nulls and verified not to return null
41     protected abstract @NonNull P serializeImpl(@NonNull I input) throws X;
42 }