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 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.JSON})
55 public class JsonToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<PATCHContext> {
57 private final static Logger LOG = LoggerFactory.getLogger(JsonToPATCHBodyReader.class);
58 private String patchId;
61 public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
66 public PATCHContext readFrom(Class<PATCHContext> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
68 return readFrom(getInstanceIdentifierContext(), entityStream);
69 } catch (final Exception e) {
70 throw propagateExceptionAs(e);
74 private static RuntimeException propagateExceptionAs(Exception e) throws RestconfDocumentedException {
75 if(e instanceof RestconfDocumentedException) {
76 throw (RestconfDocumentedException)e;
79 if(e instanceof ResultAlreadySetException) {
80 LOG.debug("Error parsing json input:", e);
82 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
85 throw new RestconfDocumentedException("Error parsing json input: " + e.getMessage(), ErrorType.PROTOCOL,
86 ErrorTag.MALFORMED_MESSAGE, e);
89 public PATCHContext readFrom(final String uriPath, final InputStream entityStream) throws
90 RestconfDocumentedException {
92 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
93 } catch (final Exception e) {
94 propagateExceptionAs(e);
99 private PATCHContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream) throws IOException {
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, patchId);
111 private List<PATCHEntity> read(final JsonReader in, InstanceIdentifierContext path) throws IOException {
112 List<PATCHEntity> resultCollection = new ArrayList<>();
113 StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(path.getSchemaContext());
114 JsonToPATCHBodyReader.PatchEdit edit = new JsonToPATCHBodyReader.PatchEdit();
116 while (in.hasNext()) {
123 Boolean.toString(in.nextBoolean());
137 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
151 return ImmutableList.copyOf(resultCollection);
155 * Switch value of parsed JsonToken.NAME and read edit definition or patch id
156 * @param name value of token
157 * @param edit PatchEdit instance
158 * @param in JsonReader reader
159 * @param path InstanceIdentifierContext context
160 * @param codec StringModuleInstanceIdentifierCodec codec
161 * @param resultCollection collection of parsed edits
162 * @throws IOException
164 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
165 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext path,
166 @Nonnull final StringModuleInstanceIdentifierCodec codec,
167 @Nonnull final List<PATCHEntity> resultCollection) throws IOException {
170 if (in.peek() == JsonToken.BEGIN_ARRAY) {
173 while (in.hasNext()) {
174 readEditDefinition(edit, in, path, codec);
175 resultCollection.add(prepareEditOperation(edit));
181 readEditDefinition(edit, in, path, codec);
182 resultCollection.add(prepareEditOperation(edit));
188 this.patchId = in.nextString();
196 * Read one patch edit object from Json input
197 * @param edit PatchEdit instance to be filled with read data
198 * @param in JsonReader reader
199 * @param path InstanceIdentifierContext path context
200 * @param codec StringModuleInstanceIdentifierCodec codec
201 * @throws IOException
203 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
204 @Nonnull final InstanceIdentifierContext path,
205 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
206 StringBuffer value = new StringBuffer();
209 while (in.hasNext()) {
210 final String editDefinition = in.nextName();
211 switch (editDefinition) {
213 edit.setId(in.nextString());
216 edit.setOperation(in.nextString());
219 // target can be specified completely in request URI
220 final String target = in.nextString();
221 if (target.equals("/")) {
222 edit.setTarget(path.getInstanceIdentifier());
223 edit.setTargetSchemaNode(path.getSchemaContext());
225 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
226 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
227 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
233 // save data defined in value node for next (later) processing, because target needs to be read
234 // always first and there is no ordering in Json input
235 readValueNode(value, in);
244 // read saved data to normalized node when target schema is already known
245 edit.setData(readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
249 * Parse data defined in value node and saves it to buffer
250 * @param value Buffer to read value node
251 * @param in JsonReader reader
252 * @throws IOException
254 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
258 value.append("\"" + in.nextName() + "\"" + ":");
260 if (in.peek() == JsonToken.BEGIN_ARRAY) {
264 while (in.hasNext()) {
265 readValueObject(value, in);
266 if (in.peek() != JsonToken.END_ARRAY) {
274 readValueObject(value, in);
282 * Parse one value object of data and saves it to buffer
283 * @param value Buffer to read value object
284 * @param in JsonReader reader
285 * @throws IOException
287 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
291 while (in.hasNext()) {
292 value.append("\"" + in.nextName() + "\"");
295 if (in.peek() == JsonToken.STRING) {
296 value.append("\"" + in.nextString() + "\"");
298 if (in.peek() == JsonToken.BEGIN_ARRAY) {
302 while (in.hasNext()) {
303 readValueObject(value, in);
304 if (in.peek() != JsonToken.END_ARRAY) {
312 readValueObject(value, in);
316 if (in.peek() != JsonToken.END_OBJECT) {
326 * Read patch edit data defined in value node to NormalizedNode
327 * @param in reader JsonReader reader
328 * @return NormalizedNode representing data
330 private NormalizedNode readEditData(@Nonnull final JsonReader in, @Nonnull SchemaNode targetSchemaNode,
331 @Nonnull InstanceIdentifierContext path) {
332 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
333 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
334 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
336 return resultHolder.getResult();
340 * Prepare PATCHEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception
341 * @param edit Instance of PatchEdit
342 * @return PATCHEntity
344 private PATCHEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
345 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
346 && checkDataPresence(edit.getOperation(), (edit.getData() != null))) {
347 if (isPatchOperationWithValue(edit.getOperation())) {
348 // for lists allow to manipulate with list items through their parent
349 YangInstanceIdentifier targetNode;
350 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
351 targetNode = edit.getTarget().getParent();
353 targetNode = edit.getTarget();
356 return new PATCHEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
358 return new PATCHEntity(edit.getId(), edit.getOperation(), edit.getTarget());
362 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
366 * Check if data is present when operation requires it and not present when operation data is not allowed
367 * @param operation Name of operation
368 * @param hasData Data in edit are present/not present
369 * @return true if data is present when operation requires it or if there are no data when operation does not
370 * allow it, false otherwise
372 private boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
373 if (isPatchOperationWithValue(operation)) {
389 * Helper class representing one patch edit
391 private static final class PatchEdit {
393 private String operation;
394 private YangInstanceIdentifier target;
395 private SchemaNode targetSchemaNode;
396 private NormalizedNode data;
398 public String getId() {
402 public void setId(String id) {
406 public String getOperation() {
410 public void setOperation(String operation) {
411 this.operation = operation;
414 public YangInstanceIdentifier getTarget() {
418 public void setTarget(YangInstanceIdentifier target) {
419 this.target = target;
422 public SchemaNode getTargetSchemaNode() {
423 return targetSchemaNode;
426 public void setTargetSchemaNode(SchemaNode targetSchemaNode) {
427 this.targetSchemaNode = targetSchemaNode;
430 public NormalizedNode getData() {
434 public void setData(NormalizedNode data) {
438 public void clear() {
442 targetSchemaNode = null;