2 * Copyright (c) 2015 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.netconf.sal.rest.impl;
10 import static com.google.common.base.Verify.verify;
12 import com.google.common.base.Throwables;
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.lang.annotation.Annotation;
21 import java.lang.reflect.Type;
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.core.MediaType;
31 import javax.ws.rs.core.MultivaluedMap;
32 import javax.ws.rs.ext.MessageBodyReader;
33 import javax.ws.rs.ext.Provider;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.netconf.sal.rest.api.Draft02;
36 import org.opendaylight.netconf.sal.rest.api.RestconfService;
37 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
38 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
39 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
40 import org.opendaylight.restconf.common.patch.PatchContext;
41 import org.opendaylight.restconf.common.patch.PatchEditOperation;
42 import org.opendaylight.restconf.common.patch.PatchEntity;
43 import org.opendaylight.restconf.common.util.RestUtil;
44 import org.opendaylight.yangtools.yang.common.ErrorTag;
45 import org.opendaylight.yangtools.yang.common.ErrorType;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
51 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
54 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
55 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
59 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * Patch reader for JSON.
66 * @deprecated This class will be replaced by JsonToPatchBodyReader in restconf-nb-rfc8040
70 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
71 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
72 implements MessageBodyReader<PatchContext> {
74 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
76 public JsonToPatchBodyReader(final ControllerContext controllerContext) {
77 super(controllerContext);
81 public boolean isReadable(final Class<?> type, final Type genericType,
82 final Annotation[] annotations, final MediaType mediaType) {
86 @SuppressWarnings("checkstyle:IllegalCatch")
88 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
89 final Annotation[] annotations, final MediaType mediaType,
90 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
91 throws WebApplicationException {
93 return readFrom(getInstanceIdentifierContext(), entityStream);
94 } catch (final Exception e) {
95 throw propagateExceptionAs(e);
99 @SuppressWarnings("checkstyle:IllegalCatch")
100 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
101 RestconfDocumentedException {
103 return readFrom(getControllerContext().toInstanceIdentifier(uriPath), entityStream);
104 } catch (final Exception e) {
105 propagateExceptionAs(e);
106 return null; // no-op
110 private PatchContext readFrom(final InstanceIdentifierContext path, final InputStream entityStream)
112 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
113 if (nonEmptyInputStreamOptional.isEmpty()) {
114 return new PatchContext(path, null, null);
117 final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
118 StandardCharsets.UTF_8));
119 AtomicReference<String> patchId = new AtomicReference<>();
120 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
123 return new PatchContext(path, resultList, patchId.get());
126 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
127 Throwables.throwIfInstanceOf(exception, RestconfDocumentedException.class);
128 LOG.debug("Error parsing json input", exception);
130 if (exception instanceof ResultAlreadySetException) {
131 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
134 RestconfDocumentedException.throwIfYangError(exception);
135 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
136 ErrorTag.MALFORMED_MESSAGE, exception);
139 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext path,
140 final AtomicReference<String> patchId) throws IOException {
141 final List<PatchEntity> resultCollection = new ArrayList<>();
142 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
143 path.getSchemaContext());
144 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
146 while (in.hasNext()) {
153 Boolean.toString(in.nextBoolean());
167 parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
181 return ImmutableList.copyOf(resultCollection);
185 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
187 * @param name value of token
188 * @param edit PatchEdit instance
189 * @param in JsonReader reader
190 * @param path InstanceIdentifierContext context
191 * @param codec StringModuleInstanceIdentifierCodec codec
192 * @param resultCollection collection of parsed edits
193 * @throws IOException if operation fails
195 private void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
196 final @NonNull JsonReader in, final @NonNull InstanceIdentifierContext path,
197 final @NonNull StringModuleInstanceIdentifierCodec codec,
198 final @NonNull List<PatchEntity> resultCollection,
199 final @NonNull AtomicReference<String> patchId) throws IOException {
202 if (in.peek() == JsonToken.BEGIN_ARRAY) {
205 while (in.hasNext()) {
206 readEditDefinition(edit, in, path, codec);
207 resultCollection.add(prepareEditOperation(edit));
213 readEditDefinition(edit, in, path, codec);
214 resultCollection.add(prepareEditOperation(edit));
220 patchId.set(in.nextString());
228 * Read one patch edit object from Json input.
229 * @param edit PatchEdit instance to be filled with read data
230 * @param in JsonReader reader
231 * @param path InstanceIdentifierContext path context
232 * @param codec StringModuleInstanceIdentifierCodec codec
233 * @throws IOException if operation fails
235 private void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
236 final @NonNull InstanceIdentifierContext path,
237 final @NonNull StringModuleInstanceIdentifierCodec codec) throws IOException {
238 final StringBuilder value = new StringBuilder();
241 while (in.hasNext()) {
242 final String editDefinition = in.nextName();
243 switch (editDefinition) {
245 edit.setId(in.nextString());
248 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
251 // target can be specified completely in request URI
252 final String target = in.nextString();
253 if (target.equals("/")) {
254 edit.setTarget(path.getInstanceIdentifier());
255 edit.setTargetSchemaNode(SchemaInferenceStack.of(path.getSchemaContext()).toInference());
257 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
259 final var stack = codec.getDataContextTree().enterPath(edit.getTarget()).orElseThrow().stack();
261 final EffectiveStatement<?, ?> parentStmt = stack.currentStatement();
262 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
263 edit.setTargetSchemaNode(stack.toInference());
268 // save data defined in value node for next (later) processing, because target needs to be read
269 // always first and there is no ordering in Json input
270 readValueNode(value, in);
279 // read saved data to normalized node when target schema is already known
280 edit.setData(readEditData(new JsonReader(
281 new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
285 * Parse data defined in value node and saves it to buffer.
286 * @param value Buffer to read value node
287 * @param in JsonReader reader
288 * @throws IOException if operation fails
290 private void readValueNode(final @NonNull StringBuilder value, final @NonNull JsonReader in) throws IOException {
294 value.append('"').append(in.nextName()).append("\":");
296 if (in.peek() == JsonToken.BEGIN_ARRAY) {
300 while (in.hasNext()) {
301 if (in.peek() == JsonToken.STRING) {
302 value.append('"').append(in.nextString()).append('"');
304 readValueObject(value, in);
306 if (in.peek() != JsonToken.END_ARRAY) {
314 readValueObject(value, in);
322 * Parse one value object of data and saves it to buffer.
323 * @param value Buffer to read value object
324 * @param in JsonReader reader
325 * @throws IOException if operation fails
327 private void readValueObject(final @NonNull StringBuilder value, final @NonNull JsonReader in) throws IOException {
328 // read simple leaf value
329 if (in.peek() == JsonToken.STRING) {
330 value.append('"').append(in.nextString()).append('"');
337 while (in.hasNext()) {
338 value.append('"').append(in.nextName()).append("\":");
340 if (in.peek() == JsonToken.STRING) {
341 value.append('"').append(in.nextString()).append('"');
343 if (in.peek() == JsonToken.BEGIN_ARRAY) {
347 while (in.hasNext()) {
348 if (in.peek() == JsonToken.STRING) {
349 value.append('"').append(in.nextString()).append('"');
351 readValueObject(value, in);
353 if (in.peek() != JsonToken.END_ARRAY) {
361 readValueObject(value, in);
365 if (in.peek() != JsonToken.END_OBJECT) {
375 * Read patch edit data defined in value node to NormalizedNode.
376 * @param in reader JsonReader reader
377 * @return NormalizedNode representing data
379 private static NormalizedNode readEditData(final @NonNull JsonReader in,
380 final @NonNull Inference targetSchemaNode, final @NonNull InstanceIdentifierContext path) {
381 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
382 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
383 final EffectiveModelContext context = path.getSchemaContext();
384 JsonParserStream.create(writer, JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(context),
388 return resultHolder.getResult();
392 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
393 * @param edit Instance of PatchEdit
394 * @return PatchEntity Patch entity
396 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
397 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
398 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
399 if (edit.getOperation().isWithValue()) {
400 // for lists allow to manipulate with list items through their parent
401 final YangInstanceIdentifier targetNode;
402 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
403 targetNode = edit.getTarget().getParent();
405 targetNode = edit.getTarget();
408 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
411 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
414 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
418 * Check if data is present when operation requires it and not present when operation data is not allowed.
419 * @param operation Name of operation
420 * @param hasData Data in edit are present/not present
421 * @return true if data is present when operation requires it or if there are no data when operation does not
422 * allow it, false otherwise
424 private static boolean checkDataPresence(final @NonNull PatchEditOperation operation, final boolean hasData) {
425 return operation.isWithValue() == hasData;
429 * Helper class representing one patch edit.
431 private static final class PatchEdit {
433 private PatchEditOperation operation;
434 private YangInstanceIdentifier target;
435 private Inference targetSchemaNode;
436 private NormalizedNode data;
438 public String getId() {
442 public void setId(final String id) {
446 public PatchEditOperation getOperation() {
450 public void setOperation(final PatchEditOperation operation) {
451 this.operation = operation;
454 public YangInstanceIdentifier getTarget() {
458 public void setTarget(final YangInstanceIdentifier target) {
459 this.target = target;
462 public Inference getTargetSchemaNode() {
463 return targetSchemaNode;
466 public void setTargetSchemaNode(final Inference targetSchemaNode) {
467 this.targetSchemaNode = targetSchemaNode;
470 public NormalizedNode getData() {
474 public void setData(final NormalizedNode data) {
478 public void clear() {
482 targetSchemaNode = null;