2 * Copyright (c) 2016 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.restconf.jersey.providers;
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.restconf.impl.ControllerContext;
30 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
31 import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
32 import org.opendaylight.netconf.sal.restconf.impl.PatchEditOperation;
33 import org.opendaylight.netconf.sal.restconf.impl.PatchEntity;
34 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
37 import org.opendaylight.restconf.Rfc8040;
38 import org.opendaylight.restconf.utils.RestconfConstants;
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 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
54 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
55 implements MessageBodyReader<PatchContext> {
57 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
58 private String patchId;
61 public boolean isReadable(final Class<?> type, final Type genericType,
62 final Annotation[] annotations, final MediaType mediaType) {
66 @SuppressWarnings("checkstyle:IllegalCatch")
68 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
69 final Annotation[] annotations, final MediaType mediaType,
70 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
71 throws IOException, WebApplicationException {
73 return readFrom(getInstanceIdentifierContext(), entityStream);
74 } catch (final Exception e) {
75 throw propagateExceptionAs(e);
79 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
81 if (entityStream.available() < 1) {
82 return new PatchContext(path, null, null);
85 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
86 final List<PatchEntity> resultList = read(jsonReader, path);
89 return new PatchContext(path, resultList, patchId);
92 @SuppressWarnings("checkstyle:IllegalCatch")
93 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
94 RestconfDocumentedException {
96 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
97 } catch (final Exception e) {
98 propagateExceptionAs(e);
103 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
104 if (exception instanceof RestconfDocumentedException) {
105 throw (RestconfDocumentedException)exception;
108 if (exception instanceof ResultAlreadySetException) {
109 LOG.debug("Error parsing json input:", exception);
110 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
113 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
114 ErrorTag.MALFORMED_MESSAGE, exception);
117 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
118 final List<PatchEntity> resultCollection = new ArrayList<>();
119 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
120 path.getSchemaContext());
121 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
123 while (in.hasNext()) {
130 Boolean.toString(in.nextBoolean());
144 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
158 return ImmutableList.copyOf(resultCollection);
162 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
164 * @param name value of token
165 * @param edit PatchEdit instance
166 * @param in JsonReader reader
167 * @param path InstanceIdentifierContext context
168 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
169 * @param resultCollection collection of parsed edits
170 * @throws IOException if operation fails
172 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
173 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
174 @Nonnull final StringModuleInstanceIdentifierCodec codec,
175 @Nonnull final List<PatchEntity> resultCollection) throws IOException {
178 if (in.peek() == JsonToken.BEGIN_ARRAY) {
181 while (in.hasNext()) {
182 readEditDefinition(edit, in, path, codec);
183 resultCollection.add(prepareEditOperation(edit));
189 readEditDefinition(edit, in, path, codec);
190 resultCollection.add(prepareEditOperation(edit));
196 this.patchId = in.nextString();
204 * Read one patch edit object from Json input.
206 * @param edit PatchEdit instance to be filled with read data
207 * @param in JsonReader reader
208 * @param path InstanceIdentifierContext path context
209 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
210 * @throws IOException if operation fails
212 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
213 @Nonnull final InstanceIdentifierContext<?> path,
214 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
215 final StringBuilder sb = new StringBuilder();
218 while (in.hasNext()) {
219 final String editDefinition = in.nextName();
220 switch (editDefinition) {
222 edit.setId(in.nextString());
225 edit.setOperation(PatchEditOperation.valueOf(in.nextString().toUpperCase()));
228 // target can be specified completely in request URI
229 final String target = in.nextString();
230 if (target.equals("/")) {
231 edit.setTarget(path.getInstanceIdentifier());
232 edit.setTargetSchemaNode(path.getSchemaContext());
234 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
235 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
236 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
242 // save data defined in value node for next (later) processing, because target needs to be read
243 // always first and there is no ordering in Json input
244 readValueNode(sb, in);
253 // read saved data to normalized node when target schema is already known
255 readEditData(new JsonReader(new StringReader(sb.toString())), edit.getTargetSchemaNode(), path));
259 * Parse data defined in value node and saves it to buffer.
260 * @param sb Buffer to read value node
261 * @param in JsonReader reader
262 * @throws IOException if operation fails
264 private void readValueNode(@Nonnull final StringBuilder sb, @Nonnull final JsonReader in) throws IOException {
267 sb.append("{\"").append(in.nextName()).append("\":");
274 while (in.hasNext()) {
275 if (in.peek() == JsonToken.STRING) {
276 sb.append('"').append(in.nextString()).append('"');
278 readValueObject(sb, in);
280 if (in.peek() != JsonToken.END_ARRAY) {
289 readValueObject(sb, in);
298 * Parse one value object of data and saves it to buffer.
299 * @param sb Buffer to read value object
300 * @param in JsonReader reader
301 * @throws IOException if operation fails
303 private void readValueObject(@Nonnull final StringBuilder sb, @Nonnull final JsonReader in) throws IOException {
304 // read simple leaf value
305 if (in.peek() == JsonToken.STRING) {
306 sb.append('"').append(in.nextString()).append('"');
313 while (in.hasNext()) {
314 sb.append('"').append(in.nextName()).append("\":");
318 sb.append('"').append(in.nextString()).append('"');
324 while (in.hasNext()) {
325 if (in.peek() == JsonToken.STRING) {
326 sb.append('"').append(in.nextString()).append('"');
328 readValueObject(sb, in);
331 if (in.peek() != JsonToken.END_ARRAY) {
340 readValueObject(sb, in);
343 if (in.peek() != JsonToken.END_OBJECT) {
353 * Read patch edit data defined in value node to NormalizedNode.
354 * @param in reader JsonReader reader
355 * @return NormalizedNode representing data
357 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
358 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
359 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
360 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
361 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
363 return resultHolder.getResult();
367 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
368 * @param edit Instance of PatchEdit
369 * @return PatchEntity Patch entity
371 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
372 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
373 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
374 if (!edit.getOperation().isWithValue()) {
375 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
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 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
393 * Check if data is present when operation requires it and not present when operation data is not allowed.
394 * @param operation Name of operation
395 * @param hasData Data in edit are present/not present
396 * @return true if data is present when operation requires it or if there are no data when operation does not
397 * allow it, false otherwise
399 private static boolean checkDataPresence(@Nonnull final PatchEditOperation operation, final boolean hasData) {
400 return operation.isWithValue() == hasData;
404 * Helper class representing one patch edit.
406 private static final class PatchEdit {
408 private PatchEditOperation operation;
409 private YangInstanceIdentifier target;
410 private SchemaNode targetSchemaNode;
411 private NormalizedNode<?, ?> data;
413 public String getId() {
417 public void setId(final String id) {
421 public PatchEditOperation getOperation() {
425 public void setOperation(final PatchEditOperation operation) {
426 this.operation = operation;
429 public YangInstanceIdentifier getTarget() {
433 public void setTarget(final YangInstanceIdentifier target) {
434 this.target = target;
437 public SchemaNode getTargetSchemaNode() {
438 return targetSchemaNode;
441 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
442 this.targetSchemaNode = targetSchemaNode;
445 public NormalizedNode<?, ?> getData() {
449 public void setData(final NormalizedNode<?, ?> data) {
453 public void clear() {
457 targetSchemaNode = null;