Do not pretty-print body class
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / AnydataNodeDataWithSchema.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.yang.data.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import java.io.IOException;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.yangtools.rfc7952.data.api.StreamWriterMetadataExtension;
18 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
19 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
20
21 @Beta
22 public class AnydataNodeDataWithSchema extends SimpleNodeDataWithSchema<AnydataSchemaNode> {
23     private Class<?> objectModel;
24
25     public AnydataNodeDataWithSchema(final AnydataSchemaNode dataSchemaNode) {
26         super(dataSchemaNode);
27     }
28
29     public AnydataNodeDataWithSchema(final AnydataSchemaNode dataSchemaNode, final Class<?> objectModel) {
30         super(dataSchemaNode);
31         this.objectModel = requireNonNull(objectModel);
32     }
33
34     @Override
35     public Object getValue() {
36         return getObjectModel().cast(super.getValue());
37     }
38
39     @Override
40     public void setValue(final Object value) {
41         final Class<?> clazz = getObjectModel();
42         checkArgument(clazz.isInstance(value), "Value %s is not compatible with %s", clazz);
43         super.setValue(value);
44     }
45
46     @Override
47     protected void write(final NormalizedNodeStreamWriter writer, final StreamWriterMetadataExtension metaWriter)
48             throws IOException {
49         writer.nextDataSchemaNode(getSchema());
50         if (writer.startAnydataNode(provideNodeIdentifier(), getObjectModel())) {
51             writer.scalarValue(getValue());
52             writer.endNode();
53         }
54     }
55
56     public final @NonNull Class<?> getObjectModel() {
57         checkState(objectModel != null, "Object model not set");
58         return objectModel;
59     }
60
61     public void setObjectModel(final Class<?> newObjectModel) {
62         checkState(objectModel == null, "Object model already set to %s", objectModel);
63         objectModel = requireNonNull(newObjectModel);
64     }
65 }