Bump to odlparent 3.1.0 and yangtools 2.0.3
[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.ws.rs.core.MediaType;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
23 import org.opendaylight.netconf.sal.rest.impl.JsonToPatchBodyReader;
24 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
25 import org.opendaylight.netconf.sal.rest.impl.PatchJsonBodyWriter;
26 import org.opendaylight.netconf.sal.restconf.api.JSONRestconfService;
27 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.common.errors.RestconfError;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
31 import org.opendaylight.restconf.common.patch.PatchContext;
32 import org.opendaylight.restconf.common.patch.PatchStatusContext;
33 import org.opendaylight.restconf.common.util.SimpleUriInfo;
34 import org.opendaylight.yangtools.yang.common.OperationFailedException;
35 import org.opendaylight.yangtools.yang.common.RpcError;
36 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
37 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Implementation of the JSONRestconfService interface using the restconf Draft02 implementation.
43  *
44  * @author Thomas Pantelis
45  * @deprecated Replaced by {JSONRestconfServiceRfc8040Impl from restconf-nb-rfc8040
46  */
47 @Deprecated
48 public class JSONRestconfServiceImpl implements JSONRestconfService, AutoCloseable {
49     private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
50
51     private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
52
53     @SuppressWarnings("checkstyle:IllegalCatch")
54     @Override
55     public void put(final String uriPath, final String payload) throws OperationFailedException {
56         Preconditions.checkNotNull(payload, "payload can't be null");
57
58         LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
59
60         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
61         final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false);
62
63         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
64         LOG.debug("Parsed NormalizedNode: {}", context.getData());
65
66         try {
67             RestconfImpl.getInstance().updateConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
68         } catch (final Exception e) {
69             propagateExceptionAs(uriPath, e, "PUT");
70         }
71     }
72
73     @SuppressWarnings("checkstyle:IllegalCatch")
74     @Override
75     public void post(final String uriPath, final String payload)
76             throws OperationFailedException {
77         Preconditions.checkNotNull(payload, "payload can't be null");
78
79         LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
80
81         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
82         final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
83
84         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
85         LOG.debug("Parsed NormalizedNode: {}", context.getData());
86
87         try {
88             RestconfImpl.getInstance().createConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
89         } catch (final Exception e) {
90             propagateExceptionAs(uriPath, e, "POST");
91         }
92     }
93
94     @SuppressWarnings("checkstyle:IllegalCatch")
95     @Override
96     public void delete(final String uriPath) throws OperationFailedException {
97         LOG.debug("delete: uriPath: {}", uriPath);
98
99         try {
100             RestconfImpl.getInstance().deleteConfigurationData(uriPath);
101         } catch (final Exception e) {
102             propagateExceptionAs(uriPath, e, "DELETE");
103         }
104     }
105
106     @SuppressWarnings("checkstyle:IllegalCatch")
107     @Override
108     public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType)
109             throws OperationFailedException {
110         LOG.debug("get: uriPath: {}", uriPath);
111
112         try {
113             NormalizedNodeContext readData;
114             final SimpleUriInfo uriInfo = new SimpleUriInfo(uriPath);
115             if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
116                 readData = RestconfImpl.getInstance().readConfigurationData(uriPath, uriInfo);
117             } else {
118                 readData = RestconfImpl.getInstance().readOperationalData(uriPath, uriInfo);
119             }
120
121             final Optional<String> result = Optional.of(toJson(readData));
122
123             LOG.debug("get returning: {}", result.get());
124
125             return result;
126         } catch (final Exception e) {
127             if (!isDataMissing(e)) {
128                 propagateExceptionAs(uriPath, e, "GET");
129             }
130
131             LOG.debug("Data missing - returning absent");
132             return Optional.absent();
133         }
134     }
135
136     @SuppressWarnings("checkstyle:IllegalCatch")
137     @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Unrecognised NullableDecl")
138     @Override
139     public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
140             throws OperationFailedException {
141         Preconditions.checkNotNull(uriPath, "uriPath can't be null");
142
143         final String actualInput = input.isPresent() ? input.get() : null;
144
145         LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
146
147         String output = null;
148         try {
149             NormalizedNodeContext outputContext;
150             if (actualInput != null) {
151                 final InputStream entityStream = new ByteArrayInputStream(actualInput.getBytes(StandardCharsets.UTF_8));
152                 final NormalizedNodeContext inputContext =
153                         JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
154
155                 LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
156                         .getInstanceIdentifier());
157                 LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
158
159                 outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, inputContext, null);
160             } else {
161                 outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, "", null);
162             }
163
164             if (outputContext.getData() != null) {
165                 output = toJson(outputContext);
166             }
167         } catch (final RuntimeException | IOException e) {
168             propagateExceptionAs(uriPath, e, "RPC");
169         }
170
171         return Optional.fromNullable(output);
172     }
173
174     @SuppressWarnings("checkstyle:IllegalCatch")
175     @Override
176     public Optional<String> patch(final String uriPath, final String payload)
177             throws OperationFailedException {
178
179         String output = null;
180         Preconditions.checkNotNull(payload, "payload can't be null");
181
182         LOG.debug("patch: uriPath: {}, payload: {}", uriPath, payload);
183
184         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
185
186         JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader();
187         final PatchContext context = jsonToPatchBodyReader.readFrom(uriPath, entityStream);
188
189         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
190         LOG.debug("Parsed NormalizedNode: {}", context.getData());
191
192         try {
193             PatchStatusContext patchStatusContext = RestconfImpl.getInstance()
194                 .patchConfigurationData(context, new SimpleUriInfo(uriPath));
195             output = toJson(patchStatusContext);
196         } catch (final Exception e) {
197             propagateExceptionAs(uriPath, e, "PATCH");
198         }
199         return Optional.fromNullable(output);
200     }
201
202     @Override
203     public void close() {
204     }
205
206     private  String toJson(final PatchStatusContext patchStatusContext) throws IOException {
207         final PatchJsonBodyWriter writer = new PatchJsonBodyWriter();
208         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
209         writer.writeTo(patchStatusContext, PatchStatusContext.class, null, EMPTY_ANNOTATIONS,
210                 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
211         return outputStream.toString(StandardCharsets.UTF_8.name());
212     }
213
214     private static String toJson(final NormalizedNodeContext readData) throws IOException {
215         final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
216         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
217         writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
218                 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
219         return outputStream.toString(StandardCharsets.UTF_8.name());
220     }
221
222     private static boolean isDataMissing(final Exception exception) {
223         boolean dataMissing = false;
224         if (exception instanceof RestconfDocumentedException) {
225             final RestconfDocumentedException rde = (RestconfDocumentedException)exception;
226             if (!rde.getErrors().isEmpty()) {
227                 if (rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
228                     dataMissing = true;
229                 }
230             }
231         }
232
233         return dataMissing;
234     }
235
236     private static void propagateExceptionAs(final String uriPath, final Exception exception, final String operation)
237             throws OperationFailedException {
238         LOG.debug("Error for uriPath: {}", uriPath, exception);
239
240         if (exception instanceof RestconfDocumentedException) {
241             throw new OperationFailedException(String.format(
242                     "%s failed for URI %s", operation, uriPath), exception.getCause(),
243                     toRpcErrors(((RestconfDocumentedException)exception).getErrors()));
244         }
245
246         throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
247     }
248
249     private static RpcError[] toRpcErrors(final List<RestconfError> from) {
250         final RpcError[] to = new RpcError[from.size()];
251         int index = 0;
252         for (final RestconfError e: from) {
253             to[index++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
254                     e.getErrorMessage());
255         }
256
257         return to;
258     }
259
260     private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
261         switch (errorType) {
262             case TRANSPORT: {
263                 return ErrorType.TRANSPORT;
264             }
265             case RPC: {
266                 return ErrorType.RPC;
267             }
268             case PROTOCOL: {
269                 return ErrorType.PROTOCOL;
270             }
271             default: {
272                 return ErrorType.APPLICATION;
273             }
274         }
275     }
276 }