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 com.google.common.base.Throwables;
11 import com.google.common.collect.ImmutableList;
12 import com.google.gson.stream.JsonReader;
13 import com.google.gson.stream.JsonToken;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.InputStreamReader;
17 import java.io.StringReader;
18 import java.lang.annotation.Annotation;
19 import java.lang.reflect.Type;
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.core.MediaType;
29 import javax.ws.rs.core.MultivaluedMap;
30 import javax.ws.rs.ext.MessageBodyReader;
31 import javax.ws.rs.ext.Provider;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.opendaylight.netconf.sal.rest.api.Draft02;
34 import org.opendaylight.netconf.sal.rest.api.RestconfService;
35 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
36 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
37 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
38 import org.opendaylight.restconf.common.patch.PatchContext;
39 import org.opendaylight.restconf.common.patch.PatchEditOperation;
40 import org.opendaylight.restconf.common.patch.PatchEntity;
41 import org.opendaylight.restconf.common.util.RestUtil;
42 import org.opendaylight.yangtools.yang.common.ErrorTag;
43 import org.opendaylight.yangtools.yang.common.ErrorType;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
49 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
53 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
54 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
55 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
60 * Patch reader for JSON.
62 * @deprecated This class will be replaced by JsonToPatchBodyReader in restconf-nb-rfc8040
66 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
67 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
68 implements MessageBodyReader<PatchContext> {
70 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
72 public JsonToPatchBodyReader(final ControllerContext controllerContext) {
73 super(controllerContext);
77 public boolean isReadable(final Class<?> type, final Type genericType,
78 final Annotation[] annotations, final MediaType mediaType) {
82 @SuppressWarnings("checkstyle:IllegalCatch")
84 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
85 final Annotation[] annotations, final MediaType mediaType,
86 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
87 throws WebApplicationException {
89 return readFrom(getInstanceIdentifierContext(), entityStream);
90 } catch (final Exception e) {
91 throw propagateExceptionAs(e);
95 @SuppressWarnings("checkstyle:IllegalCatch")
96 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
97 RestconfDocumentedException {
99 return readFrom(getControllerContext().toInstanceIdentifier(uriPath), entityStream);
100 } catch (final Exception e) {
101 propagateExceptionAs(e);
102 return null; // no-op
106 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
108 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
109 if (nonEmptyInputStreamOptional.isEmpty()) {
110 return new PatchContext(path, null, null);
113 final JsonReader jsonReader = new JsonReader(new InputStreamReader(nonEmptyInputStreamOptional.get(),
114 StandardCharsets.UTF_8));
115 AtomicReference<String> patchId = new AtomicReference<>();
116 final List<PatchEntity> resultList = read(jsonReader, path, patchId);
119 return new PatchContext(path, resultList, patchId.get());
122 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
123 Throwables.throwIfInstanceOf(exception, RestconfDocumentedException.class);
124 LOG.debug("Error parsing json input", exception);
126 if (exception instanceof ResultAlreadySetException) {
127 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
130 RestconfDocumentedException.throwIfYangError(exception);
131 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
132 ErrorTag.MALFORMED_MESSAGE, exception);
135 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path,
136 final AtomicReference<String> patchId) throws IOException {
137 final List<PatchEntity> resultCollection = new ArrayList<>();
138 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
139 path.getSchemaContext());
140 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
142 while (in.hasNext()) {
149 Boolean.toString(in.nextBoolean());
163 parseByName(in.nextName(), edit, in, path, codec, resultCollection, patchId);
177 return ImmutableList.copyOf(resultCollection);
181 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
183 * @param name value of token
184 * @param edit PatchEdit instance
185 * @param in JsonReader reader
186 * @param path InstanceIdentifierContext context
187 * @param codec StringModuleInstanceIdentifierCodec codec
188 * @param resultCollection collection of parsed edits
189 * @throws IOException if operation fails
191 private void parseByName(final @NonNull String name, final @NonNull PatchEdit edit,
192 final @NonNull JsonReader in, final @NonNull InstanceIdentifierContext<?> path,
193 final @NonNull StringModuleInstanceIdentifierCodec codec,
194 final @NonNull List<PatchEntity> resultCollection,
195 final @NonNull AtomicReference<String> patchId) throws IOException {
198 if (in.peek() == JsonToken.BEGIN_ARRAY) {
201 while (in.hasNext()) {
202 readEditDefinition(edit, in, path, codec);
203 resultCollection.add(prepareEditOperation(edit));
209 readEditDefinition(edit, in, path, codec);
210 resultCollection.add(prepareEditOperation(edit));
216 patchId.set(in.nextString());
224 * Read one patch edit object from Json input.
225 * @param edit PatchEdit instance to be filled with read data
226 * @param in JsonReader reader
227 * @param path InstanceIdentifierContext path context
228 * @param codec StringModuleInstanceIdentifierCodec codec
229 * @throws IOException if operation fails
231 private void readEditDefinition(final @NonNull PatchEdit edit, final @NonNull JsonReader in,
232 final @NonNull InstanceIdentifierContext<?> path,
233 final @NonNull StringModuleInstanceIdentifierCodec codec) throws IOException {
234 final StringBuilder value = new StringBuilder();
237 while (in.hasNext()) {
238 final String editDefinition = in.nextName();
239 switch (editDefinition) {
241 edit.setId(in.nextString());
244 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase(Locale.ROOT)));
247 // target can be specified completely in request URI
248 final String target = in.nextString();
249 final SchemaInferenceStack stack = SchemaInferenceStack.of(path.getSchemaContext());
250 if (target.equals("/")) {
251 edit.setTarget(path.getInstanceIdentifier());
252 edit.setTargetInference(stack.toInference());
254 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
255 edit.getTarget().getPathArguments().stream()
256 .filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates))
257 .filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier))
258 .forEach(p -> stack.enterSchemaTree(p.getNodeType()));
260 edit.setTargetInference(stack.toInference());
264 // save data defined in value node for next (later) processing, because target needs to be read
265 // always first and there is no ordering in Json input
266 readValueNode(value, in);
275 // read saved data to normalized node when target schema is already known
276 edit.setData(readEditData(new JsonReader(
277 new StringReader(value.toString())), edit.getTargetInference(), path));
281 * Parse data defined in value node and saves it to buffer.
282 * @param value Buffer to read value node
283 * @param in JsonReader reader
284 * @throws IOException if operation fails
286 private void readValueNode(final @NonNull StringBuilder value, final @NonNull JsonReader in) throws IOException {
290 value.append('"').append(in.nextName()).append("\":");
292 if (in.peek() == JsonToken.BEGIN_ARRAY) {
296 while (in.hasNext()) {
297 if (in.peek() == JsonToken.STRING) {
298 value.append('"').append(in.nextString()).append('"');
300 readValueObject(value, in);
302 if (in.peek() != JsonToken.END_ARRAY) {
310 readValueObject(value, in);
318 * Parse one value object of data and saves it to buffer.
319 * @param value Buffer to read value object
320 * @param in JsonReader reader
321 * @throws IOException if operation fails
323 private void readValueObject(final @NonNull StringBuilder value, final @NonNull JsonReader in) throws IOException {
324 // read simple leaf value
325 if (in.peek() == JsonToken.STRING) {
326 value.append('"').append(in.nextString()).append('"');
333 while (in.hasNext()) {
334 value.append('"').append(in.nextName()).append("\":");
336 if (in.peek() == JsonToken.STRING) {
337 value.append('"').append(in.nextString()).append('"');
339 if (in.peek() == JsonToken.BEGIN_ARRAY) {
343 while (in.hasNext()) {
344 if (in.peek() == JsonToken.STRING) {
345 value.append('"').append(in.nextString()).append('"');
347 readValueObject(value, in);
349 if (in.peek() != JsonToken.END_ARRAY) {
357 readValueObject(value, in);
361 if (in.peek() != JsonToken.END_OBJECT) {
371 * Read patch edit data defined in value node to NormalizedNode.
372 * @param in reader JsonReader reader
373 * @return NormalizedNode representing data
375 private static NormalizedNode readEditData(final @NonNull JsonReader in,
376 final @NonNull Inference inference, final @NonNull InstanceIdentifierContext<?> path) {
377 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
378 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
379 final EffectiveModelContext context = path.getSchemaContext();
380 JsonParserStream.create(writer, JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(context),
381 inference).parse(in);
383 return resultHolder.getResult();
387 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
388 * @param edit Instance of PatchEdit
389 * @return PatchEntity Patch entity
391 private static PatchEntity prepareEditOperation(final @NonNull PatchEdit edit) {
392 if (edit.getOperation() != null && edit.getTargetInference() != null
393 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
394 if (edit.getOperation().isWithValue()) {
395 // for lists allow to manipulate with list items through their parent
396 final YangInstanceIdentifier targetNode;
397 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
398 targetNode = edit.getTarget().getParent();
400 targetNode = edit.getTarget();
403 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
406 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
409 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
413 * Check if data is present when operation requires it and not present when operation data is not allowed.
414 * @param operation Name of operation
415 * @param hasData Data in edit are present/not present
416 * @return true if data is present when operation requires it or if there are no data when operation does not
417 * allow it, false otherwise
419 private static boolean checkDataPresence(final @NonNull PatchEditOperation operation, final boolean hasData) {
420 return operation.isWithValue() == hasData;
424 * Helper class representing one patch edit.
426 private static final class PatchEdit {
428 private PatchEditOperation operation;
429 private YangInstanceIdentifier target;
430 private Inference targetInference;
431 private NormalizedNode data;
433 public String getId() {
437 public void setId(final String id) {
441 public PatchEditOperation getOperation() {
442 return this.operation;
445 public void setOperation(final PatchEditOperation operation) {
446 this.operation = operation;
449 public YangInstanceIdentifier getTarget() {
453 public void setTarget(final YangInstanceIdentifier target) {
454 this.target = target;
457 public Inference getTargetInference() {
458 return this.targetInference;
461 public void setTargetInference(final Inference targetInference) {
462 this.targetInference = targetInference;
465 public NormalizedNode getData() {
469 public void setData(final NormalizedNode data) {
473 public void clear() {
475 this.operation = null;
477 this.targetInference = null;