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.restconf.common.context.InstanceIdentifierContext;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
35 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
36 import org.opendaylight.restconf.common.patch.PatchContext;
37 import org.opendaylight.restconf.common.patch.PatchEditOperation;
38 import org.opendaylight.restconf.common.patch.PatchEntity;
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 JsonToPatchBodyReader in restconf-nb-rfc8040
59 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
60 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
61 implements MessageBodyReader<PatchContext> {
63 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
64 private String patchId;
67 public boolean isReadable(final Class<?> type, final Type genericType,
68 final Annotation[] annotations, final MediaType mediaType) {
72 @SuppressWarnings("checkstyle:IllegalCatch")
74 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
75 final Annotation[] annotations, final MediaType mediaType,
76 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
77 throws IOException, WebApplicationException {
79 return readFrom(getInstanceIdentifierContext(), entityStream);
80 } catch (final Exception e) {
81 throw propagateExceptionAs(e);
85 @SuppressWarnings("checkstyle:IllegalCatch")
86 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
87 RestconfDocumentedException {
89 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
90 } catch (final Exception e) {
91 propagateExceptionAs(e);
96 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
98 if (entityStream.available() < 1) {
99 return new PatchContext(path, null, null);
102 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
103 final List<PatchEntity> resultList = read(jsonReader, path);
106 return new PatchContext(path, resultList, this.patchId);
109 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
110 if (exception instanceof RestconfDocumentedException) {
111 throw (RestconfDocumentedException)exception;
114 if (exception instanceof ResultAlreadySetException) {
115 LOG.debug("Error parsing json input:", exception);
116 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
119 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
120 ErrorTag.MALFORMED_MESSAGE, exception);
123 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
124 final List<PatchEntity> resultCollection = new ArrayList<>();
125 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
126 path.getSchemaContext());
127 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
129 while (in.hasNext()) {
136 Boolean.toString(in.nextBoolean());
150 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
164 return ImmutableList.copyOf(resultCollection);
168 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
170 * @param name value of token
171 * @param edit PatchEdit instance
172 * @param in JsonReader reader
173 * @param path InstanceIdentifierContext context
174 * @param codec StringModuleInstanceIdentifierCodec codec
175 * @param resultCollection collection of parsed edits
176 * @throws IOException if operation fails
178 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
179 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
180 @Nonnull final StringModuleInstanceIdentifierCodec codec,
181 @Nonnull final List<PatchEntity> resultCollection) throws IOException {
184 if (in.peek() == JsonToken.BEGIN_ARRAY) {
187 while (in.hasNext()) {
188 readEditDefinition(edit, in, path, codec);
189 resultCollection.add(prepareEditOperation(edit));
195 readEditDefinition(edit, in, path, codec);
196 resultCollection.add(prepareEditOperation(edit));
202 this.patchId = in.nextString();
210 * Read one patch edit object from Json input.
211 * @param edit PatchEdit instance to be filled with read data
212 * @param in JsonReader reader
213 * @param path InstanceIdentifierContext path context
214 * @param codec StringModuleInstanceIdentifierCodec codec
215 * @throws IOException if operation fails
217 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
218 @Nonnull final InstanceIdentifierContext<?> path,
219 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
220 final StringBuffer value = new StringBuffer();
223 while (in.hasNext()) {
224 final String editDefinition = in.nextName();
225 switch (editDefinition) {
227 edit.setId(in.nextString());
230 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase()));
233 // target can be specified completely in request URI
234 final String target = in.nextString();
235 if (target.equals("/")) {
236 edit.setTarget(path.getInstanceIdentifier());
237 edit.setTargetSchemaNode(path.getSchemaContext());
239 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
240 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
241 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
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(value, in);
258 // read saved data to normalized node when target schema is already known
259 edit.setData(readEditData(new JsonReader(
260 new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
264 * Parse data defined in value node and saves it to buffer.
265 * @param value Buffer to read value node
266 * @param in JsonReader reader
267 * @throws IOException if operation fails
269 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
273 value.append("\"" + in.nextName() + "\"" + ":");
275 if (in.peek() == JsonToken.BEGIN_ARRAY) {
279 while (in.hasNext()) {
280 if (in.peek() == JsonToken.STRING) {
281 value.append("\"" + in.nextString() + "\"");
283 readValueObject(value, in);
285 if (in.peek() != JsonToken.END_ARRAY) {
293 readValueObject(value, in);
301 * Parse one value object of data and saves it to buffer.
302 * @param value Buffer to read value object
303 * @param in JsonReader reader
304 * @throws IOException if operation fails
306 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
307 // read simple leaf value
308 if (in.peek() == JsonToken.STRING) {
309 value.append("\"" + in.nextString() + "\"");
316 while (in.hasNext()) {
317 value.append("\"" + in.nextName() + "\"");
320 if (in.peek() == JsonToken.STRING) {
321 value.append("\"" + in.nextString() + "\"");
323 if (in.peek() == JsonToken.BEGIN_ARRAY) {
327 while (in.hasNext()) {
328 if (in.peek() == JsonToken.STRING) {
329 value.append("\"" + in.nextString() + "\"");
331 readValueObject(value, in);
333 if (in.peek() != JsonToken.END_ARRAY) {
341 readValueObject(value, in);
345 if (in.peek() != JsonToken.END_OBJECT) {
355 * Read patch edit data defined in value node to NormalizedNode.
356 * @param in reader JsonReader reader
357 * @return NormalizedNode representing data
359 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
360 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
361 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
362 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
363 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
365 return resultHolder.getResult();
369 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
370 * @param edit Instance of PatchEdit
371 * @return PatchEntity Patch entity
373 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
374 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
375 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
376 if (edit.getOperation().isWithValue()) {
377 // for lists allow to manipulate with list items through their parent
378 final YangInstanceIdentifier targetNode;
379 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
380 targetNode = edit.getTarget().getParent();
382 targetNode = edit.getTarget();
385 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
388 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
391 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
395 * Check if data is present when operation requires it and not present when operation data is not allowed.
396 * @param operation Name of operation
397 * @param hasData Data in edit are present/not present
398 * @return true if data is present when operation requires it or if there are no data when operation does not
399 * allow it, false otherwise
401 private static boolean checkDataPresence(@Nonnull final PatchEditOperation operation, final boolean hasData) {
402 return operation.isWithValue() == hasData;
406 * Helper class representing one patch edit.
408 private static final class PatchEdit {
410 private PatchEditOperation operation;
411 private YangInstanceIdentifier target;
412 private SchemaNode targetSchemaNode;
413 private NormalizedNode<?, ?> data;
415 public String getId() {
419 public void setId(final String id) {
423 public PatchEditOperation getOperation() {
424 return this.operation;
427 public void setOperation(final PatchEditOperation operation) {
428 this.operation = operation;
431 public YangInstanceIdentifier getTarget() {
435 public void setTarget(final YangInstanceIdentifier target) {
436 this.target = target;
439 public SchemaNode getTargetSchemaNode() {
440 return this.targetSchemaNode;
443 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
444 this.targetSchemaNode = targetSchemaNode;
447 public NormalizedNode<?, ?> getData() {
451 public void setData(final NormalizedNode<?, ?> data) {
455 public void clear() {
457 this.operation = null;
459 this.targetSchemaNode = null;