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