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 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;
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;
48 * Implementation of the JSONRestconfService interface using the restconf Draft02 implementation.
50 * @author Thomas Pantelis
51 * @deprecated Replaced by {JSONRestconfServiceRfc8040Impl from restconf-nb-rfc8040
54 public class JSONRestconfServiceImpl implements JSONRestconfService, AutoCloseable {
55 private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
57 private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
59 private final ControllerContext controllerContext;
60 private final RestconfService restconfService;
62 public JSONRestconfServiceImpl(ControllerContext controllerContext, RestconfService restconfService) {
63 this.controllerContext = controllerContext;
64 this.restconfService = restconfService;
67 @SuppressWarnings("checkstyle:IllegalCatch")
69 public void put(final String uriPath, final String payload) throws OperationFailedException {
70 Preconditions.checkNotNull(payload, "payload can't be null");
72 LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
74 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
75 final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false,
78 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
79 LOG.debug("Parsed NormalizedNode: {}", context.getData());
82 restconfService.updateConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
83 } catch (final Exception e) {
84 propagateExceptionAs(uriPath, e, "PUT");
88 @SuppressWarnings("checkstyle:IllegalCatch")
90 public void post(final String uriPath, final String payload)
91 throws OperationFailedException {
92 Preconditions.checkNotNull(payload, "payload can't be null");
94 LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
96 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
97 final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true,
100 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
101 LOG.debug("Parsed NormalizedNode: {}", context.getData());
104 restconfService.createConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
105 } catch (final Exception e) {
106 propagateExceptionAs(uriPath, e, "POST");
110 @SuppressWarnings("checkstyle:IllegalCatch")
112 public void delete(final String uriPath) throws OperationFailedException {
113 LOG.debug("delete: uriPath: {}", uriPath);
116 restconfService.deleteConfigurationData(uriPath);
117 } catch (final Exception e) {
118 propagateExceptionAs(uriPath, e, "DELETE");
122 @SuppressWarnings("checkstyle:IllegalCatch")
124 public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType)
125 throws OperationFailedException {
126 LOG.debug("get: uriPath: {}", uriPath);
129 NormalizedNodeContext readData;
130 final SimpleUriInfo uriInfo = new SimpleUriInfo(uriPath);
131 if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
132 readData = restconfService.readConfigurationData(uriPath, uriInfo);
134 readData = restconfService.readOperationalData(uriPath, uriInfo);
137 final Optional<String> result = Optional.of(toJson(readData));
139 LOG.debug("get returning: {}", result.get());
142 } catch (final Exception e) {
143 if (!isDataMissing(e)) {
144 propagateExceptionAs(uriPath, e, "GET");
147 LOG.debug("Data missing - returning absent");
148 return Optional.absent();
152 @SuppressWarnings("checkstyle:IllegalCatch")
153 @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Unrecognised NullableDecl")
155 public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
156 throws OperationFailedException {
157 Preconditions.checkNotNull(uriPath, "uriPath can't be null");
159 final String actualInput = input.isPresent() ? input.get() : null;
161 LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
163 String output = null;
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);
171 LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
172 .getInstanceIdentifier());
173 LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
175 outputContext = restconfService.invokeRpc(uriPath, inputContext, null);
177 outputContext = restconfService.invokeRpc(uriPath, "", null);
180 if (outputContext.getData() != null) {
181 output = toJson(outputContext);
183 } catch (final RuntimeException | IOException e) {
184 propagateExceptionAs(uriPath, e, "RPC");
187 return Optional.fromNullable(output);
190 @SuppressWarnings("checkstyle:IllegalCatch")
192 public Optional<String> patch(final String uriPath, final String payload)
193 throws OperationFailedException {
195 String output = null;
196 Preconditions.checkNotNull(payload, "payload can't be null");
198 LOG.debug("patch: uriPath: {}, payload: {}", uriPath, payload);
200 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
202 JsonToPatchBodyReader jsonToPatchBodyReader = new JsonToPatchBodyReader(controllerContext);
203 final PatchContext context = jsonToPatchBodyReader.readFrom(uriPath, entityStream);
205 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
206 LOG.debug("Parsed NormalizedNode: {}", context.getData());
209 PatchStatusContext patchStatusContext = restconfService
210 .patchConfigurationData(context, new SimpleUriInfo(uriPath));
211 output = toJson(patchStatusContext);
212 } catch (final Exception e) {
213 propagateExceptionAs(uriPath, e, "PATCH");
215 return Optional.fromNullable(output);
218 @SuppressWarnings("checkstyle:IllegalCatch")
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);
227 String jsonRes = null;
229 NormalizedNodeContext res = restconfService.subscribeToStream(identifier, uriInfo);
230 jsonRes = toJson(res);
231 } catch (final Exception e) {
232 propagateExceptionAs(identifier, e, "RPC");
235 return Optional.fromNullable(jsonRes);
239 public void close() {
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());
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());
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) {
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);
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()));
282 throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
285 private static RpcError[] toRpcErrors(final List<RestconfError> from) {
286 final RpcError[] to = new RpcError[from.size()];
288 for (final RestconfError e: from) {
289 to[index++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
290 e.getErrorMessage());
296 private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
299 return ErrorType.TRANSPORT;
302 return ErrorType.RPC;
305 return ErrorType.PROTOCOL;
308 return ErrorType.APPLICATION;