64c482bf0e980bee8fe9035f94d825c3cd69c060
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / restconf / impl / JSONRestconfServiceImpl.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.netconf.sal.restconf.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
13 import java.io.ByteArrayInputStream;
14 import java.io.ByteArrayOutputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.lang.annotation.Annotation;
18 import java.nio.charset.StandardCharsets;
19 import java.util.List;
20 import javax.annotation.Nonnull;
21 import javax.ws.rs.core.MediaType;
22 import javax.ws.rs.core.MultivaluedMap;
23 import javax.ws.rs.core.UriInfo;
24
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.netconf.sal.rest.api.RestconfService;
27 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
28 import org.opendaylight.netconf.sal.rest.impl.JsonToPatchBodyReader;
29 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
30 import org.opendaylight.netconf.sal.rest.impl.PatchJsonBodyWriter;
31 import org.opendaylight.netconf.sal.restconf.api.JSONRestconfService;
32 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfError;
35 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
36 import org.opendaylight.restconf.common.patch.PatchContext;
37 import org.opendaylight.restconf.common.patch.PatchStatusContext;
38 import org.opendaylight.restconf.common.util.MultivaluedHashMap;
39 import org.opendaylight.restconf.common.util.SimpleUriInfo;
40 import org.opendaylight.yangtools.yang.common.OperationFailedException;
41 import org.opendaylight.yangtools.yang.common.RpcError;
42 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Implementation of the JSONRestconfService interface using the restconf Draft02 implementation.
49  *
50  * @author Thomas Pantelis
51  * @deprecated Replaced by {JSONRestconfServiceRfc8040Impl from restconf-nb-rfc8040
52  */
53 @Deprecated
54 public class JSONRestconfServiceImpl implements JSONRestconfService, AutoCloseable {
55     private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
56
57     private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
58
59     private final ControllerContext controllerContext;
60     private final RestconfService restconfService;
61
62     public JSONRestconfServiceImpl(ControllerContext controllerContext, RestconfService restconfService) {
63         this.controllerContext = controllerContext;
64         this.restconfService = restconfService;
65     }
66
67     @SuppressWarnings("checkstyle:IllegalCatch")
68     @Override
69     public void put(final String uriPath, final String payload) throws OperationFailedException {
70         Preconditions.checkNotNull(payload, "payload can't be null");
71
72         LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
73
74         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
75         final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false,
76                 controllerContext);
77
78         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
79         LOG.debug("Parsed NormalizedNode: {}", context.getData());
80
81         try {
82             restconfService.updateConfigurationData(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 InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
97         final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true,
98                 controllerContext);
99
100         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
101         LOG.debug("Parsed NormalizedNode: {}", context.getData());
102
103         try {
104             restconfService.createConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
105         } catch (final Exception e) {
106             propagateExceptionAs(uriPath, e, "POST");
107         }
108     }
109
110     @SuppressWarnings("checkstyle:IllegalCatch")
111     @Override
112     public void delete(final String uriPath) throws OperationFailedException {
113         LOG.debug("delete: uriPath: {}", uriPath);
114
115         try {
116             restconfService.deleteConfigurationData(uriPath);
117         } catch (final Exception e) {
118             propagateExceptionAs(uriPath, e, "DELETE");
119         }
120     }
121
122     @SuppressWarnings("checkstyle:IllegalCatch")
123     @Override
124     public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType)
125             throws OperationFailedException {
126         LOG.debug("get: uriPath: {}", uriPath);
127
128         try {
129             NormalizedNodeContext readData;
130             final SimpleUriInfo uriInfo = new SimpleUriInfo(uriPath);
131             if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
132                 readData = restconfService.readConfigurationData(uriPath, uriInfo);
133             } else {
134                 readData = restconfService.readOperationalData(uriPath, uriInfo);
135             }
136
137             final Optional<String> result = Optional.of(toJson(readData));
138
139             LOG.debug("get returning: {}", result.get());
140
141             return result;
142         } catch (final Exception e) {
143             if (!isDataMissing(e)) {
144                 propagateExceptionAs(uriPath, e, "GET");
145             }
146
147             LOG.debug("Data missing - returning absent");
148             return Optional.absent();
149         }
150     }
151
152     @SuppressWarnings("checkstyle:IllegalCatch")
153     @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Unrecognised NullableDecl")
154     @Override
155     public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
156             throws OperationFailedException {
157         Preconditions.checkNotNull(uriPath, "uriPath can't be null");
158
159         final String actualInput = input.isPresent() ? input.get() : null;
160
161         LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
162
163         String output = null;
164         try {
165             NormalizedNodeContext outputContext;
166             if (actualInput != null) {
167                 final InputStream entityStream = new ByteArrayInputStream(actualInput.getBytes(StandardCharsets.UTF_8));
168                 final NormalizedNodeContext inputContext =
169                         JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true, controllerContext);
170
171                 LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
172                         .getInstanceIdentifier());
173                 LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
174
175                 outputContext = restconfService.invokeRpc(uriPath, inputContext, null);
176             } else {
177                 outputContext = restconfService.invokeRpc(uriPath, "", null);
178             }
179
180             if (outputContext.getData() != null) {
181                 output = toJson(outputContext);
182             }
183         } catch (final RuntimeException | IOException e) {
184             propagateExceptionAs(uriPath, e, "RPC");
185         }
186
187         return Optional.fromNullable(output);
188     }
189
190     @SuppressWarnings("checkstyle:IllegalCatch")
191     @Override
192     public Optional<String> patch(final String uriPath, final String payload)
193             throws OperationFailedException {
194
195         String output = null;
196         Preconditions.checkNotNull(payload, "payload can't be null");
197
198         LOG.debug("patch: uriPath: {}, payload: {}", uriPath, payload);
199
200         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
201
202         JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader(controllerContext);
203         final PatchContext context = jsonToPatchBodyReader.readFrom(uriPath, entityStream);
204
205         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
206         LOG.debug("Parsed NormalizedNode: {}", context.getData());
207
208         try {
209             PatchStatusContext patchStatusContext = restconfService
210                 .patchConfigurationData(context, new SimpleUriInfo(uriPath));
211             output = toJson(patchStatusContext);
212         } catch (final Exception e) {
213             propagateExceptionAs(uriPath, e, "PATCH");
214         }
215         return Optional.fromNullable(output);
216     }
217
218     @SuppressWarnings("checkstyle:IllegalCatch")
219     @Override
220     public Optional<String> subscribeToStream(@Nonnull String identifier,
221                                       MultivaluedMap<String, String> params) throws OperationFailedException {
222         //Note: We use http://127.0.0.1 because the Uri parser requires something there though it does nothing
223         String uri = new StringBuilder("http://127.0.0.1:8081/restconf/streams/stream/").append(identifier).toString();
224         MultivaluedMap queryParams = (params != null) ? params : new MultivaluedHashMap<String, String>();
225         UriInfo uriInfo = new SimpleUriInfo(uri, queryParams);
226
227         String jsonRes = null;
228         try {
229             NormalizedNodeContext res = restconfService.subscribeToStream(identifier, uriInfo);
230             jsonRes = toJson(res);
231         } catch (final Exception e) {
232             propagateExceptionAs(identifier, e, "RPC");
233         }
234
235         return Optional.fromNullable(jsonRes);
236     }
237
238     @Override
239     public void close() {
240     }
241
242     private  String toJson(final PatchStatusContext patchStatusContext) throws IOException {
243         final PatchJsonBodyWriter writer = new PatchJsonBodyWriter();
244         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
245         writer.writeTo(patchStatusContext, PatchStatusContext.class, null, EMPTY_ANNOTATIONS,
246                 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
247         return outputStream.toString(StandardCharsets.UTF_8.name());
248     }
249
250     private static String toJson(final NormalizedNodeContext readData) throws IOException {
251         final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
252         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
253         writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
254                 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
255         return outputStream.toString(StandardCharsets.UTF_8.name());
256     }
257
258     private static boolean isDataMissing(final Exception exception) {
259         boolean dataMissing = false;
260         if (exception instanceof RestconfDocumentedException) {
261             final RestconfDocumentedException rde = (RestconfDocumentedException)exception;
262             if (!rde.getErrors().isEmpty()) {
263                 if (rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
264                     dataMissing = true;
265                 }
266             }
267         }
268
269         return dataMissing;
270     }
271
272     private static void propagateExceptionAs(final String uriPath, final Exception exception, final String operation)
273             throws OperationFailedException {
274         LOG.debug("Error for uriPath: {}", uriPath, exception);
275
276         if (exception instanceof RestconfDocumentedException) {
277             throw new OperationFailedException(String.format(
278                     "%s failed for URI %s", operation, uriPath), exception.getCause(),
279                     toRpcErrors(((RestconfDocumentedException)exception).getErrors()));
280         }
281
282         throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
283     }
284
285     private static RpcError[] toRpcErrors(final List<RestconfError> from) {
286         final RpcError[] to = new RpcError[from.size()];
287         int index = 0;
288         for (final RestconfError e: from) {
289             to[index++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
290                     e.getErrorMessage());
291         }
292
293         return to;
294     }
295
296     private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
297         switch (errorType) {
298             case TRANSPORT: {
299                 return ErrorType.TRANSPORT;
300             }
301             case RPC: {
302                 return ErrorType.RPC;
303             }
304             case PROTOCOL: {
305                 return ErrorType.PROTOCOL;
306             }
307             default: {
308                 return ErrorType.APPLICATION;
309             }
310         }
311     }
312 }