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 static org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation.isPatchOperationWithValue;
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.util.ArrayList;
23 import java.util.List;
24 import javax.annotation.Nonnull;
25 import javax.ws.rs.Consumes;
26 import javax.ws.rs.WebApplicationException;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.MultivaluedMap;
29 import javax.ws.rs.ext.MessageBodyReader;
30 import javax.ws.rs.ext.Provider;
31 import org.opendaylight.netconf.sal.rest.api.Draft02;
32 import org.opendaylight.netconf.sal.rest.api.RestconfService;
33 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
34 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
35 import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
36 import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
37 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
38 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
39 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Patch reader for JSON.
56 * @deprecated This class will be replaced by
57 * {@link org.opendaylight.restconf.jersey.providers.JsonToPatchBodyReader}
61 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
62 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
63 implements MessageBodyReader<PatchContext> {
65 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
66 private String patchId;
69 public boolean isReadable(final Class<?> type, final Type genericType,
70 final Annotation[] annotations, final MediaType mediaType) {
74 @SuppressWarnings("checkstyle:IllegalCatch")
76 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
77 final Annotation[] annotations, final MediaType mediaType,
78 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
79 throws IOException, WebApplicationException {
81 return readFrom(getInstanceIdentifierContext(), entityStream);
82 } catch (final Exception e) {
83 throw propagateExceptionAs(e);
87 @SuppressWarnings("checkstyle:IllegalCatch")
88 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
89 RestconfDocumentedException {
91 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
92 } catch (final Exception e) {
93 propagateExceptionAs(e);
98 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
100 if (entityStream.available() < 1) {
101 return new PatchContext(path, null, null);
104 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
105 final List<PatchEntity> resultList = read(jsonReader, path);
108 return new PatchContext(path, resultList, this.patchId);
111 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
112 if (exception instanceof RestconfDocumentedException) {
113 throw (RestconfDocumentedException)exception;
116 if (exception instanceof ResultAlreadySetException) {
117 LOG.debug("Error parsing json input:", exception);
118 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
121 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
122 ErrorTag.MALFORMED_MESSAGE, exception);
125 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
126 final List<PatchEntity> resultCollection = new ArrayList<>();
127 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
128 path.getSchemaContext());
129 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
131 while (in.hasNext()) {
138 Boolean.toString(in.nextBoolean());
152 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
166 return ImmutableList.copyOf(resultCollection);
170 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
172 * @param name value of token
173 * @param edit PatchEdit instance
174 * @param in JsonReader reader
175 * @param path InstanceIdentifierContext context
176 * @param codec StringModuleInstanceIdentifierCodec codec
177 * @param resultCollection collection of parsed edits
178 * @throws IOException if operation fails
180 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
181 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
182 @Nonnull final StringModuleInstanceIdentifierCodec codec,
183 @Nonnull final List<PatchEntity> resultCollection) throws IOException {
186 if (in.peek() == JsonToken.BEGIN_ARRAY) {
189 while (in.hasNext()) {
190 readEditDefinition(edit, in, path, codec);
191 resultCollection.add(prepareEditOperation(edit));
197 readEditDefinition(edit, in, path, codec);
198 resultCollection.add(prepareEditOperation(edit));
204 this.patchId = in.nextString();
212 * Read one patch edit object from Json input.
213 * @param edit PatchEdit instance to be filled with read data
214 * @param in JsonReader reader
215 * @param path InstanceIdentifierContext path context
216 * @param codec StringModuleInstanceIdentifierCodec codec
217 * @throws IOException if operation fails
219 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
220 @Nonnull final InstanceIdentifierContext<?> path,
221 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
222 final StringBuffer value = new StringBuffer();
225 while (in.hasNext()) {
226 final String editDefinition = in.nextName();
227 switch (editDefinition) {
229 edit.setId(in.nextString());
232 edit.setOperation(in.nextString());
235 // target can be specified completely in request URI
236 final String target = in.nextString();
237 if (target.equals("/")) {
238 edit.setTarget(path.getInstanceIdentifier());
239 edit.setTargetSchemaNode(path.getSchemaContext());
241 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
242 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
243 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
249 // save data defined in value node for next (later) processing, because target needs to be read
250 // always first and there is no ordering in Json input
251 readValueNode(value, in);
260 // read saved data to normalized node when target schema is already known
261 edit.setData(readEditData(new JsonReader(
262 new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
266 * Parse data defined in value node and saves it to buffer.
267 * @param value Buffer to read value node
268 * @param in JsonReader reader
269 * @throws IOException if operation fails
271 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
275 value.append("\"" + in.nextName() + "\"" + ":");
277 if (in.peek() == JsonToken.BEGIN_ARRAY) {
281 while (in.hasNext()) {
282 if (in.peek() == JsonToken.STRING) {
283 value.append("\"" + in.nextString() + "\"");
285 readValueObject(value, in);
287 if (in.peek() != JsonToken.END_ARRAY) {
295 readValueObject(value, in);
303 * Parse one value object of data and saves it to buffer.
304 * @param value Buffer to read value object
305 * @param in JsonReader reader
306 * @throws IOException if operation fails
308 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
309 // read simple leaf value
310 if (in.peek() == JsonToken.STRING) {
311 value.append("\"" + in.nextString() + "\"");
318 while (in.hasNext()) {
319 value.append("\"" + in.nextName() + "\"");
322 if (in.peek() == JsonToken.STRING) {
323 value.append("\"" + in.nextString() + "\"");
325 if (in.peek() == JsonToken.BEGIN_ARRAY) {
329 while (in.hasNext()) {
330 if (in.peek() == JsonToken.STRING) {
331 value.append("\"" + in.nextString() + "\"");
333 readValueObject(value, in);
335 if (in.peek() != JsonToken.END_ARRAY) {
343 readValueObject(value, in);
347 if (in.peek() != JsonToken.END_OBJECT) {
357 * Read patch edit data defined in value node to NormalizedNode.
358 * @param in reader JsonReader reader
359 * @return NormalizedNode representing data
361 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
362 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
363 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
364 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
365 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
367 return resultHolder.getResult();
371 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
372 * @param edit Instance of PatchEdit
373 * @return PatchEntity Patch entity
375 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
376 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
377 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
378 if (isPatchOperationWithValue(edit.getOperation())) {
379 // for lists allow to manipulate with list items through their parent
380 final YangInstanceIdentifier targetNode;
381 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
382 targetNode = edit.getTarget().getParent();
384 targetNode = edit.getTarget();
387 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
390 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
393 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
397 * Check if data is present when operation requires it and not present when operation data is not allowed.
398 * @param operation Name of operation
399 * @param hasData Data in edit are present/not present
400 * @return true if data is present when operation requires it or if there are no data when operation does not
401 * allow it, false otherwise
403 private static boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
404 return isPatchOperationWithValue(operation) == hasData;
408 * Helper class representing one patch edit.
410 private static final class PatchEdit {
412 private String operation;
413 private YangInstanceIdentifier target;
414 private SchemaNode targetSchemaNode;
415 private NormalizedNode<?, ?> data;
417 public String getId() {
421 public void setId(final String id) {
425 public String getOperation() {
426 return this.operation;
429 public void setOperation(final String operation) {
430 this.operation = operation;
433 public YangInstanceIdentifier getTarget() {
437 public void setTarget(final YangInstanceIdentifier target) {
438 this.target = target;
441 public SchemaNode getTargetSchemaNode() {
442 return this.targetSchemaNode;
445 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
446 this.targetSchemaNode = targetSchemaNode;
449 public NormalizedNode<?, ?> getData() {
453 public void setData(final NormalizedNode<?, ?> data) {
457 public void clear() {
459 this.operation = null;
461 this.targetSchemaNode = null;