Share common parts of AbstractNormalizedNodeBodyWriter
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / AbstractNormalizedNodeBodyWriter.java
1 /*
2  * Copyright (c) 2021 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.restconf.nb.rfc8040.jersey.providers;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.core.MultivaluedMap;
18 import javax.ws.rs.ext.MessageBodyWriter;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.restconf.nb.rfc8040.legacy.InstanceIdentifierContext;
21 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
22 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24
25 abstract class AbstractNormalizedNodeBodyWriter implements MessageBodyWriter<NormalizedNodePayload> {
26     @Override
27     public final boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
28             final MediaType mediaType) {
29         return type.equals(NormalizedNodePayload.class);
30     }
31
32     @Override
33     public final void writeTo(final NormalizedNodePayload context, final Class<?> type, final Type genericType,
34             final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
35             final OutputStream entityStream) throws IOException {
36         final var data = context.getData();
37         if (data == null) {
38             return;
39         }
40         if (httpHeaders != null) {
41             for (var entry : context.getNewHeaders().entrySet()) {
42                 httpHeaders.add(entry.getKey(), entry.getValue());
43             }
44         }
45
46         writeTo(context.getInstanceIdentifierContext(), context.getWriterParameters(), data,
47             requireNonNull(entityStream));
48     }
49
50     abstract void writeTo(@NonNull InstanceIdentifierContext context, @NonNull QueryParameters writerParameters,
51         @NonNull NormalizedNode data, @NonNull OutputStream entityStream) throws IOException;
52 }