Merge "Bug 8351: Enforce check-style rules for restconf - sal-rest-docgen"
[netconf.git] / restconf / sal-rest-docgen / src / main / java / org / opendaylight / netconf / sal / rest / doc / mountpoints / MountPointSwagger.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. 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.netconf.sal.rest.doc.mountpoints;
9
10 import com.google.common.base.Optional;
11 import java.util.Collections;
12 import java.util.HashMap;
13 import java.util.LinkedList;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Map.Entry;
17 import java.util.TreeMap;
18 import java.util.concurrent.atomic.AtomicLong;
19 import java.util.concurrent.atomic.AtomicReference;
20 import javax.ws.rs.core.UriInfo;
21 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
22 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
23 import org.opendaylight.controller.sal.core.api.model.SchemaService;
24 import org.opendaylight.controller.sal.core.api.mount.MountProvisionListener;
25 import org.opendaylight.netconf.sal.rest.doc.impl.BaseYangSwaggerGenerator;
26 import org.opendaylight.netconf.sal.rest.doc.swagger.Api;
27 import org.opendaylight.netconf.sal.rest.doc.swagger.ApiDeclaration;
28 import org.opendaylight.netconf.sal.rest.doc.swagger.Operation;
29 import org.opendaylight.netconf.sal.rest.doc.swagger.Resource;
30 import org.opendaylight.netconf.sal.rest.doc.swagger.ResourceList;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37
38 public class MountPointSwagger extends BaseYangSwaggerGenerator implements MountProvisionListener {
39
40     private static final String DATASTORES_REVISION = "-";
41     private static final String DATASTORES_LABEL = "Datastores";
42     private static final String RESTCONF_DRAFT = "18";
43     private static final AtomicReference<MountPointSwagger> SELF_REF = new AtomicReference<>();
44
45     private DOMMountPointService mountService;
46     private final Map<YangInstanceIdentifier, Long> instanceIdToLongId =
47             new TreeMap<>((o1, o2) -> o1.toString().compareToIgnoreCase(o2.toString()));
48     private final Map<Long, YangInstanceIdentifier> longIdToInstanceId = new HashMap<>();
49
50     private final Object lock = new Object();
51
52     private final AtomicLong idKey = new AtomicLong(0);
53     private SchemaService globalSchema;
54     private static boolean newDraft;
55
56     public Map<String, Long> getInstanceIdentifiers() {
57         final Map<String, Long> urlToId = new HashMap<>();
58         synchronized (this.lock) {
59             final SchemaContext context = this.globalSchema.getGlobalContext();
60             for (final Entry<YangInstanceIdentifier, Long> entry : this.instanceIdToLongId.entrySet()) {
61                 final String modName = findModuleName(entry.getKey(), context);
62                 urlToId.put(generateUrlPrefixFromInstanceID(entry.getKey(), modName), entry.getValue());
63             }
64         }
65         return urlToId;
66     }
67
68     public void setGlobalSchema(final SchemaService globalSchema) {
69         this.globalSchema = globalSchema;
70     }
71
72     private String findModuleName(final YangInstanceIdentifier id, final SchemaContext context) {
73         final PathArgument rootQName = id.getPathArguments().iterator().next();
74         for (final Module mod : context.getModules()) {
75             if (mod.getDataChildByName(rootQName.getNodeType()) != null) {
76                 return mod.getName();
77             }
78         }
79         return null;
80     }
81
82     private String generateUrlPrefixFromInstanceID(final YangInstanceIdentifier key, final String moduleName) {
83         final StringBuilder builder = new StringBuilder();
84         builder.append("/");
85         if (moduleName != null) {
86             builder.append(moduleName).append(':');
87         }
88         for (final PathArgument arg : key.getPathArguments()) {
89             final String name = arg.getNodeType().getLocalName();
90             if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
91                 final NodeIdentifierWithPredicates nodeId = (NodeIdentifierWithPredicates) arg;
92                 for (final Entry<QName, Object> entry : nodeId.getKeyValues().entrySet()) {
93                     if (newDraft) {
94                         builder.deleteCharAt(builder.length() - 1).append("=").append(entry.getValue()).append('/');
95                     } else {
96                         builder.append(entry.getValue()).append('/');
97                     }
98                 }
99             } else {
100                 builder.append(name).append('/');
101             }
102         }
103         return builder.toString();
104     }
105
106     private String getYangMountUrl(final YangInstanceIdentifier key) {
107         final String modName = findModuleName(key, this.globalSchema.getGlobalContext());
108         return generateUrlPrefixFromInstanceID(key, modName) + "yang-ext:mount";
109     }
110
111     public ResourceList getResourceList(final UriInfo uriInfo, final Long id) {
112         final YangInstanceIdentifier iid = getInstanceId(id);
113         if (iid == null) {
114             return null; // indicating not found.
115         }
116         final SchemaContext context = getSchemaContext(iid);
117         if (context == null) {
118             return createResourceList();
119         }
120         final List<Resource> resources = new LinkedList<>();
121         final Resource dataStores = new Resource();
122         dataStores.setDescription("Provides methods for accessing the data stores.");
123         dataStores.setPath(generatePath(uriInfo, DATASTORES_LABEL, DATASTORES_REVISION));
124         resources.add(dataStores);
125         final String urlPrefix = getYangMountUrl(iid);
126         final ResourceList list = super.getResourceListing(uriInfo, context, urlPrefix);
127         resources.addAll(list.getApis());
128         list.setApis(resources);
129         return list;
130     }
131
132     private YangInstanceIdentifier getInstanceId(final Long id) {
133         final YangInstanceIdentifier instanceId;
134         synchronized (this.lock) {
135             instanceId = this.longIdToInstanceId.get(id);
136         }
137         return instanceId;
138     }
139
140     private SchemaContext getSchemaContext(final YangInstanceIdentifier id) {
141
142         if (id == null) {
143             return null;
144         }
145
146         final Optional<DOMMountPoint> mountPoint = this.mountService.getMountPoint(id);
147         if (!mountPoint.isPresent()) {
148             return null;
149         }
150
151         final SchemaContext context = mountPoint.get().getSchemaContext();
152         if (context == null) {
153             return null;
154         }
155         return context;
156     }
157
158     public ApiDeclaration getMountPointApi(final UriInfo uriInfo, final Long id, final String module,
159             final String revision) {
160         final YangInstanceIdentifier iid = getInstanceId(id);
161         final SchemaContext context = getSchemaContext(iid);
162         final String urlPrefix = getYangMountUrl(iid);
163         if (context == null) {
164             return null;
165         }
166
167         if (DATASTORES_LABEL.equals(module) && DATASTORES_REVISION.equals(revision)) {
168             return generateDataStoreApiDoc(uriInfo, urlPrefix);
169         }
170         return super.getApiDeclaration(module, revision, uriInfo, context, urlPrefix);
171     }
172
173     private ApiDeclaration generateDataStoreApiDoc(final UriInfo uriInfo, final String context) {
174         final List<Api> apis = new LinkedList<>();
175         apis.add(createGetApi("config", "Queries the config (startup) datastore on the mounted hosted.", context));
176         apis.add(createGetApi("operational", "Queries the operational (running) datastore on the mounted hosted.",
177                 context));
178         apis.add(createGetApi("operations", "Queries the available operations (RPC calls) on the mounted hosted.",
179                 context));
180
181         final ApiDeclaration declaration = super.createApiDeclaration(createBasePathFromUriInfo(uriInfo));
182         declaration.setApis(apis);
183         return declaration;
184
185     }
186
187     private Api createGetApi(final String datastore, final String note, final String context) {
188         final Operation getConfig = new Operation();
189         getConfig.setMethod("GET");
190         getConfig.setNickname("GET " + datastore);
191         getConfig.setNotes(note);
192
193         final Api api = new Api();
194         api.setPath(getDataStorePath(datastore, context).concat(getContent(datastore)));
195         api.setOperations(Collections.singletonList(getConfig));
196
197         return api;
198     }
199
200     public void setMountService(final DOMMountPointService mountService) {
201         this.mountService = mountService;
202     }
203
204     @Override
205     public void onMountPointCreated(final YangInstanceIdentifier path) {
206         synchronized (this.lock) {
207             final Long idLong = this.idKey.incrementAndGet();
208             this.instanceIdToLongId.put(path, idLong);
209             this.longIdToInstanceId.put(idLong, path);
210         }
211     }
212
213     @Override
214     public void onMountPointRemoved(final YangInstanceIdentifier path) {
215         synchronized (this.lock) {
216             final Long id = this.instanceIdToLongId.remove(path);
217             this.longIdToInstanceId.remove(id);
218         }
219     }
220
221     public static MountPointSwagger getInstance() {
222         MountPointSwagger swagger = SELF_REF.get();
223         if (swagger == null) {
224             SELF_REF.compareAndSet(null, new MountPointSwagger());
225             swagger = SELF_REF.get();
226         }
227         newDraft = false;
228         return swagger;
229     }
230
231     public static MountPointSwagger getInstanceDraft18() {
232         MountPointSwagger swagger = SELF_REF.get();
233         if (swagger == null) {
234             SELF_REF.compareAndSet(null, new MountPointSwagger());
235             swagger = SELF_REF.get();
236         }
237         newDraft = true;
238         return swagger;
239     }
240 }