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.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.lang.annotation.Annotation;
20 import java.lang.reflect.Type;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Locale;
25 import java.util.Optional;
26 import java.util.concurrent.atomic.AtomicReference;
27 import javax.ws.rs.Consumes;
28 import javax.ws.rs.WebApplicationException;
29 import javax.ws.rs.core.MediaType;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.ext.MessageBodyReader;
32 import javax.ws.rs.ext.Provider;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.netconf.sal.rest.api.Draft02;
35 import org.opendaylight.netconf.sal.rest.api.RestconfService;
36 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
37 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
38 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
39 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
40 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
41 import org.opendaylight.restconf.common.patch.PatchContext;
42 import org.opendaylight.restconf.common.patch.PatchEditOperation;
43 import org.opendaylight.restconf.common.patch.PatchEntity;
44 import org.opendaylight.restconf.common.util.RestUtil;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
50 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
51 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
52 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
53 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
54 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * Patch reader for JSON.
64 * @deprecated This class will be replaced by JsonToPatchBodyReader in restconf-nb-rfc8040
68 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
69 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
70 implements MessageBodyReader<PatchContext> {
72 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
74 public JsonToPatchBodyReader(final ControllerContext controllerContext) {
75 super(controllerContext);
79 public boolean isReadable(final Class<?> type, final Type genericType,
80 final Annotation[] annotations, final MediaType mediaType) {
84 @SuppressWarnings("checkstyle:IllegalCatch")
86 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
87 final Annotation[] annotations, final MediaType mediaType,
88 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
89 throws WebApplicationException {
91 return readFrom(getInstanceIdentifierContext(), entityStream);
92 } catch (final Exception e) {
93 throw propagateExceptionAs(e);
97 @SuppressWarnings("checkstyle:IllegalCatch")
98 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
99 RestconfDocumentedException {
101 return readFrom(getControllerContext().toInstanceIdentifier(uriPath), entityStream);
102 } catch (final Exception e) {
103 propagateExceptionAs(e);
104 return null; // no-op
108 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
110 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
111 if (nonEmptyInputStreamOptional.isEmpty()) {
112 return new PatchContext(path, null, null);
115 final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
116 StandardCharsets.UTF_8));
117 AtomicReference<String> patchId = new AtomicReference<>();
118 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
121 return new PatchContext(path, resultList, patchId.get());
124 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
125 if (exception instanceof RestconfDocumentedException) {
126 throw (RestconfDocumentedException)exception;
129 if (exception instanceof ResultAlreadySetException) {
130 LOG.debug("Error parsing json input:", exception);
131 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
134 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
135 ErrorTag.MALFORMED_MESSAGE, exception);
138 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
139 final AtomicReference<String> patchId) throws IOException {
140 final List<PatchEntity> resultCollection = new ArrayList<>();
141 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
142 path.getSchemaContext());
143 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
145 while (in.hasNext()) {
152 Boolean.toString(in.nextBoolean());
166 parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
180 return ImmutableList.copyOf(resultCollection);
184 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
186 * @param name value of token
187 * @param edit PatchEdit instance
188 * @param in JsonReader reader
189 * @param path InstanceIdentifierContext context
190 * @param codec StringModuleInstanceIdentifierCodec codec
191 * @param resultCollection collection of parsed edits
192 * @throws IOException if operation fails
194 private void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
195 final @NonNull JsonReader in, final @NonNull InstanceIdentifierContext<?> path,
196 final @NonNull StringModuleInstanceIdentifierCodec codec,
197 final @NonNull List<PatchEntity> resultCollection,
198 final @NonNull AtomicReference<String> patchId) throws IOException {
201 if (in.peek() == JsonToken.BEGIN_ARRAY) {
204 while (in.hasNext()) {
205 readEditDefinition(edit, in, path, codec);
206 resultCollection.add(prepareEditOperation(edit));
212 readEditDefinition(edit, in, path, codec);
213 resultCollection.add(prepareEditOperation(edit));
219 patchId.set(in.nextString());
227 * Read one patch edit object from Json input.
228 * @param edit PatchEdit instance to be filled with read data
229 * @param in JsonReader reader
230 * @param path InstanceIdentifierContext path context
231 * @param codec StringModuleInstanceIdentifierCodec codec
232 * @throws IOException if operation fails
234 private void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
235 final @NonNull InstanceIdentifierContext<?> path,
236 final @NonNull StringModuleInstanceIdentifierCodec codec) throws IOException {
237 final StringBuilder value = new StringBuilder();
240 while (in.hasNext()) {
241 final String editDefinition = in.nextName();
242 switch (editDefinition) {
244 edit.setId(in.nextString());
247 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
250 // target can be specified completely in request URI
251 final String target = in.nextString();
252 if (target.equals("/")) {
253 edit.setTarget(path.getInstanceIdentifier());
254 edit.setTargetSchemaNode(path.getSchemaContext());
256 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
258 final EffectiveStatement<?, ?> parentStmt = SchemaInferenceStack.ofInstantiatedPath(
259 path.getSchemaContext(),
260 codec.getDataContextTree().findChild(edit.getTarget()).orElseThrow().getDataSchemaNode()
261 .getPath().getParent())
263 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
264 edit.setTargetSchemaNode((SchemaNode) parentStmt);
269 // save data defined in value node for next (later) processing, because target needs to be read
270 // always first and there is no ordering in Json input
271 readValueNode(value, in);
280 // read saved data to normalized node when target schema is already known
281 edit.setData(readEditData(new JsonReader(
282 new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
286 * Parse data defined in value node and saves it to buffer.
287 * @param value Buffer to read value node
288 * @param in JsonReader reader
289 * @throws IOException if operation fails
291 private void readValueNode(final @NonNull StringBuilder value, final @NonNull JsonReader in) throws IOException {
295 value.append('"').append(in.nextName()).append("\":");
297 if (in.peek() == JsonToken.BEGIN_ARRAY) {
301 while (in.hasNext()) {
302 if (in.peek() == JsonToken.STRING) {
303 value.append('"').append(in.nextString()).append('"');
305 readValueObject(value, in);
307 if (in.peek() != JsonToken.END_ARRAY) {
315 readValueObject(value, in);
323 * Parse one value object of data and saves it to buffer.
324 * @param value Buffer to read value object
325 * @param in JsonReader reader
326 * @throws IOException if operation fails
328 private void readValueObject(final @NonNull StringBuilder value, final @NonNull JsonReader in) throws IOException {
329 // read simple leaf value
330 if (in.peek() == JsonToken.STRING) {
331 value.append('"').append(in.nextString()).append('"');
338 while (in.hasNext()) {
339 value.append('"').append(in.nextName()).append("\":");
341 if (in.peek() == JsonToken.STRING) {
342 value.append('"').append(in.nextString()).append('"');
344 if (in.peek() == JsonToken.BEGIN_ARRAY) {
348 while (in.hasNext()) {
349 if (in.peek() == JsonToken.STRING) {
350 value.append('"').append(in.nextString()).append('"');
352 readValueObject(value, in);
354 if (in.peek() != JsonToken.END_ARRAY) {
362 readValueObject(value, in);
366 if (in.peek() != JsonToken.END_OBJECT) {
376 * Read patch edit data defined in value node to NormalizedNode.
377 * @param in reader JsonReader reader
378 * @return NormalizedNode representing data
380 private static NormalizedNode readEditData(final @NonNull JsonReader in,
381 final @NonNull SchemaNode targetSchemaNode, final @NonNull InstanceIdentifierContext<?> path) {
382 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
383 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
384 final EffectiveModelContext context = path.getSchemaContext();
385 JsonParserStream.create(writer, JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(context),
386 SchemaInferenceStack.ofInstantiatedPath(context, targetSchemaNode.getPath()).toInference())
389 return resultHolder.getResult();
393 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
394 * @param edit Instance of PatchEdit
395 * @return PatchEntity Patch entity
397 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
398 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
399 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
400 if (edit.getOperation().isWithValue()) {
401 // for lists allow to manipulate with list items through their parent
402 final YangInstanceIdentifier targetNode;
403 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
404 targetNode = edit.getTarget().getParent();
406 targetNode = edit.getTarget();
409 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
412 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
415 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
419 * Check if data is present when operation requires it and not present when operation data is not allowed.
420 * @param operation Name of operation
421 * @param hasData Data in edit are present/not present
422 * @return true if data is present when operation requires it or if there are no data when operation does not
423 * allow it, false otherwise
425 private static boolean checkDataPresence(final @NonNull PatchEditOperation operation, final boolean hasData) {
426 return operation.isWithValue() == hasData;
430 * Helper class representing one patch edit.
432 private static final class PatchEdit {
434 private PatchEditOperation operation;
435 private YangInstanceIdentifier target;
436 private SchemaNode targetSchemaNode;
437 private NormalizedNode data;
439 public String getId() {
443 public void setId(final String id) {
447 public PatchEditOperation getOperation() {
448 return this.operation;
451 public void setOperation(final PatchEditOperation operation) {
452 this.operation = operation;
455 public YangInstanceIdentifier getTarget() {
459 public void setTarget(final YangInstanceIdentifier target) {
460 this.target = target;
463 public SchemaNode getTargetSchemaNode() {
464 return this.targetSchemaNode;
467 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
468 this.targetSchemaNode = targetSchemaNode;
471 public NormalizedNode getData() {
475 public void setData(final NormalizedNode data) {
479 public void clear() {
481 this.operation = null;
483 this.targetSchemaNode = null;