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.Optional;
12 import com.google.common.base.Preconditions;
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.concurrent.atomic.AtomicReference;
25 import javax.annotation.Nonnull;
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.WebApplicationException;
28 import javax.ws.rs.ext.Provider;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
33 import org.opendaylight.restconf.common.patch.PatchContext;
34 import org.opendaylight.restconf.common.patch.PatchEditOperation;
35 import org.opendaylight.restconf.common.patch.PatchEntity;
36 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
37 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
38 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
40 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
41 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
47 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
58 public class JsonToPatchBodyReader extends AbstractToPatchBodyReader {
59 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
61 public JsonToPatchBodyReader(SchemaContextHandler schemaContextHandler,
62 DOMMountPointServiceHandler mountPointServiceHandler) {
63 super(schemaContextHandler, mountPointServiceHandler);
66 @SuppressWarnings("checkstyle:IllegalCatch")
68 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
69 throws IOException, WebApplicationException {
71 return readFrom(path, entityStream);
72 } catch (final Exception e) {
73 throw propagateExceptionAs(e);
77 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
79 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
80 AtomicReference<String> patchId = new AtomicReference<>();
81 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
84 return new PatchContext(path, resultList, patchId.get());
87 @SuppressWarnings("checkstyle:IllegalCatch")
88 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
89 RestconfDocumentedException {
92 ParserIdentifier.toInstanceIdentifier(uriPath, getSchemaContext(),
93 Optional.fromNullable(getMountPointService())), entityStream);
94 } catch (final Exception e) {
95 propagateExceptionAs(e);
100 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
101 if (exception instanceof RestconfDocumentedException) {
102 throw (RestconfDocumentedException)exception;
105 if (exception instanceof ResultAlreadySetException) {
106 LOG.debug("Error parsing json input:", exception);
107 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
110 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
111 ErrorTag.MALFORMED_MESSAGE, exception);
114 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
115 final AtomicReference<String> patchId) throws IOException {
116 final List<PatchEntity> resultCollection = new ArrayList<>();
117 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
118 path.getSchemaContext());
119 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
121 while (in.hasNext()) {
128 Boolean.toString(in.nextBoolean());
142 parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
156 return ImmutableList.copyOf(resultCollection);
160 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
162 * @param name value of token
163 * @param edit PatchEdit instance
164 * @param in JsonReader reader
165 * @param path InstanceIdentifierContext context
166 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
167 * @param resultCollection collection of parsed edits
168 * @throws IOException if operation fails
170 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
171 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
172 @Nonnull final StringModuleInstanceIdentifierCodec codec,
173 @Nonnull final List<PatchEntity> resultCollection,
174 @Nonnull final AtomicReference<String> patchId) throws IOException {
177 if (in.peek() == JsonToken.BEGIN_ARRAY) {
180 while (in.hasNext()) {
181 readEditDefinition(edit, in, path, codec);
182 resultCollection.add(prepareEditOperation(edit));
188 readEditDefinition(edit, in, path, codec);
189 resultCollection.add(prepareEditOperation(edit));
195 patchId.set(in.nextString());
203 * Read one patch edit object from Json input.
205 * @param edit PatchEdit instance to be filled with read data
206 * @param in JsonReader reader
207 * @param path InstanceIdentifierContext path context
208 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
209 * @throws IOException if operation fails
211 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
212 @Nonnull final InstanceIdentifierContext<?> path,
213 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
214 String deferredValue = null;
217 while (in.hasNext()) {
218 final String editDefinition = in.nextName();
219 switch (editDefinition) {
221 edit.setId(in.nextString());
224 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
227 // target can be specified completely in request URI
228 final String target = in.nextString();
229 if (target.equals("/")) {
230 edit.setTarget(path.getInstanceIdentifier());
231 edit.setTargetSchemaNode(path.getSchemaContext());
233 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
234 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
235 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
241 Preconditions.checkArgument(edit.getData() == null && deferredValue == null,
242 "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(@Nonnull final StringBuilder sb, @Nonnull final 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(@Nonnull final StringBuilder sb, @Nonnull final 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(@Nonnull final JsonReader in,
371 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final 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(@Nonnull final 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(@Nonnull final 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 = Preconditions.checkNotNull(id);
435 PatchEditOperation getOperation() {
439 void setOperation(final PatchEditOperation operation) {
440 this.operation = Preconditions.checkNotNull(operation);
443 YangInstanceIdentifier getTarget() {
447 void setTarget(final YangInstanceIdentifier target) {
448 this.target = Preconditions.checkNotNull(target);
451 SchemaNode getTargetSchemaNode() {
452 return targetSchemaNode;
455 void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
456 this.targetSchemaNode = Preconditions.checkNotNull(targetSchemaNode);
459 NormalizedNode<?, ?> getData() {
463 void setData(final NormalizedNode<?, ?> data) {
464 this.data = Preconditions.checkNotNull(data);
471 targetSchemaNode = null;