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 java.util.Objects.requireNonNull;
13 import com.google.common.collect.ImmutableList;
14 import com.google.gson.stream.JsonReader;
15 import com.google.gson.stream.JsonToken;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.InputStreamReader;
19 import java.io.StringReader;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Optional;
25 import java.util.concurrent.atomic.AtomicReference;
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.WebApplicationException;
28 import javax.ws.rs.ext.Provider;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
33 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
34 import org.opendaylight.restconf.common.patch.PatchContext;
35 import org.opendaylight.restconf.common.patch.PatchEditOperation;
36 import org.opendaylight.restconf.common.patch.PatchEntity;
37 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
38 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
40 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
41 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
42 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
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.model.api.SchemaNode;
53 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
59 public class JsonToPatchBodyReader extends AbstractToPatchBodyReader {
60 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
62 public JsonToPatchBodyReader(final SchemaContextHandler schemaContextHandler,
63 final DOMMountPointServiceHandler mountPointServiceHandler) {
64 super(schemaContextHandler, mountPointServiceHandler);
67 @SuppressWarnings("checkstyle:IllegalCatch")
69 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
70 throws WebApplicationException {
72 return readFrom(path, entityStream);
73 } catch (final Exception e) {
74 throw propagateExceptionAs(e);
78 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
80 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
81 AtomicReference<String> patchId = new AtomicReference<>();
82 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
85 return new PatchContext(path, resultList, patchId.get());
88 @SuppressWarnings("checkstyle:IllegalCatch")
89 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
90 RestconfDocumentedException {
93 ParserIdentifier.toInstanceIdentifier(uriPath, getSchemaContext(),
94 Optional.ofNullable(getMountPointService())), entityStream);
95 } catch (final Exception e) {
96 propagateExceptionAs(e);
101 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
102 if (exception instanceof RestconfDocumentedException) {
103 throw (RestconfDocumentedException)exception;
106 if (exception instanceof ResultAlreadySetException) {
107 LOG.debug("Error parsing json input:", exception);
108 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
111 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
112 ErrorTag.MALFORMED_MESSAGE, exception);
115 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
116 final AtomicReference<String> patchId) throws IOException {
117 final List<PatchEntity> resultCollection = new ArrayList<>();
118 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
119 path.getSchemaContext());
120 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
122 while (in.hasNext()) {
129 Boolean.toString(in.nextBoolean());
143 parseByName(in.nextName(), edit, in, path, codec, 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 StringModuleInstanceIdentifierCodec codec,
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, codec);
183 resultCollection.add(prepareEditOperation(edit));
189 readEditDefinition(edit, in, path, codec);
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 StringModuleInstanceIdentifierCodec codec) 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(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
235 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
236 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
242 checkArgument(edit.getData() == null && deferredValue == null, "Multiple value entries found");
244 if (edit.getTargetSchemaNode() == null) {
245 final StringBuilder sb = new StringBuilder();
247 // save data defined in value node for next (later) processing, because target needs to be read
248 // always first and there is no ordering in Json input
249 readValueNode(sb, in);
250 deferredValue = sb.toString();
252 // We have a target schema node, reuse this reader without buffering the value.
253 edit.setData(readEditData(in, edit.getTargetSchemaNode(), path));
257 // FIXME: this does not look right, as it can wreck our logic
264 if (deferredValue != null) {
265 // read saved data to normalized node when target schema is already known
266 edit.setData(readEditData(new JsonReader(new StringReader(deferredValue)), edit.getTargetSchemaNode(),
272 * Parse data defined in value node and saves it to buffer.
273 * @param sb Buffer to read value node
274 * @param in JsonReader reader
275 * @throws IOException if operation fails
277 private void readValueNode(final @NonNull StringBuilder sb, final @NonNull JsonReader in) throws IOException {
280 sb.append("{\"").append(in.nextName()).append("\":");
287 while (in.hasNext()) {
288 if (in.peek() == JsonToken.STRING) {
289 sb.append('"').append(in.nextString()).append('"');
291 readValueObject(sb, in);
293 if (in.peek() != JsonToken.END_ARRAY) {
302 readValueObject(sb, in);
311 * Parse one value object of data and saves it to buffer.
312 * @param sb Buffer to read value object
313 * @param in JsonReader reader
314 * @throws IOException if operation fails
316 private void readValueObject(final @NonNull StringBuilder sb, final @NonNull JsonReader in) throws IOException {
317 // read simple leaf value
318 if (in.peek() == JsonToken.STRING) {
319 sb.append('"').append(in.nextString()).append('"');
326 while (in.hasNext()) {
327 sb.append('"').append(in.nextName()).append("\":");
331 sb.append('"').append(in.nextString()).append('"');
337 while (in.hasNext()) {
338 if (in.peek() == JsonToken.STRING) {
339 sb.append('"').append(in.nextString()).append('"');
341 readValueObject(sb, in);
344 if (in.peek() != JsonToken.END_ARRAY) {
353 readValueObject(sb, in);
356 if (in.peek() != JsonToken.END_OBJECT) {
366 * Read patch edit data defined in value node to NormalizedNode.
367 * @param in reader JsonReader reader
368 * @return NormalizedNode representing data
370 private static NormalizedNode<?, ?> readEditData(final @NonNull JsonReader in,
371 final @NonNull SchemaNode targetSchemaNode, final @NonNull InstanceIdentifierContext<?> path) {
372 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
373 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
374 JsonParserStream.create(writer, JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()),
375 targetSchemaNode).parse(in);
377 return resultHolder.getResult();
381 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
382 * @param edit Instance of PatchEdit
383 * @return PatchEntity Patch entity
385 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
386 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
387 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
388 if (!edit.getOperation().isWithValue()) {
389 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
392 // for lists allow to manipulate with list items through their parent
393 final YangInstanceIdentifier targetNode;
394 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
395 targetNode = edit.getTarget().getParent();
397 targetNode = edit.getTarget();
400 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
403 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
407 * Check if data is present when operation requires it and not present when operation data is not allowed.
408 * @param operation Name of operation
409 * @param hasData Data in edit are present/not present
410 * @return true if data is present when operation requires it or if there are no data when operation does not
411 * allow it, false otherwise
413 private static boolean checkDataPresence(final @NonNull PatchEditOperation operation, final boolean hasData) {
414 return operation.isWithValue() == hasData;
418 * Helper class representing one patch edit.
420 private static final class PatchEdit {
422 private PatchEditOperation operation;
423 private YangInstanceIdentifier target;
424 private SchemaNode targetSchemaNode;
425 private NormalizedNode<?, ?> data;
431 void setId(final String id) {
432 this.id = requireNonNull(id);
435 PatchEditOperation getOperation() {
439 void setOperation(final PatchEditOperation operation) {
440 this.operation = requireNonNull(operation);
443 YangInstanceIdentifier getTarget() {
447 void setTarget(final YangInstanceIdentifier target) {
448 this.target = requireNonNull(target);
451 SchemaNode getTargetSchemaNode() {
452 return targetSchemaNode;
455 void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
456 this.targetSchemaNode = requireNonNull(targetSchemaNode);
459 NormalizedNode<?, ?> getData() {
463 void setData(final NormalizedNode<?, ?> data) {
464 this.data = requireNonNull(data);
471 targetSchemaNode = null;