Merge "Clean up netconf-parent root pom"
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / 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.nb.rfc8040.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.time.format.DateTimeParseException;
14 import java.util.AbstractMap.SimpleImmutableEntry;
15 import java.util.Date;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Map.Entry;
19 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
20 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
21 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
22 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
25 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
26 import org.opendaylight.restconf.common.schema.SchemaExportContext;
27 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
28 import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.Revision;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
33 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Util class for parsing identifier.
43  */
44 public final class ParserIdentifier {
45
46     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
47
48     private ParserIdentifier() {
49         throw new UnsupportedOperationException("Util class.");
50     }
51
52     /**
53      * Make {@link InstanceIdentifierContext} from {@link String} identifier
54      * <br>
55      * For identifiers of data NOT behind mount points returned
56      * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
57      * controller's {@link SchemaContext}.
58      * <br>
59      * For identifiers of data behind mount points returned
60      * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
61      * own {@link SchemaContext}.
62      *
63      * @param identifier
64      *           - path identifier
65      * @param schemaContext
66      *           - controller schema context
67      * @param mountPointService
68      *           - mount point service
69      * @return {@link InstanceIdentifierContext}
70      */
71     public static InstanceIdentifierContext<?> toInstanceIdentifier(
72             final String identifier,
73             final SchemaContext schemaContext,
74             final Optional<DOMMountPointService> mountPointService) {
75         if (identifier != null && identifier.contains(RestconfConstants.MOUNT)) {
76             if (!mountPointService.isPresent()) {
77                 throw new RestconfDocumentedException("Mount point service is not available");
78             }
79
80             final Iterator<String> pathsIt = Splitter.on("/" + RestconfConstants.MOUNT).split(identifier).iterator();
81
82             final String mountPointId = pathsIt.next();
83             final YangInstanceIdentifier mountYangInstanceIdentifier = IdentifierCodec.deserialize(
84                     mountPointId, schemaContext);
85             final Optional<DOMMountPoint> mountPoint =
86                     mountPointService.get().getMountPoint(mountYangInstanceIdentifier);
87
88             if (!mountPoint.isPresent()) {
89                 throw new RestconfDocumentedException(
90                         "Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
91             }
92
93             final DOMMountPoint domMountPoint = mountPoint.get();
94             final SchemaContext mountSchemaContext = domMountPoint.getSchemaContext();
95
96             final String pathId = pathsIt.next().replaceFirst("/", "");
97             final YangInstanceIdentifier pathYangInstanceIdentifier = IdentifierCodec.deserialize(
98                     pathId, mountSchemaContext);
99
100             final DataSchemaContextNode<?> child = DataSchemaContextTree.from(mountSchemaContext)
101                 .getChild(pathYangInstanceIdentifier);
102             if (child != null) {
103                 return new InstanceIdentifierContext<SchemaNode>(pathYangInstanceIdentifier, child.getDataSchemaNode(),
104                         domMountPoint, mountSchemaContext);
105             }
106             final QName rpcQName = pathYangInstanceIdentifier.getLastPathArgument().getNodeType();
107             RpcDefinition def = null;
108             for (final RpcDefinition rpcDefinition : mountSchemaContext
109                     .findModule(rpcQName.getModule()).get().getRpcs()) {
110                 if (rpcDefinition.getQName().getLocalName().equals(rpcQName.getLocalName())) {
111                     def = rpcDefinition;
112                     break;
113                 }
114             }
115             return new InstanceIdentifierContext<>(pathYangInstanceIdentifier, def, domMountPoint, mountSchemaContext);
116         } else {
117             final YangInstanceIdentifier deserialize = IdentifierCodec.deserialize(identifier, schemaContext);
118             final DataSchemaContextNode<?> child = DataSchemaContextTree.from(schemaContext).getChild(deserialize);
119
120             if (child != null) {
121                 return new InstanceIdentifierContext<SchemaNode>(
122                             deserialize, child.getDataSchemaNode(), null, schemaContext);
123             }
124             final QName rpcQName = deserialize.getLastPathArgument().getNodeType();
125             RpcDefinition def = null;
126             for (final RpcDefinition rpcDefinition : schemaContext.findModule(rpcQName.getModule()).get().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 moduleName/Revision pair from identifier.
150      *
151      * @param identifier
152      *             path parameter
153      * @return {@link QName}
154      */
155     public static Entry<String, Revision> 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 Revision moduleRevision;
183         try {
184             moduleRevision = Revision.of(pathArgs.get(1));
185         } catch (final DateTimeParseException 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, e);
189         }
190
191         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
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 DOMYangTextSourceProvider sourceProvider) {
210         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
211         final Iterator<String> componentIter = pathComponents.iterator();
212         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
213             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
214             final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
215             final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
216             return new SchemaExportContext(schemaContext, module, sourceProvider);
217         } else {
218             final StringBuilder pathBuilder = new StringBuilder();
219             while (componentIter.hasNext()) {
220                 final String current = componentIter.next();
221
222                 if (RestconfConstants.MOUNT.equals(current)) {
223                     pathBuilder.append("/");
224                     pathBuilder.append(RestconfConstants.MOUNT);
225                     break;
226                 }
227
228                 if (pathBuilder.length() != 0) {
229                     pathBuilder.append("/");
230                 }
231
232                 pathBuilder.append(current);
233             }
234             final InstanceIdentifierContext<?> point = ParserIdentifier
235                     .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
236             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
237             final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
238             final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
239                     .orElse(null);
240             return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);
241         }
242     }
243 }