2 * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.schema;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.ImmutableMap;
15 import java.io.IOException;
16 import java.util.ArrayDeque;
17 import java.util.Deque;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedMetadata;
23 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter.MetadataExtension;
24 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedMetadata.Builder;
27 * A simple {@link MetadataExtension} implementation, which takes care of building {@link NormalizedMetadata} based on
28 * additional nesting instructions.
31 public final class ImmutableMetadataExtension implements MetadataExtension {
33 private record BuilderEntry(PathArgument identifier, Builder builder) {
35 requireNonNull(identifier);
36 requireNonNull(builder);
40 private final Deque<BuilderEntry> builders = new ArrayDeque<>();
42 private ImmutableNormalizedMetadata result;
44 public void enter(final PathArgument identifier) {
46 builders.push(new BuilderEntry(identifier, ImmutableNormalizedMetadata.builder()));
52 final var last = builders.pop();
53 final var metadata = last.builder.build();
54 final var current = builders.peek();
55 if (current != null) {
56 if (!metadata.getAnnotations().isEmpty() || !metadata.getChildren().isEmpty()) {
57 current.builder().withChild(last.identifier, metadata);
64 public Optional<NormalizedMetadata> getResult() {
65 checkState(result != null, "Metadata tree has not been completely built");
66 return result.getAnnotations().isEmpty() ? Optional.empty() : Optional.of(result);
70 public void metadata(final ImmutableMap<QName, Object> metadata) throws IOException {
71 builders.peek().builder.withAnnotations(metadata);
74 private void checkNotDone() {
75 checkState(result != null, "Metadata already completed");