Move OperationsContent
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / OperationsContent.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.rests.services.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.HashBasedTable;
13 import java.util.ArrayList;
14 import java.util.Comparator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Optional;
19 import java.util.stream.Collectors;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.yangtools.yang.common.Revision;
23 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
24 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
26
27 /**
28  * RESTCONF {@code /operations} content for a {@code GET} operation as per
29  * <a href="https://datatracker.ietf.org/doc/html/rfc8040#section-3.3.2">RFC8040</a>.
30  */
31 enum OperationsContent {
32     JSON("{ \"ietf-restconf:operations\" : { } }") {
33         @Override
34         String createBody(final List<Entry<String, List<String>>> rpcsByPrefix) {
35             final var sb = new StringBuilder("{\n"
36                 + "  \"ietf-restconf:operations\" : {\n");
37             var entryIt = rpcsByPrefix.iterator();
38             var entry = entryIt.next();
39             var nameIt = entry.getValue().iterator();
40             while (true) {
41                 sb.append("    \"").append(entry.getKey()).append(':').append(nameIt.next()).append("\": [null]");
42                 if (nameIt.hasNext()) {
43                     sb.append(",\n");
44                     continue;
45                 }
46
47                 if (entryIt.hasNext()) {
48                     sb.append(",\n");
49                     entry = entryIt.next();
50                     nameIt = entry.getValue().iterator();
51                     continue;
52                 }
53
54                 break;
55             }
56
57             return sb.append("\n  }\n}").toString();
58         }
59
60         @Override
61         String prefix(final ModuleEffectiveStatement module) {
62             return module.argument().getLocalName();
63         }
64     },
65
66     XML("<operations xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"/>") {
67         @Override
68         String createBody(final List<Entry<String, List<String>>> rpcsByPrefix) {
69             // Header with namespace declarations for each module
70             final var sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
71                 + "<operations xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\"");
72             for (int i = 0; i < rpcsByPrefix.size(); ++i) {
73                 final var prefix = "ns" + i;
74                 sb.append("\n            xmlns:").append(prefix).append("=\"").append(rpcsByPrefix.get(i).getKey())
75                     .append("\"");
76             }
77             sb.append(" >");
78
79             // Second pass: emit all leaves
80             for (int i = 0; i < rpcsByPrefix.size(); ++i) {
81                 final var prefix = "ns" + i;
82                 for (var localName : rpcsByPrefix.get(i).getValue()) {
83                     sb.append("\n  <").append(prefix).append(':').append(localName).append("/>");
84                 }
85             }
86
87             return sb.append("\n</operations>").toString();
88         }
89
90         @Override
91         String prefix(final ModuleEffectiveStatement module) {
92             return module.localQNameModule().getNamespace().toString();
93         }
94     };
95
96     private final @NonNull String emptyBody;
97
98     OperationsContent(final String emptyBody) {
99         this.emptyBody = requireNonNull(emptyBody);
100     }
101
102     /**
103      * Return the content for a particular {@link EffectiveModelContext}.
104      *
105      * @param context Context to use
106      * @return Content of HTTP GET operation as a String
107      */
108     public final @NonNull String bodyFor(final @Nullable EffectiveModelContext context) {
109         if (context == null) {
110             return emptyBody;
111         }
112         final var modules = context.getModuleStatements();
113         if (modules.isEmpty()) {
114             return emptyBody;
115         }
116
117         // Index into prefix -> revision -> module table
118         final var prefixRevModule = HashBasedTable.<String, Optional<Revision>, ModuleEffectiveStatement>create();
119         for (var module : modules.values()) {
120             prefixRevModule.put(prefix(module), module.localQNameModule().getRevision(), module);
121         }
122
123         // Now extract RPC names for each module with highest revision. This needed so we expose the right set of RPCs,
124         // as we always pick the latest revision to resolve prefix (or module name)
125         // TODO: Simplify this once we have yangtools-7.0.9+
126         final var moduleRpcs = new ArrayList<Entry<String, List<String>>>();
127         for (var moduleEntry : prefixRevModule.rowMap().entrySet()) {
128             final var revisions = new ArrayList<>(moduleEntry.getValue().keySet());
129             revisions.sort(Revision::compare);
130             final var selectedRevision = revisions.get(revisions.size() - 1);
131
132             final var rpcNames = moduleEntry.getValue().get(selectedRevision)
133                 .streamEffectiveSubstatements(RpcEffectiveStatement.class)
134                 .map(rpc -> rpc.argument().getLocalName())
135                 .collect(Collectors.toUnmodifiableList());
136             if (!rpcNames.isEmpty()) {
137                 moduleRpcs.add(Map.entry(moduleEntry.getKey(), rpcNames));
138             }
139         }
140
141         if (moduleRpcs.isEmpty()) {
142             // No RPCs, return empty content
143             return emptyBody;
144         }
145
146         // Ensure stability: sort by prefix
147         moduleRpcs.sort(Comparator.comparing(Entry::getKey));
148
149         return modules.isEmpty() ? emptyBody : createBody(moduleRpcs);
150     }
151
152     abstract @NonNull String createBody(List<Entry<String, List<String>>> rpcsByPrefix);
153
154     abstract @NonNull String prefix(ModuleEffectiveStatement module);
155 }