Merge "Bug 9092: revert to org.json temporarily"
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / utils / parser / ParserIdentifier.java
1 /*
2  * Copyright (c) 2016 Cisco 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.restconf.utils.parser;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.Iterables;
13 import java.text.ParseException;
14 import java.util.Date;
15 import java.util.Iterator;
16 import java.util.List;
17 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
18 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
19 import org.opendaylight.netconf.md.sal.rest.schema.SchemaExportContext;
20 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
21 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
22 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
23 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
24 import org.opendaylight.restconf.parser.IdentifierCodec;
25 import org.opendaylight.restconf.utils.RestconfConstants;
26 import org.opendaylight.restconf.utils.validation.RestconfValidation;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
31 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Util class for parsing identifier.
41  */
42 public final class ParserIdentifier {
43
44     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
45
46     private ParserIdentifier() {
47         throw new UnsupportedOperationException("Util class.");
48     }
49
50     /**
51      * Make {@link InstanceIdentifierContext} from {@link String} identifier
52      * <br>
53      * For identifiers of data NOT behind mount points returned
54      * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
55      * controller's {@link SchemaContext}.
56      * <br>
57      * For identifiers of data behind mount points returned
58      * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
59      * own {@link SchemaContext}.
60      *
61      * @param identifier
62      *           - path identifier
63      * @param schemaContext
64      *           - controller schema context
65      * @param mountPointService
66      *           - mount point service
67      * @return {@link InstanceIdentifierContext}
68      */
69     public static InstanceIdentifierContext<?> toInstanceIdentifier(
70             final String identifier,
71             final SchemaContext schemaContext,
72             final Optional<DOMMountPointService> mountPointService) {
73         if (identifier != null && identifier.contains(RestconfConstants.MOUNT)) {
74             if (!mountPointService.isPresent()) {
75                 throw new RestconfDocumentedException("Mount point service is not available");
76             }
77
78             final Iterator<String> pathsIt = Splitter.on("/" + RestconfConstants.MOUNT).split(identifier).iterator();
79
80             final String mountPointId = pathsIt.next();
81             final YangInstanceIdentifier mountYangInstanceIdentifier = IdentifierCodec.deserialize(
82                     mountPointId, schemaContext);
83             final Optional<DOMMountPoint> mountPoint =
84                     mountPointService.get().getMountPoint(mountYangInstanceIdentifier);
85
86             if (!mountPoint.isPresent()) {
87                 throw new RestconfDocumentedException(
88                         "Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
89             }
90
91             final DOMMountPoint domMountPoint = mountPoint.get();
92             final SchemaContext mountSchemaContext = domMountPoint.getSchemaContext();
93
94             final String pathId = pathsIt.next().replaceFirst("/", "");
95             final YangInstanceIdentifier pathYangInstanceIdentifier = IdentifierCodec.deserialize(
96                     pathId, mountSchemaContext);
97
98             final DataSchemaContextNode<?> child = DataSchemaContextTree.from(mountSchemaContext)
99                 .getChild(pathYangInstanceIdentifier);
100             if (child != null) {
101                 return new InstanceIdentifierContext<SchemaNode>(pathYangInstanceIdentifier, child.getDataSchemaNode(),
102                         domMountPoint, mountSchemaContext);
103             }
104             final QName rpcQName = pathYangInstanceIdentifier.getLastPathArgument().getNodeType();
105             RpcDefinition def = null;
106             for (final RpcDefinition rpcDefinition : mountSchemaContext
107                     .findModuleByNamespaceAndRevision(rpcQName.getNamespace(), rpcQName.getRevision()).getRpcs()) {
108                 if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
109                     def = rpcDefinition;
110                     break;
111                 }
112             }
113             return new InstanceIdentifierContext<>(pathYangInstanceIdentifier, def, domMountPoint, mountSchemaContext);
114         } else {
115             final YangInstanceIdentifier deserialize = IdentifierCodec.deserialize(identifier, schemaContext);
116             final DataSchemaContextNode<?> child = DataSchemaContextTree.from(schemaContext).getChild(deserialize);
117
118             if (child != null) {
119                 return new InstanceIdentifierContext<SchemaNode>(
120                             deserialize, child.getDataSchemaNode(), null, schemaContext);
121             }
122             final QName rpcQName = deserialize.getLastPathArgument().getNodeType();
123             RpcDefinition def = null;
124             for (final RpcDefinition rpcDefinition
125                     : schemaContext.findModuleByNamespaceAndRevision(rpcQName.getNamespace(),
126                         rpcQName.getRevision()).getRpcs()) {
127                 if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
128                     def = rpcDefinition;
129                     break;
130                 }
131             }
132             return new InstanceIdentifierContext<>(deserialize, def, null, schemaContext);
133         }
134     }
135
136     /**
137      * Make {@link String} from {@link YangInstanceIdentifier}.
138      *
139      * @param instanceIdentifier    Instance identifier
140      * @param schemaContext         Schema context
141      * @return                      Yang instance identifier serialized to String
142      */
143     public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
144             final SchemaContext schemaContext) {
145         return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
146     }
147
148     /**
149      * Make a {@link QName} from identifier.
150      *
151      * @param identifier
152      *             path parameter
153      * @return {@link QName}
154      */
155     public static QName makeQNameFromIdentifier(final String identifier) {
156         // check if more than one slash is not used as path separator
157         if (identifier.contains(
158                 String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
159             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
160             throw new RestconfDocumentedException(
161                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
162                     ErrorTag.INVALID_VALUE);
163         }
164
165         final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
166         final String moduleNameAndRevision;
167         if (mountIndex >= 0) {
168             moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
169                     .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
170         } else {
171             moduleNameAndRevision = identifier;
172         }
173
174         final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
175         if (pathArgs.size() != 2) {
176             LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
177             throw new RestconfDocumentedException(
178                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
179                     ErrorTag.INVALID_VALUE);
180         }
181
182         final Date moduleRevision;
183         try {
184             moduleRevision = SimpleDateFormatUtil.getRevisionFormat().parse(pathArgs.get(1));
185         } catch (final ParseException e) {
186             LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
187             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
188                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
189         }
190
191         return QName.create(null, moduleRevision, pathArgs.get(0));
192     }
193
194     /**
195      * Parsing {@link Module} module by {@link String} module name and
196      * {@link Date} revision and from the parsed module create
197      * {@link SchemaExportContext}.
198      *
199      * @param schemaContext
200      *             {@link SchemaContext}
201      * @param identifier
202      *             path parameter
203      * @param domMountPointService
204      *             {@link DOMMountPointService}
205      * @return {@link SchemaExportContext}
206      */
207     public static SchemaExportContext toSchemaExportContextFromIdentifier(final SchemaContext schemaContext,
208             final String identifier, final DOMMountPointService domMountPointService) {
209         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
210         final Iterator<String> componentIter = pathComponents.iterator();
211         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
212             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
213             final Date revision = RestconfValidation.validateAndGetRevision(componentIter);
214             final Module module = schemaContext.findModuleByName(moduleName, revision);
215             return new SchemaExportContext(schemaContext, module);
216         } else {
217             final StringBuilder pathBuilder = new StringBuilder();
218             while (componentIter.hasNext()) {
219                 final String current = componentIter.next();
220
221                 if (RestconfConstants.MOUNT.equals(current)) {
222                     pathBuilder.append("/");
223                     pathBuilder.append(RestconfConstants.MOUNT);
224                     break;
225                 }
226
227                 if (pathBuilder.length() != 0) {
228                     pathBuilder.append("/");
229                 }
230
231                 pathBuilder.append(current);
232             }
233             final InstanceIdentifierContext<?> point = ParserIdentifier
234                     .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
235             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
236             final Date revision = RestconfValidation.validateAndGetRevision(componentIter);
237             final Module module = point.getMountPoint().getSchemaContext().findModuleByName(moduleName, revision);
238             return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module);
239         }
240     }
241 }