Support for patch command
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / JSONRestconfServiceRfc8040Impl.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.lang.annotation.Annotation;
17 import java.nio.charset.StandardCharsets;
18 import java.util.List;
19 import javax.annotation.Nullable;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.core.MultivaluedMap;
22 import javax.ws.rs.core.Response;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
25 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.errors.RestconfError;
28 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
29 import org.opendaylight.restconf.common.patch.PatchContext;
30 import org.opendaylight.restconf.common.patch.PatchStatusContext;
31 import org.opendaylight.restconf.common.util.MultivaluedHashMap;
32 import org.opendaylight.restconf.common.util.SimpleUriInfo;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
35 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.JsonNormalizedNodeBodyReader;
36 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.NormalizedNodeJsonBodyWriter;
37 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch.JsonToPatchBodyReader;
38 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch.PatchJsonBodyWriter;
39 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.JSONRestconfService;
40 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.TransactionServicesWrapper;
41 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant;
42 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
43 import org.opendaylight.yangtools.yang.common.OperationFailedException;
44 import org.opendaylight.yangtools.yang.common.RpcError;
45 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
46 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Implementation of the JSONRestconfService interface using the restconf Draft18 implementation.
52  *
53  * @author Thomas Pantelis
54  */
55 public class JSONRestconfServiceRfc8040Impl implements JSONRestconfService, AutoCloseable {
56     private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceRfc8040Impl.class);
57
58     private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
59
60     private final TransactionServicesWrapper services;
61     private final DOMMountPointServiceHandler mountPointServiceHandler;
62
63     public JSONRestconfServiceRfc8040Impl(final TransactionServicesWrapper services,
64             final DOMMountPointServiceHandler mountPointServiceHandler) {
65         this.services = services;
66         this.mountPointServiceHandler = mountPointServiceHandler;
67     }
68
69     @SuppressWarnings("checkstyle:IllegalCatch")
70     @Override
71     public void put(final String uriPath, final String payload) throws OperationFailedException {
72         Preconditions.checkNotNull(payload, "payload can't be null");
73
74         LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
75
76         final NormalizedNodeContext context = toNormalizedNodeContext(uriPath, payload, false);
77
78         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
79         LOG.debug("Parsed NormalizedNode: {}", context.getData());
80
81         try {
82             services.putData(uriPath, context, new SimpleUriInfo(uriPath));
83         } catch (final Exception e) {
84             propagateExceptionAs(uriPath, e, "PUT");
85         }
86     }
87
88     @SuppressWarnings("checkstyle:IllegalCatch")
89     @Override
90     public void post(final String uriPath, final String payload)
91             throws OperationFailedException {
92         Preconditions.checkNotNull(payload, "payload can't be null");
93
94         LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
95
96         final NormalizedNodeContext context = toNormalizedNodeContext(uriPath, payload, true);
97
98         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
99         LOG.debug("Parsed NormalizedNode: {}", context.getData());
100
101         try {
102             services.postData(uriPath, context, new SimpleUriInfo(uriPath));
103         } catch (final Exception e) {
104             propagateExceptionAs(uriPath, e, "POST");
105         }
106     }
107
108     @SuppressWarnings("checkstyle:IllegalCatch")
109     @Override
110     public void delete(final String uriPath) throws OperationFailedException {
111         LOG.debug("delete: uriPath: {}", uriPath);
112
113         try {
114             services.deleteData(uriPath);
115         } catch (final Exception e) {
116             propagateExceptionAs(uriPath, e, "DELETE");
117         }
118     }
119
120     @SuppressWarnings("checkstyle:IllegalCatch")
121     @Override
122     public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType)
123             throws OperationFailedException {
124         LOG.debug("get: uriPath: {}", uriPath);
125
126         try {
127             final MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
128             queryParams.putSingle(RestconfDataServiceConstant.ReadData.CONTENT,
129                     datastoreType == LogicalDatastoreType.CONFIGURATION ? RestconfDataServiceConstant.ReadData.CONFIG :
130                         RestconfDataServiceConstant.ReadData.NONCONFIG);
131
132             final Response response = services.readData(uriPath, new SimpleUriInfo(uriPath, queryParams));
133             final NormalizedNodeContext readData = (NormalizedNodeContext) response.getEntity();
134
135             final Optional<String> result = Optional.of(toJson(readData));
136
137             LOG.debug("get returning: {}", result.get());
138
139             return result;
140         } catch (final Exception e) {
141             if (!isDataMissing(e)) {
142                 propagateExceptionAs(uriPath, e, "GET");
143             }
144
145             LOG.debug("Data missing - returning absent");
146             return Optional.absent();
147         }
148     }
149
150     @SuppressWarnings("checkstyle:IllegalCatch")
151     @Override
152     public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
153             throws OperationFailedException {
154         Preconditions.checkNotNull(uriPath, "uriPath can't be null");
155
156         final String actualInput = input.isPresent() ? input.get() : null;
157
158         LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
159
160         String output = null;
161         try {
162             final NormalizedNodeContext inputContext = toNormalizedNodeContext(uriPath, actualInput, true);
163
164             LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
165                     .getInstanceIdentifier());
166             LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
167
168             final NormalizedNodeContext outputContext =
169                     services.invokeRpc(uriPath, inputContext, new SimpleUriInfo(uriPath));
170
171             if (outputContext.getData() != null) {
172                 output = toJson(outputContext);
173             }
174         } catch (final Exception e) {
175             propagateExceptionAs(uriPath, e, "RPC");
176         }
177
178         return Optional.fromNullable(output);
179     }
180
181     @SuppressWarnings("checkstyle:IllegalCatch")
182     @Override
183     public Optional<String> patch(final String uriPath, final String payload)
184             throws OperationFailedException {
185
186         String output = null;
187         Preconditions.checkNotNull(payload, "payload can't be null");
188
189         LOG.debug("patch: uriPath: {}, payload: {}", uriPath, payload);
190
191         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
192
193         JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader();
194         final PatchContext context = jsonToPatchBodyReader.readFrom(uriPath, entityStream);
195
196         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
197         LOG.debug("Parsed NormalizedNode: {}", context.getData());
198
199         try {
200             PatchStatusContext patchStatusContext = services.patchData(context, new SimpleUriInfo(uriPath));
201             output = toJson(patchStatusContext);
202         } catch (final Exception e) {
203             propagateExceptionAs(uriPath, e, "PATCH");
204         }
205         return Optional.fromNullable(output);
206     }
207
208     @Override
209     public void close() {
210     }
211
212     private NormalizedNodeContext toNormalizedNodeContext(final String uriPath, @Nullable final String payload,
213             final boolean isPost) throws OperationFailedException {
214         final InstanceIdentifierContext<?> instanceIdentifierContext = ParserIdentifier.toInstanceIdentifier(
215                 uriPath, SchemaContextHandler.getActualSchemaContext(),
216                 Optional.of(mountPointServiceHandler.get()));
217
218         if (payload == null) {
219             return new NormalizedNodeContext(instanceIdentifierContext, null);
220         }
221
222         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
223         try {
224             return JsonNormalizedNodeBodyReader.readFrom(instanceIdentifierContext, entityStream, isPost);
225         } catch (final IOException e) {
226             propagateExceptionAs(uriPath, e, "GET");
227             return null;
228         }
229     }
230
231     private  String toJson(final PatchStatusContext patchStatusContext) throws IOException {
232         final PatchJsonBodyWriter writer = new PatchJsonBodyWriter();
233         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
234         writer.writeTo(patchStatusContext, PatchStatusContext.class, null, EMPTY_ANNOTATIONS,
235                 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
236         return outputStream.toString(StandardCharsets.UTF_8.name());
237     }
238
239     private static String toJson(final NormalizedNodeContext readData) throws IOException {
240         final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
241         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
242         writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
243                 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
244         return outputStream.toString(StandardCharsets.UTF_8.name());
245     }
246
247     private static boolean isDataMissing(final Exception exception) {
248         if (exception instanceof RestconfDocumentedException) {
249             final RestconfDocumentedException rde = (RestconfDocumentedException)exception;
250             return !rde.getErrors().isEmpty() && rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING;
251         }
252
253         return false;
254     }
255
256     private static void propagateExceptionAs(final String uriPath, final Exception exception, final String operation)
257             throws OperationFailedException {
258         LOG.debug("Error for uriPath: {}", uriPath, exception);
259
260         if (exception instanceof RestconfDocumentedException) {
261             throw new OperationFailedException(String.format(
262                     "%s failed for URI %s", operation, uriPath), exception.getCause(),
263                     toRpcErrors(((RestconfDocumentedException)exception).getErrors()));
264         }
265
266         throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
267     }
268
269     private static RpcError[] toRpcErrors(final List<RestconfError> from) {
270         final RpcError[] to = new RpcError[from.size()];
271         int index = 0;
272         for (final RestconfError e: from) {
273             to[index++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
274                     e.getErrorMessage());
275         }
276
277         return to;
278     }
279
280     private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
281         switch (errorType) {
282             case TRANSPORT:
283                 return ErrorType.TRANSPORT;
284             case RPC:
285                 return ErrorType.RPC;
286             case PROTOCOL:
287                 return ErrorType.PROTOCOL;
288             default:
289                 return ErrorType.APPLICATION;
290         }
291     }
292 }