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 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.restconf.impl.ControllerContext;
32 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
33 import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
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.Rfc8040;
39 import org.opendaylight.restconf.utils.RestconfConstants;
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({Rfc8040.MediaTypes.PATCH + RestconfConstants.JSON})
55 public class JsonToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider
56 implements MessageBodyReader<PatchContext> {
58 private static final Logger LOG = LoggerFactory.getLogger(JsonToPatchBodyReader.class);
59 private String patchId;
62 public boolean isReadable(final Class<?> type, final Type genericType,
63 final Annotation[] annotations, final MediaType mediaType) {
67 @SuppressWarnings("checkstyle:IllegalCatch")
69 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
70 final Annotation[] annotations, final MediaType mediaType,
71 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
72 throws IOException, WebApplicationException {
74 return readFrom(getInstanceIdentifierContext(), entityStream);
75 } catch (final Exception e) {
76 throw propagateExceptionAs(e);
80 private PatchContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
82 if (entityStream.available() < 1) {
83 return new PatchContext(path, null, null);
86 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
87 final List<PatchEntity> resultList = read(jsonReader, path);
90 return new PatchContext(path, resultList, patchId);
93 @SuppressWarnings("checkstyle:IllegalCatch")
94 public PatchContext readFrom(final String uriPath, final InputStream entityStream) throws
95 RestconfDocumentedException {
97 return readFrom(ControllerContext.getInstance().toInstanceIdentifier(uriPath), entityStream);
98 } catch (final Exception e) {
99 propagateExceptionAs(e);
100 return null; // no-op
104 private static RuntimeException propagateExceptionAs(final Exception exception) throws RestconfDocumentedException {
105 if (exception instanceof RestconfDocumentedException) {
106 throw (RestconfDocumentedException)exception;
109 if (exception instanceof ResultAlreadySetException) {
110 LOG.debug("Error parsing json input:", exception);
111 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
114 throw new RestconfDocumentedException("Error parsing json input: " + exception.getMessage(), ErrorType.PROTOCOL,
115 ErrorTag.MALFORMED_MESSAGE, exception);
118 private List<PatchEntity> read(final JsonReader in, final InstanceIdentifierContext<?> path) throws IOException {
119 final List<PatchEntity> resultCollection = new ArrayList<>();
120 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
121 path.getSchemaContext());
122 final JsonToPatchBodyReader.PatchEdit edit = new JsonToPatchBodyReader.PatchEdit();
124 while (in.hasNext()) {
131 Boolean.toString(in.nextBoolean());
145 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
159 return ImmutableList.copyOf(resultCollection);
163 * Switch value of parsed JsonToken.NAME and read edit definition or patch id.
165 * @param name value of token
166 * @param edit PatchEdit instance
167 * @param in JsonReader reader
168 * @param path InstanceIdentifierContext context
169 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
170 * @param resultCollection collection of parsed edits
171 * @throws IOException if operation fails
173 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
174 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext<?> path,
175 @Nonnull final StringModuleInstanceIdentifierCodec codec,
176 @Nonnull final List<PatchEntity> resultCollection) throws IOException {
179 if (in.peek() == JsonToken.BEGIN_ARRAY) {
182 while (in.hasNext()) {
183 readEditDefinition(edit, in, path, codec);
184 resultCollection.add(prepareEditOperation(edit));
190 readEditDefinition(edit, in, path, codec);
191 resultCollection.add(prepareEditOperation(edit));
197 this.patchId = in.nextString();
205 * Read one patch edit object from Json input.
207 * @param edit PatchEdit instance to be filled with read data
208 * @param in JsonReader reader
209 * @param path InstanceIdentifierContext path context
210 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
211 * @throws IOException if operation fails
213 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
214 @Nonnull final InstanceIdentifierContext<?> path,
215 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
216 final StringBuffer value = new StringBuffer();
219 while (in.hasNext()) {
220 final String editDefinition = in.nextName();
221 switch (editDefinition) {
223 edit.setId(in.nextString());
226 edit.setOperation(in.nextString());
229 // target can be specified completely in request URI
230 final String target = in.nextString();
231 if (target.equals("/")) {
232 edit.setTarget(path.getInstanceIdentifier());
233 edit.setTargetSchemaNode(path.getSchemaContext());
235 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
236 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
237 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
243 // save data defined in value node for next (later) processing, because target needs to be read
244 // always first and there is no ordering in Json input
245 readValueNode(value, in);
254 // read saved data to normalized node when target schema is already known
256 readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
260 * Parse data defined in value node and saves it to buffer.
261 * @param value Buffer to read value node
262 * @param in JsonReader reader
263 * @throws IOException if operation fails
265 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
269 value.append("\"" + in.nextName() + "\"" + ":");
271 if (in.peek() == JsonToken.BEGIN_ARRAY) {
275 while (in.hasNext()) {
276 if (in.peek() == JsonToken.STRING) {
277 value.append("\"" + in.nextString() + "\"");
279 readValueObject(value, in);
281 if (in.peek() != JsonToken.END_ARRAY) {
289 readValueObject(value, in);
297 * Parse one value object of data and saves it to buffer.
298 * @param value Buffer to read value object
299 * @param in JsonReader reader
300 * @throws IOException if operation fails
302 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
303 // read simple leaf value
304 if (in.peek() == JsonToken.STRING) {
305 value.append("\"" + in.nextString() + "\"");
312 while (in.hasNext()) {
313 value.append("\"" + in.nextName() + "\"");
316 if (in.peek() == JsonToken.STRING) {
317 value.append("\"" + in.nextString() + "\"");
319 if (in.peek() == JsonToken.BEGIN_ARRAY) {
323 while (in.hasNext()) {
324 if (in.peek() == JsonToken.STRING) {
325 value.append("\"" + in.nextString() + "\"");
327 readValueObject(value, in);
329 if (in.peek() != JsonToken.END_ARRAY) {
337 readValueObject(value, in);
341 if (in.peek() != JsonToken.END_OBJECT) {
351 * Read patch edit data defined in value node to NormalizedNode.
352 * @param in reader JsonReader reader
353 * @return NormalizedNode representing data
355 private static NormalizedNode<?, ?> readEditData(@Nonnull final JsonReader in,
356 @Nonnull final SchemaNode targetSchemaNode, @Nonnull final InstanceIdentifierContext<?> path) {
357 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
358 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
359 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
361 return resultHolder.getResult();
365 * Prepare PatchEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception.
366 * @param edit Instance of PatchEdit
367 * @return PatchEntity Patch entity
369 private static PatchEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
370 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
371 && checkDataPresence(edit.getOperation(), edit.getData() != null)) {
372 if (!isPatchOperationWithValue(edit.getOperation())) {
373 return new PatchEntity(edit.getId(), edit.getOperation(), edit.getTarget());
376 // for lists allow to manipulate with list items through their parent
377 final YangInstanceIdentifier targetNode;
378 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
379 targetNode = edit.getTarget().getParent();
381 targetNode = edit.getTarget();
384 return new PatchEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
387 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
391 * Check if data is present when operation requires it and not present when operation data is not allowed.
392 * @param operation Name of operation
393 * @param hasData Data in edit are present/not present
394 * @return true if data is present when operation requires it or if there are no data when operation does not
395 * allow it, false otherwise
397 private static boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
398 return isPatchOperationWithValue(operation) == hasData;
402 * Helper class representing one patch edit.
404 private static final class PatchEdit {
406 private String operation;
407 private YangInstanceIdentifier target;
408 private SchemaNode targetSchemaNode;
409 private NormalizedNode<?, ?> data;
411 public String getId() {
415 public void setId(final String id) {
419 public String getOperation() {
423 public void setOperation(final String operation) {
424 this.operation = operation;
427 public YangInstanceIdentifier getTarget() {
431 public void setTarget(final YangInstanceIdentifier target) {
432 this.target = target;
435 public SchemaNode getTargetSchemaNode() {
436 return targetSchemaNode;
439 public void setTargetSchemaNode(final SchemaNode targetSchemaNode) {
440 this.targetSchemaNode = targetSchemaNode;
443 public NormalizedNode<?, ?> getData() {
447 public void setData(final NormalizedNode<?, ?> data) {
451 public void clear() {
455 targetSchemaNode = null;