2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import com.google.gson.stream.JsonReader;
14 import com.google.gson.stream.JsonToken;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InputStreamReader;
18 import java.io.StringReader;
19 import java.util.ArrayList;
20 import java.util.List;
21 import javax.annotation.Nonnull;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.ext.Provider;
25 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
28 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
29 import org.opendaylight.restconf.common.patch.PatchContext;
30 import org.opendaylight.restconf.common.patch.PatchEditOperation;
31 import org.opendaylight.restconf.common.patch.PatchEntity;
32 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
33 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
36 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
37 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
53 public class JsonToPatchBodyReader extends AbstractToPatchBodyReader {
54 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
56 private String patchId;
58 @SuppressWarnings("checkstyle:IllegalCatch")
60 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
61 throws IOException, WebApplicationException {
63 return readFrom(path, entityStream);
64 } catch (final Exception e) {
65 throw propagateExceptionAs(e);
69 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
71 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
72 final List<PatchEntity> resultList = read(jsonReader, path);
75 return new PatchContext(path, resultList, patchId);
78 @SuppressWarnings("checkstyle:IllegalCatch")
79 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
80 RestconfDocumentedException {
83 ParserIdentifier.toInstanceIdentifier(uriPath, SchemaContextHandler.getActualSchemaContext(),
84 DOMMountPointServiceHandler.getActualMountPointService()), entityStream);
85 } catch (final Exception e) {
86 propagateExceptionAs(e);
91 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
92 if (exception instanceof RestconfDocumentedException) {
93 throw (RestconfDocumentedException)exception;
96 if (exception instanceof ResultAlreadySetException) {
97 LOG.debug("Error parsing json input:", exception);
98 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
101 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
102 ErrorTag.MALFORMED_MESSAGE, exception);
105 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
106 final List<PatchEntity> resultCollection = new ArrayList<>();
107 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
108 path.getSchemaContext());
109 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
111 while (in.hasNext()) {
118 Boolean.toString(in.nextBoolean());
132 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
146 return ImmutableList.copyOf(resultCollection);
150 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
152 * @param name value of token
153 * @param edit PatchEdit instance
154 * @param in JsonReader reader
155 * @param path InstanceIdentifierContext context
156 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
157 * @param resultCollection collection of parsed edits
158 * @throws IOException if operation fails
160 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
161 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
162 @Nonnull final StringModuleInstanceIdentifierCodec codec,
163 @Nonnull final List<PatchEntity> resultCollection) throws IOException {
166 if (in.peek() == JsonToken.BEGIN_ARRAY) {
169 while (in.hasNext()) {
170 readEditDefinition(edit, in, path, codec);
171 resultCollection.add(prepareEditOperation(edit));
177 readEditDefinition(edit, in, path, codec);
178 resultCollection.add(prepareEditOperation(edit));
184 this.patchId = in.nextString();
192 * Read one patch edit object from Json input.
194 * @param edit PatchEdit instance to be filled with read data
195 * @param in JsonReader reader
196 * @param path InstanceIdentifierContext path context
197 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
198 * @throws IOException if operation fails
200 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
201 @Nonnull final InstanceIdentifierContext<?> path,
202 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
203 String deferredValue = null;
206 while (in.hasNext()) {
207 final String editDefinition = in.nextName();
208 switch (editDefinition) {
210 edit.setId(in.nextString());
213 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase()));
216 // target can be specified completely in request URI
217 final String target = in.nextString();
218 if (target.equals("/")) {
219 edit.setTarget(path.getInstanceIdentifier());
220 edit.setTargetSchemaNode(path.getSchemaContext());
222 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
223 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
224 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
230 Preconditions.checkArgument(edit.getData() == null && deferredValue == null,
231 "Multiple value entries found");
233 if (edit.getTargetSchemaNode() == null) {
234 final StringBuilder sb = new StringBuilder();
236 // save data defined in value node for next (later) processing, because target needs to be read
237 // always first and there is no ordering in Json input
238 readValueNode(sb, in);
239 deferredValue = sb.toString();
241 // We have a target schema node, reuse this reader without buffering the value.
242 edit.setData(readEditData(in, edit.getTargetSchemaNode(), path));
246 // FIXME: this does not look right, as it can wreck our logic
253 if (deferredValue != null) {
254 // read saved data to normalized node when target schema is already known
255 edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
261 * Parse data defined in value node and saves it to buffer.
262 * @param sb Buffer to read value node
263 * @param in JsonReader reader
264 * @throws IOException if operation fails
266 private void readValueNode(@Nonnull final StringBuilder sb, @Nonnull final JsonReader in) throws IOException {
269 sb.append("{\"").append(in.nextName()).append("\":");
276 while (in.hasNext()) {
277 if (in.peek() == JsonToken.STRING) {
278 sb.append('"').append(in.nextString()).append('"');
280 readValueObject(sb, in);
282 if (in.peek() != JsonToken.END_ARRAY) {
291 readValueObject(sb, in);
300 * Parse one value object of data and saves it to buffer.
301 * @param sb Buffer to read value object
302 * @param in JsonReader reader
303 * @throws IOException if operation fails
305 private void readValueObject(@Nonnull final StringBuilder sb, @Nonnull final JsonReader in) throws IOException {
306 // read simple leaf value
307 if (in.peek() == JsonToken.STRING) {
308 sb.append('"').append(in.nextString()).append('"');
315 while (in.hasNext()) {
316 sb.append('"').append(in.nextName()).append("\":");
320 sb.append('"').append(in.nextString()).append('"');
326 while (in.hasNext()) {
327 if (in.peek() == JsonToken.STRING) {
328 sb.append('"').append(in.nextString()).append('"');
330 readValueObject(sb, in);
333 if (in.peek() != JsonToken.END_ARRAY) {
342 readValueObject(sb, in);
345 if (in.peek() != JsonToken.END_OBJECT) {
355 * Read patch edit data defined in value node to NormalizedNode.
356 * @param in reader JsonReader reader
357 * @return NormalizedNode representing data
359 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
360 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
361 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
362 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
363 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
365 return resultHolder.getResult();
369 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
370 * @param edit Instance of PatchEdit
371 * @return PatchEntity Patch entity
373 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
374 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
375 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
376 if (!edit.getOperation().isWithValue()) {
377 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
380 // for lists allow to manipulate with list items through their parent
381 final YangInstanceIdentifier targetNode;
382 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
383 targetNode = edit.getTarget().getParent();
385 targetNode = edit.getTarget();
388 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
391 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
395 * Check if data is present when operation requires it and not present when operation data is not allowed.
396 * @param operation Name of operation
397 * @param hasData Data in edit are present/not present
398 * @return true if data is present when operation requires it or if there are no data when operation does not
399 * allow it, false otherwise
401 private static boolean checkDataPresence(@Nonnull final PatchEditOperation operation, final boolean hasData) {
402 return operation.isWithValue() == hasData;
406 * Helper class representing one patch edit.
408 private static final class PatchEdit {
410 private PatchEditOperation operation;
411 private YangInstanceIdentifier target;
412 private SchemaNode targetSchemaNode;
413 private NormalizedNode<?, ?> data;
419 void setId(final String id) {
420 this.id = Preconditions.checkNotNull(id);
423 PatchEditOperation getOperation() {
427 void setOperation(final PatchEditOperation operation) {
428 this.operation = Preconditions.checkNotNull(operation);
431 YangInstanceIdentifier getTarget() {
435 void setTarget(final YangInstanceIdentifier target) {
436 this.target = Preconditions.checkNotNull(target);
439 SchemaNode getTargetSchemaNode() {
440 return targetSchemaNode;
443 void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
444 this.targetSchemaNode = Preconditions.checkNotNull(targetSchemaNode);
447 NormalizedNode<?, ?> getData() {
451 void setData(final NormalizedNode<?, ?> data) {
452 this.data = Preconditions.checkNotNull(data);
459 targetSchemaNode = null;