2 * Copyright (c) 2015 Brocade Communications 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
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import static java.util.Objects.requireNonNull;
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 java.util.Optional;
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.MultivaluedHashMap;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.core.UriInfo;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.netconf.sal.rest.api.RestconfService;
29 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
30 import org.opendaylight.netconf.sal.rest.impl.JsonToPatchBodyReader;
31 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
32 import org.opendaylight.netconf.sal.rest.impl.PatchJsonBodyWriter;
33 import org.opendaylight.netconf.sal.restconf.api.JSONRestconfService;
34 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
35 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
36 import org.opendaylight.restconf.common.errors.RestconfError;
37 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
38 import org.opendaylight.restconf.common.patch.PatchContext;
39 import org.opendaylight.restconf.common.patch.PatchStatusContext;
40 import org.opendaylight.restconf.common.util.SimpleUriInfo;
41 import org.opendaylight.yangtools.yang.common.OperationFailedException;
42 import org.opendaylight.yangtools.yang.common.RpcError;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Implementation of the JSONRestconfService interface using the restconf Draft02 implementation.
50 * @author Thomas Pantelis
51 * @deprecated Replaced by {JSONRestconfServiceRfc8040Impl from restconf-nb-rfc8040
55 public class JSONRestconfServiceImpl implements JSONRestconfService {
56 private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
58 private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
60 private final ControllerContext controllerContext;
61 private final RestconfService restconfService;
64 public JSONRestconfServiceImpl(final ControllerContext controllerContext, final RestconfImpl restconfService) {
65 this.controllerContext = controllerContext;
66 this.restconfService = restconfService;
69 @SuppressWarnings("checkstyle:IllegalCatch")
71 public void put(final String uriPath, final String payload) throws OperationFailedException {
72 requireNonNull(payload, "payload can't be null");
74 LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
76 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
77 final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false,
80 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
81 LOG.debug("Parsed NormalizedNode: {}", context.getData());
84 restconfService.updateConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
85 } catch (final Exception e) {
86 propagateExceptionAs(uriPath, e, "PUT");
90 @SuppressWarnings("checkstyle:IllegalCatch")
92 public void post(final String uriPath, final String payload) throws OperationFailedException {
93 requireNonNull(payload, "payload can't be null");
95 LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
97 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
98 final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true,
101 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
102 LOG.debug("Parsed NormalizedNode: {}", context.getData());
105 restconfService.createConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
106 } catch (final Exception e) {
107 propagateExceptionAs(uriPath, e, "POST");
111 @SuppressWarnings("checkstyle:IllegalCatch")
113 public void delete(final String uriPath) throws OperationFailedException {
114 LOG.debug("delete: uriPath: {}", uriPath);
117 restconfService.deleteConfigurationData(uriPath);
118 } catch (final Exception e) {
119 propagateExceptionAs(uriPath, e, "DELETE");
123 @SuppressWarnings("checkstyle:IllegalCatch")
125 public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType)
126 throws OperationFailedException {
127 LOG.debug("get: uriPath: {}", uriPath);
130 NormalizedNodeContext readData;
131 final SimpleUriInfo uriInfo = new SimpleUriInfo(uriPath);
132 if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
133 readData = restconfService.readConfigurationData(uriPath, uriInfo);
135 readData = restconfService.readOperationalData(uriPath, uriInfo);
138 final Optional<String> result = Optional.of(toJson(readData));
140 LOG.debug("get returning: {}", result.get());
143 } catch (final Exception e) {
144 if (!isDataMissing(e)) {
145 propagateExceptionAs(uriPath, e, "GET");
148 LOG.debug("Data missing - returning absent");
149 return Optional.empty();
153 @SuppressWarnings("checkstyle:IllegalCatch")
154 @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Unrecognised NullableDecl")
156 public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
157 throws OperationFailedException {
158 requireNonNull(uriPath, "uriPath can't be null");
160 final String actualInput = input.isPresent() ? input.get() : null;
162 LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
164 String output = null;
166 NormalizedNodeContext outputContext;
167 if (actualInput != null) {
168 final InputStream entityStream = new ByteArrayInputStream(actualInput.getBytes(StandardCharsets.UTF_8));
169 final NormalizedNodeContext inputContext =
170 JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true, controllerContext);
172 LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
173 .getInstanceIdentifier());
174 LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
176 outputContext = restconfService.invokeRpc(uriPath, inputContext, null);
178 outputContext = restconfService.invokeRpc(uriPath, null, null);
181 if (outputContext.getData() != null) {
182 output = toJson(outputContext);
184 } catch (final RuntimeException | IOException e) {
185 propagateExceptionAs(uriPath, e, "RPC");
188 return Optional.ofNullable(output);
191 @SuppressWarnings("checkstyle:IllegalCatch")
193 public Optional<String> patch(final String uriPath, final String payload)
194 throws OperationFailedException {
196 String output = null;
197 requireNonNull(payload, "payload can't be null");
199 LOG.debug("patch: uriPath: {}, payload: {}", uriPath, payload);
201 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
203 JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader(controllerContext);
204 final PatchContext context = jsonToPatchBodyReader.readFrom(uriPath, entityStream);
206 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
207 LOG.debug("Parsed NormalizedNode: {}", context.getData());
210 PatchStatusContext patchStatusContext = restconfService
211 .patchConfigurationData(context, new SimpleUriInfo(uriPath));
212 output = toJson(patchStatusContext);
213 } catch (final Exception e) {
214 propagateExceptionAs(uriPath, e, "PATCH");
216 return Optional.ofNullable(output);
219 @SuppressWarnings("checkstyle:IllegalCatch")
221 public Optional<String> subscribeToStream(final String identifier, final MultivaluedMap<String, String> params)
222 throws OperationFailedException {
223 //Note: We use http://127.0.0.1 because the Uri parser requires something there though it does nothing
224 String uri = new StringBuilder("http://127.0.0.1:8081/restconf/streams/stream/").append(identifier).toString();
225 MultivaluedMap queryParams = params != null ? params : new MultivaluedHashMap<String, String>();
226 UriInfo uriInfo = new SimpleUriInfo(uri, queryParams);
228 String jsonRes = null;
230 NormalizedNodeContext res = restconfService.subscribeToStream(identifier, uriInfo);
231 jsonRes = toJson(res);
232 } catch (final Exception e) {
233 propagateExceptionAs(identifier, e, "RPC");
236 return Optional.ofNullable(jsonRes);
239 private static String toJson(final PatchStatusContext patchStatusContext) throws IOException {
240 final PatchJsonBodyWriter writer = new PatchJsonBodyWriter();
241 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
242 writer.writeTo(patchStatusContext, PatchStatusContext.class, null, EMPTY_ANNOTATIONS,
243 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
244 return outputStream.toString(StandardCharsets.UTF_8);
247 private static String toJson(final NormalizedNodeContext readData) throws IOException {
248 final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
249 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
250 writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
251 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
252 return outputStream.toString(StandardCharsets.UTF_8);
255 private static boolean isDataMissing(final Exception exception) {
256 boolean dataMissing = false;
257 if (exception instanceof RestconfDocumentedException) {
258 final RestconfDocumentedException rde = (RestconfDocumentedException)exception;
259 if (!rde.getErrors().isEmpty()) {
260 if (rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
269 private static void propagateExceptionAs(final String uriPath, final Exception exception, final String operation)
270 throws OperationFailedException {
271 LOG.debug("Error for uriPath: {}", uriPath, exception);
273 if (exception instanceof RestconfDocumentedException) {
274 throw new OperationFailedException(String.format(
275 "%s failed for URI %s", operation, uriPath), exception.getCause(),
276 toRpcErrors(((RestconfDocumentedException)exception).getErrors()));
279 throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
282 private static RpcError[] toRpcErrors(final List<RestconfError> from) {
283 final RpcError[] to = new RpcError[from.size()];
285 for (final RestconfError e: from) {
286 to[index++] = RpcResultBuilder.newError(e.getErrorType().toLegacy(), e.getErrorTag().getTagValue(),
287 e.getErrorMessage());