Clean up revision formatting
[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  */
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<>(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<>(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 List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
170         if (pathArgs.size() != 2) {
171             LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
172             throw new RestconfDocumentedException(
173                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
174                     ErrorTag.INVALID_VALUE);
175         }
176
177         final Date moduleRevision;
178         try {
179             moduleRevision = SimpleDateFormatUtil.getRevisionFormat().parse(pathArgs.get(1));
180         } catch (final ParseException e) {
181             LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
182             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
183                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
184         }
185
186         return QName.create(null, moduleRevision, pathArgs.get(0));
187     }
188
189     /**
190      * Parsing {@link Module} module by {@link String} module name and
191      * {@link Date} revision and from the parsed module create
192      * {@link SchemaExportContext}
193      *
194      * @param schemaContext
195      *            - {@link SchemaContext}
196      * @param identifier
197      *            - path parameter
198      * @param domMountPointService
199      *            - {@link DOMMountPointService}
200      * @return {@link SchemaExportContext}
201      */
202     public static SchemaExportContext toSchemaExportContextFromIdentifier(final SchemaContext schemaContext,
203             final String identifier, final DOMMountPointService domMountPointService) {
204         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
205         final Iterator<String> componentIter = pathComponents.iterator();
206         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
207             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
208             final Date revision = RestconfValidation.validateAndGetRevision(componentIter);
209             final Module module = schemaContext.findModuleByName(moduleName, revision);
210             return new SchemaExportContext(schemaContext, module);
211         } else {
212             final StringBuilder pathBuilder = new StringBuilder();
213             while (componentIter.hasNext()) {
214                 final String current = componentIter.next();
215
216                 if (RestconfConstants.MOUNT.equals(current)) {
217                     pathBuilder.append("/");
218                     pathBuilder.append(RestconfConstants.MOUNT);
219                     break;
220                 }
221
222                 if (pathBuilder.length() != 0) {
223                     pathBuilder.append("/");
224                 }
225
226                 pathBuilder.append(current);
227             }
228             final InstanceIdentifierContext<?> point = ParserIdentifier
229                     .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
230             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
231             final Date revision = RestconfValidation.validateAndGetRevision(componentIter);
232             final Module module = point.getMountPoint().getSchemaContext().findModuleByName(moduleName, revision);
233             return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module);
234         }
235     }
236 }