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 final static 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) {
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 static RuntimeException propagateExceptionAs(final Exception e) throws RestconfDocumentedException {
80 if (e instanceof RestconfDocumentedException) {
81 throw (RestconfDocumentedException)e;
84 if (e instanceof ResultAlreadySetException) {
85 LOG.debug("Error parsing json input:", e);
86 throw new RestconfDocumentedException("Error parsing json input: Failed to create new parse result data. ");
89 throw new RestconfDocumentedException("Error parsing json input: " + e.getMessage(), ErrorType.PROTOCOL,
90 ErrorTag.MALFORMED_MESSAGE, e);
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 PATCHContext readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream)
105 if (entityStream.available() < 1) {
106 return new PATCHContext(path, null, null);
109 final JsonReader jsonReader = new JsonReader(new InputStreamReader(entityStream));
110 final List<PATCHEntity> resultList = read(jsonReader, path);
113 return new PATCHContext(path, resultList, patchId);
116 private List<PATCHEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
117 final List<PATCHEntity> resultCollection = new ArrayList<>();
118 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
119 path.getSchemaContext());
120 final JsonToPATCHBodyReader.PatchEdit edit = new JsonToPATCHBodyReader.PatchEdit();
122 while (in.hasNext()) {
129 Boolean.toString(in.nextBoolean());
143 parseByName(in.nextName(), edit, in, path, codec, resultCollection);
157 return ImmutableList.copyOf(resultCollection);
161 * Switch value of parsed JsonToken.NAME and read edit definition or patch id
162 * @param name value of token
163 * @param edit PatchEdit instance
164 * @param in JsonReader reader
165 * @param path InstanceIdentifierContext context
166 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
167 * @param resultCollection collection of parsed edits
168 * @throws IOException
170 private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
171 @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext path,
172 @Nonnull final StringModuleInstanceIdentifierCodec codec,
173 @Nonnull final List<PATCHEntity> resultCollection) throws IOException {
176 if (in.peek() == JsonToken.BEGIN_ARRAY) {
179 while (in.hasNext()) {
180 readEditDefinition(edit, in, path, codec);
181 resultCollection.add(prepareEditOperation(edit));
187 readEditDefinition(edit, in, path, codec);
188 resultCollection.add(prepareEditOperation(edit));
194 this.patchId = in.nextString();
202 * Read one patch edit object from Json input
203 * @param edit PatchEdit instance to be filled with read data
204 * @param in JsonReader reader
205 * @param path InstanceIdentifierContext path context
206 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
207 * @throws IOException
209 private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
210 @Nonnull final InstanceIdentifierContext path,
211 @Nonnull final StringModuleInstanceIdentifierCodec codec) throws IOException {
212 final StringBuffer value = new StringBuffer();
215 while (in.hasNext()) {
216 final String editDefinition = in.nextName();
217 switch (editDefinition) {
219 edit.setId(in.nextString());
222 edit.setOperation(in.nextString());
225 // target can be specified completely in request URI
226 final String target = in.nextString();
227 if (target.equals("/")) {
228 edit.setTarget(path.getInstanceIdentifier());
229 edit.setTargetSchemaNode(path.getSchemaContext());
231 edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
232 edit.setTargetSchemaNode(SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(),
233 codec.getDataContextTree().getChild(edit.getTarget()).getDataSchemaNode().getPath()
239 // save data defined in value node for next (later) processing, because target needs to be read
240 // always first and there is no ordering in Json input
241 readValueNode(value, in);
250 // read saved data to normalized node when target schema is already known
251 edit.setData(readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
255 * Parse data defined in value node and saves it to buffer
256 * @param value Buffer to read value node
257 * @param in JsonReader reader
258 * @throws IOException
260 private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
264 value.append("\"" + in.nextName() + "\"" + ":");
266 if (in.peek() == JsonToken.BEGIN_ARRAY) {
270 while (in.hasNext()) {
271 readValueObject(value, in);
272 if (in.peek() != JsonToken.END_ARRAY) {
280 readValueObject(value, in);
288 * Parse one value object of data and saves it to buffer
289 * @param value Buffer to read value object
290 * @param in JsonReader reader
291 * @throws IOException
293 private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
297 while (in.hasNext()) {
298 value.append("\"" + in.nextName() + "\"");
301 if (in.peek() == JsonToken.STRING) {
302 value.append("\"" + in.nextString() + "\"");
304 if (in.peek() == JsonToken.BEGIN_ARRAY) {
308 while (in.hasNext()) {
309 readValueObject(value, in);
310 if (in.peek() != JsonToken.END_ARRAY) {
318 readValueObject(value, in);
322 if (in.peek() != JsonToken.END_OBJECT) {
332 * Read patch edit data defined in value node to NormalizedNode
333 * @param in reader JsonReader reader
334 * @return NormalizedNode representing data
336 private NormalizedNode readEditData(@Nonnull final JsonReader in, @Nonnull SchemaNode targetSchemaNode,
337 @Nonnull InstanceIdentifierContext path) {
338 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
339 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
340 JsonParserStream.create(writer, path.getSchemaContext(), targetSchemaNode).parse(in);
342 return resultHolder.getResult();
346 * Prepare PATCHEntity from PatchEdit instance when it satisfies conditions, otherwise throws exception
347 * @param edit Instance of PatchEdit
348 * @return PATCHEntity
350 private PATCHEntity prepareEditOperation(@Nonnull final PatchEdit edit) {
351 if (edit.getOperation() != null && edit.getTargetSchemaNode() != null
352 && checkDataPresence(edit.getOperation(), (edit.getData() != null))) {
353 if (isPatchOperationWithValue(edit.getOperation())) {
354 // for lists allow to manipulate with list items through their parent
355 final YangInstanceIdentifier targetNode;
356 if (edit.getTarget().getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
357 targetNode = edit.getTarget().getParent();
359 targetNode = edit.getTarget();
362 return new PATCHEntity(edit.getId(), edit.getOperation(), targetNode, edit.getData());
364 return new PATCHEntity(edit.getId(), edit.getOperation(), edit.getTarget());
368 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
372 * Check if data is present when operation requires it and not present when operation data is not allowed
373 * @param operation Name of operation
374 * @param hasData Data in edit are present/not present
375 * @return true if data is present when operation requires it or if there are no data when operation does not
376 * allow it, false otherwise
378 private boolean checkDataPresence(@Nonnull final String operation, final boolean hasData) {
379 if (isPatchOperationWithValue(operation)) {
395 * Helper class representing one patch edit
397 private static final class PatchEdit {
399 private String operation;
400 private YangInstanceIdentifier target;
401 private SchemaNode targetSchemaNode;
402 private NormalizedNode data;
404 public String getId() {
408 public void setId(String id) {
412 public String getOperation() {
416 public void setOperation(String operation) {
417 this.operation = operation;
420 public YangInstanceIdentifier getTarget() {
424 public void setTarget(YangInstanceIdentifier target) {
425 this.target = target;
428 public SchemaNode getTargetSchemaNode() {
429 return targetSchemaNode;
432 public void setTargetSchemaNode(SchemaNode targetSchemaNode) {
433 this.targetSchemaNode = targetSchemaNode;
436 public NormalizedNode getData() {
440 public void setData(NormalizedNode data) {
444 public void clear() {
448 targetSchemaNode = null;