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
9 package org.opendaylight.netconf.sal.rest.impl;
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.util.ArrayList;
21 import java.util.List;
22 import javax.annotation.Nonnull;
23 import javax.ws.rs.Consumes;
24 import javax.ws.rs.WebApplicationException;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.MultivaluedMap;
27 import javax.ws.rs.ext.MessageBodyReader;
28 import javax.ws.rs.ext.Provider;
29 import org.opendaylight.netconf.sal.rest.api.Draft02;
30 import org.opendaylight.netconf.sal.rest.api.RestconfService;
31 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
32 import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
33 import org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation;
34 import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
37 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
38 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Patch reader for JSON.
55 * @deprecated This class will be replaced by
56 * {@link org.opendaylight.restconf.jersey.providers.JsonToPatchBodyReader}
60 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
61 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
62 implements MessageBodyReader<PatchContext> {
64 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
65 private String patchId;
68 public boolean isReadable(final Class<?> type, final Type genericType,
69 final Annotation[] annotations, final MediaType mediaType) {
73 @SuppressWarnings("checkstyle:IllegalCatch")
75 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
76 final Annotation[] annotations, final MediaType mediaType,
77 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
78 throws IOException, WebApplicationException {
80 return readFrom(getInstanceIdentifierContext(), entityStream);
81 } catch (final Exception e) {
82 throw propagateExceptionAs(e);
86 @SuppressWarnings("checkstyle:IllegalCatch")
87 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
88 RestconfDocumentedException {
90 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
91 } catch (final Exception e) {
92 propagateExceptionAs(e);
97 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
99 if (entityStream.available() < 1) {
100 return new PatchContext(path, null, null);
103 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
104 final List<PatchEntity> resultList = read(jsonReader, path);
107 return new PatchContext(path, resultList, this.patchId);
110 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
111 if (exception instanceof RestconfDocumentedException) {
112 throw (RestconfDocumentedException)exception;
115 if (exception instanceof ResultAlreadySetException) {
116 LOG.debug("Error parsing json input:", exception);
117 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
120 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
121 ErrorTag.MALFORMED_MESSAGE, exception);
124 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
125 final List<PatchEntity> resultCollection = new ArrayList<>();
126 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
127 path.getSchemaContext());
128 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
130 while (in.hasNext()) {
137 Boolean.toString(in.nextBoolean());
151 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
165 return ImmutableList.copyOf(resultCollection);
169 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
171 * @param name value of token
172 * @param edit PatchEdit instance
173 * @param in JsonReader reader
174 * @param path InstanceIdentifierContext context
175 * @param codec StringModuleInstanceIdentifierCodec codec
176 * @param resultCollection collection of parsed edits
177 * @throws IOException if operation fails
179 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
180 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
181 @Nonnull final StringModuleInstanceIdentifierCodec codec,
182 @Nonnull final List<PatchEntity> resultCollection) throws IOException {
185 if (in.peek() == JsonToken.BEGIN_ARRAY) {
188 while (in.hasNext()) {
189 readEditDefinition(edit, in, path, codec);
190 resultCollection.add(prepareEditOperation(edit));
196 readEditDefinition(edit, in, path, codec);
197 resultCollection.add(prepareEditOperation(edit));
203 this.patchId = in.nextString();
211 * Read one patch edit object from Json input.
212 * @param edit PatchEdit instance to be filled with read data
213 * @param in JsonReader reader
214 * @param path InstanceIdentifierContext path context
215 * @param codec StringModuleInstanceIdentifierCodec codec
216 * @throws IOException if operation fails
218 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
219 @Nonnull final InstanceIdentifierContext<?> path,
220 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
221 final StringBuffer value = new StringBuffer();
224 while (in.hasNext()) {
225 final String editDefinition = in.nextName();
226 switch (editDefinition) {
228 edit.setId(in.nextString());
231 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase()));
234 // target can be specified completely in request URI
235 final String target = in.nextString();
236 if (target.equals("/")) {
237 edit.setTarget(path.getInstanceIdentifier());
238 edit.setTargetSchemaNode(path.getSchemaContext());
240 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
241 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
242 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
248 // save data defined in value node for next (later) processing, because target needs to be read
249 // always first and there is no ordering in Json input
250 readValueNode(value, in);
259 // read saved data to normalized node when target schema is already known
260 edit.setData(readEditData(new JsonReader(
261 new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
265 * Parse data defined in value node and saves it to buffer.
266 * @param value Buffer to read value node
267 * @param in JsonReader reader
268 * @throws IOException if operation fails
270 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
274 value.append("\"" + in.nextName() + "\"" + ":");
276 if (in.peek() == JsonToken.BEGIN_ARRAY) {
280 while (in.hasNext()) {
281 if (in.peek() == JsonToken.STRING) {
282 value.append("\"" + in.nextString() + "\"");
284 readValueObject(value, in);
286 if (in.peek() != JsonToken.END_ARRAY) {
294 readValueObject(value, in);
302 * Parse one value object of data and saves it to buffer.
303 * @param value Buffer to read value object
304 * @param in JsonReader reader
305 * @throws IOException if operation fails
307 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
308 // read simple leaf value
309 if (in.peek() == JsonToken.STRING) {
310 value.append("\"" + in.nextString() + "\"");
317 while (in.hasNext()) {
318 value.append("\"" + in.nextName() + "\"");
321 if (in.peek() == JsonToken.STRING) {
322 value.append("\"" + in.nextString() + "\"");
324 if (in.peek() == JsonToken.BEGIN_ARRAY) {
328 while (in.hasNext()) {
329 if (in.peek() == JsonToken.STRING) {
330 value.append("\"" + in.nextString() + "\"");
332 readValueObject(value, in);
334 if (in.peek() != JsonToken.END_ARRAY) {
342 readValueObject(value, in);
346 if (in.peek() != JsonToken.END_OBJECT) {
356 * Read patch edit data defined in value node to NormalizedNode.
357 * @param in reader JsonReader reader
358 * @return NormalizedNode representing data
360 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
361 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
362 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
363 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
364 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
366 return resultHolder.getResult();
370 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
371 * @param edit Instance of PatchEdit
372 * @return PatchEntity Patch entity
374 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
375 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
376 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
377 if (edit.getOperation().isWithValue()) {
378 // for lists allow to manipulate with list items through their parent
379 final YangInstanceIdentifier targetNode;
380 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
381 targetNode = edit.getTarget().getParent();
383 targetNode = edit.getTarget();
386 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
389 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
392 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
396 * Check if data is present when operation requires it and not present when operation data is not allowed.
397 * @param operation Name of operation
398 * @param hasData Data in edit are present/not present
399 * @return true if data is present when operation requires it or if there are no data when operation does not
400 * allow it, false otherwise
402 private static boolean checkDataPresence(@Nonnull final PatchEditOperation operation, final boolean hasData) {
403 return operation.isWithValue() == hasData;
407 * Helper class representing one patch edit.
409 private static final class PatchEdit {
411 private PatchEditOperation operation;
412 private YangInstanceIdentifier target;
413 private SchemaNode targetSchemaNode;
414 private NormalizedNode<?, ?> data;
416 public String getId() {
420 public void setId(final String id) {
424 public PatchEditOperation getOperation() {
425 return this.operation;
428 public void setOperation(final PatchEditOperation operation) {
429 this.operation = operation;
432 public YangInstanceIdentifier getTarget() {
436 public void setTarget(final YangInstanceIdentifier target) {
437 this.target = target;
440 public SchemaNode getTargetSchemaNode() {
441 return this.targetSchemaNode;
444 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
445 this.targetSchemaNode = targetSchemaNode;
448 public NormalizedNode<?, ?> getData() {
452 public void setData(final NormalizedNode<?, ?> data) {
456 public void clear() {
458 this.operation = null;
460 this.targetSchemaNode = null;