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
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableList;
16 import com.google.gson.stream.JsonReader;
17 import com.google.gson.stream.JsonToken;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.io.StringReader;
22 import java.nio.charset.StandardCharsets;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Optional;
27 import java.util.concurrent.atomic.AtomicReference;
28 import javax.ws.rs.Consumes;
29 import javax.ws.rs.WebApplicationException;
30 import javax.ws.rs.ext.Provider;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
33 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
34 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
35 import org.opendaylight.restconf.common.patch.PatchContext;
36 import org.opendaylight.restconf.common.patch.PatchEditOperation;
37 import org.opendaylight.restconf.common.patch.PatchEntity;
38 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
40 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
41 import org.opendaylight.yangtools.yang.common.ErrorTag;
42 import org.opendaylight.yangtools.yang.common.ErrorType;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
48 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
49 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
51 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
52 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
60 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_JSON)
61 public class JsonPatchBodyReader extends AbstractPatchBodyReader {
62 private static final Logger LOG = LoggerFactory.getLogger(JsonPatchBodyReader.class);
64 public JsonPatchBodyReader(final SchemaContextHandler schemaContextHandler,
65 final DOMMountPointService mountPointService) {
66 super(schemaContextHandler, mountPointService);
69 @SuppressWarnings("checkstyle:IllegalCatch")
71 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
72 throws WebApplicationException {
74 return readFrom(path, entityStream);
75 } catch (final Exception e) {
76 throw propagateExceptionAs(e);
80 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
82 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
83 AtomicReference<String> patchId = new AtomicReference<>();
84 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
87 return new PatchContext(path, resultList, patchId.get());
90 @SuppressWarnings("checkstyle:IllegalCatch")
91 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
92 RestconfDocumentedException {
95 ParserIdentifier.toInstanceIdentifier(uriPath, getSchemaContext(),
96 Optional.ofNullable(getMountPointService())), entityStream);
97 } catch (final Exception e) {
98 propagateExceptionAs(e);
103 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
104 Throwables.throwIfInstanceOf(exception, RestconfDocumentedException.class);
105 LOG.debug("Error parsing json input", exception);
107 if (exception instanceof ResultAlreadySetException) {
108 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
111 RestconfDocumentedException.throwIfYangError(exception);
112 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
113 ErrorTag.MALFORMED_MESSAGE, exception);
116 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
117 final AtomicReference<String> patchId) throws IOException {
118 final DataSchemaContextTree schemaTree = DataSchemaContextTree.from(path.getSchemaContext());
119 final List<PatchEntity> resultCollection = new ArrayList<>();
120 final JsonPatchBodyReader.PatchEdit edit = new JsonPatchBodyReader.PatchEdit();
122 while (in.hasNext()) {
129 Boolean.toString(in.nextBoolean());
143 parseByName(in.nextName(), edit, in, path, schemaTree, resultCollection, patchId);
157 return ImmutableList.copyOf(resultCollection);
161 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
163 * @param name value of token
164 * @param edit PatchEdit instance
165 * @param in JsonReader reader
166 * @param path InstanceIdentifierContext context
167 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
168 * @param resultCollection collection of parsed edits
169 * @throws IOException if operation fails
171 private void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
172 final @NonNull JsonReader in, final @NonNull InstanceIdentifierContext<?> path,
173 final @NonNull DataSchemaContextTree schemaTree,
174 final @NonNull List<PatchEntity> resultCollection,
175 final @NonNull AtomicReference<String> patchId) throws IOException {
178 if (in.peek() == JsonToken.BEGIN_ARRAY) {
181 while (in.hasNext()) {
182 readEditDefinition(edit, in, path, schemaTree);
183 resultCollection.add(prepareEditOperation(edit));
189 readEditDefinition(edit, in, path, schemaTree);
190 resultCollection.add(prepareEditOperation(edit));
196 patchId.set(in.nextString());
204 * Read one patch edit object from Json input.
206 * @param edit PatchEdit instance to be filled with read data
207 * @param in JsonReader reader
208 * @param path InstanceIdentifierContext path context
209 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
210 * @throws IOException if operation fails
212 private void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
213 final @NonNull InstanceIdentifierContext<?> path,
214 final @NonNull DataSchemaContextTree schemaTree) throws IOException {
215 String deferredValue = null;
218 while (in.hasNext()) {
219 final String editDefinition = in.nextName();
220 switch (editDefinition) {
222 edit.setId(in.nextString());
225 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
228 // target can be specified completely in request URI
229 final String target = in.nextString();
230 if (target.equals("/")) {
231 edit.setTarget(path.getInstanceIdentifier());
232 edit.setTargetSchemaNode(path.getSchemaContext());
234 edit.setTarget(ParserIdentifier.parserPatchTarget(path, target));
236 final EffectiveStatement<?, ?> parentStmt = SchemaInferenceStack.ofInstantiatedPath(
237 path.getSchemaContext(),
238 schemaTree.findChild(edit.getTarget()).orElseThrow().getDataSchemaNode()
239 .getPath().getParent())
241 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
242 edit.setTargetSchemaNode((SchemaNode) parentStmt);
247 checkArgument(edit.getData() == null && deferredValue == null, "Multiple value entries found");
249 if (edit.getTargetSchemaNode() == null) {
250 // save data defined in value node for next (later) processing, because target needs to be read
251 // always first and there is no ordering in Json input
252 deferredValue = readValueNode(in);
254 // We have a target schema node, reuse this reader without buffering the value.
255 edit.setData(readEditData(in, edit.getTargetSchemaNode(), path));
259 // FIXME: this does not look right, as it can wreck our logic
266 if (deferredValue != null) {
267 // read saved data to normalized node when target schema is already known
268 edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
274 * Parse data defined in value node and saves it to buffer.
275 * @param sb Buffer to read value node
276 * @param in JsonReader reader
277 * @throws IOException if operation fails
279 private String readValueNode(final @NonNull JsonReader in) throws IOException {
281 final StringBuilder sb = new StringBuilder().append("{\"").append(in.nextName()).append("\":");
288 while (in.hasNext()) {
289 if (in.peek() == JsonToken.STRING) {
290 sb.append('"').append(in.nextString()).append('"');
292 readValueObject(sb, in);
294 if (in.peek() != JsonToken.END_ARRAY) {
303 readValueObject(sb, in);
308 return sb.append('}').toString();
312 * Parse one value object of data and saves it to buffer.
313 * @param sb Buffer to read value object
314 * @param in JsonReader reader
315 * @throws IOException if operation fails
317 private void readValueObject(final @NonNull StringBuilder sb, final @NonNull JsonReader in) throws IOException {
318 // read simple leaf value
319 if (in.peek() == JsonToken.STRING) {
320 sb.append('"').append(in.nextString()).append('"');
327 while (in.hasNext()) {
328 sb.append('"').append(in.nextName()).append("\":");
332 sb.append('"').append(in.nextString()).append('"');
338 while (in.hasNext()) {
339 if (in.peek() == JsonToken.STRING) {
340 sb.append('"').append(in.nextString()).append('"');
342 readValueObject(sb, in);
345 if (in.peek() != JsonToken.END_ARRAY) {
354 readValueObject(sb, in);
357 if (in.peek() != JsonToken.END_OBJECT) {
367 * Read patch edit data defined in value node to NormalizedNode.
368 * @param in reader JsonReader reader
369 * @return NormalizedNode representing data
371 private static NormalizedNode readEditData(final @NonNull JsonReader in,
372 final @NonNull SchemaNode targetSchemaNode, final @NonNull InstanceIdentifierContext<?> path) {
373 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
374 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
375 JsonParserStream.create(writer, JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()),
376 SchemaInferenceStack.ofInstantiatedPath(path.getSchemaContext(), targetSchemaNode.getPath()).toInference())
379 return resultHolder.getResult();
383 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
384 * @param edit Instance of PatchEdit
385 * @return PatchEntity Patch entity
387 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
388 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
389 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
390 if (!edit.getOperation().isWithValue()) {
391 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
394 // for lists allow to manipulate with list items through their parent
395 final YangInstanceIdentifier targetNode;
396 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
397 targetNode = edit.getTarget().getParent();
399 targetNode = edit.getTarget();
402 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
405 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
409 * Check if data is present when operation requires it and not present when operation data is not allowed.
410 * @param operation Name of operation
411 * @param hasData Data in edit are present/not present
412 * @return true if data is present when operation requires it or if there are no data when operation does not
413 * allow it, false otherwise
415 private static boolean checkDataPresence(final @NonNull PatchEditOperation operation, final boolean hasData) {
416 return operation.isWithValue() == hasData;
420 * Helper class representing one patch edit.
422 private static final class PatchEdit {
424 private PatchEditOperation operation;
425 private YangInstanceIdentifier target;
426 private SchemaNode targetSchemaNode;
427 private NormalizedNode data;
433 void setId(final String id) {
434 this.id = requireNonNull(id);
437 PatchEditOperation getOperation() {
441 void setOperation(final PatchEditOperation operation) {
442 this.operation = requireNonNull(operation);
445 YangInstanceIdentifier getTarget() {
449 void setTarget(final YangInstanceIdentifier target) {
450 this.target = requireNonNull(target);
453 SchemaNode getTargetSchemaNode() {
454 return targetSchemaNode;
457 void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
458 this.targetSchemaNode = requireNonNull(targetSchemaNode);
461 NormalizedNode getData() {
465 void setData(final NormalizedNode data) {
466 this.data = requireNonNull(data);
473 targetSchemaNode = null;