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 java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.lang.annotation.Annotation;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Collections;
20 import java.util.List;
21 import javax.ws.rs.core.MediaType;
22 import javax.ws.rs.core.MultivaluedHashMap;
23 import javax.ws.rs.core.MultivaluedMap;
24 import javax.ws.rs.core.PathSegment;
25 import javax.ws.rs.core.UriBuilder;
26 import javax.ws.rs.core.UriInfo;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.netconf.sal.rest.impl.JsonNormalizedNodeBodyReader;
29 import org.opendaylight.netconf.sal.rest.impl.NormalizedNodeJsonBodyWriter;
30 import org.opendaylight.netconf.sal.restconf.api.JSONRestconfService;
31 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.common.errors.RestconfError;
34 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
35 import org.opendaylight.yangtools.yang.common.OperationFailedException;
36 import org.opendaylight.yangtools.yang.common.RpcError;
37 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
38 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * Implementation of the JSONRestconfService interface using the restconf Draft02 implementation.
45 * @author Thomas Pantelis
46 * @deprecated Replaced by {@link JSONRestconfServiceDraft18}
49 public class JSONRestconfServiceImpl implements JSONRestconfService, AutoCloseable {
50 private static final Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
52 private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
54 @SuppressWarnings("checkstyle:IllegalCatch")
56 public void put(final String uriPath, final String payload) throws OperationFailedException {
57 Preconditions.checkNotNull(payload, "payload can't be null");
59 LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
61 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
62 final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false);
64 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
65 LOG.debug("Parsed NormalizedNode: {}", context.getData());
68 RestconfImpl.getInstance().updateConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
69 } catch (final Exception e) {
70 propagateExceptionAs(uriPath, e, "PUT");
74 @SuppressWarnings("checkstyle:IllegalCatch")
76 public void post(final String uriPath, final String payload)
77 throws OperationFailedException {
78 Preconditions.checkNotNull(payload, "payload can't be null");
80 LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
82 final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
83 final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
85 LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
86 LOG.debug("Parsed NormalizedNode: {}", context.getData());
89 RestconfImpl.getInstance().createConfigurationData(uriPath, context, new SimpleUriInfo(uriPath));
90 } catch (final Exception e) {
91 propagateExceptionAs(uriPath, e, "POST");
95 @SuppressWarnings("checkstyle:IllegalCatch")
97 public void delete(final String uriPath) throws OperationFailedException {
98 LOG.debug("delete: uriPath: {}", uriPath);
101 RestconfImpl.getInstance().deleteConfigurationData(uriPath);
102 } catch (final Exception e) {
103 propagateExceptionAs(uriPath, e, "DELETE");
107 @SuppressWarnings("checkstyle:IllegalCatch")
109 public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType)
110 throws OperationFailedException {
111 LOG.debug("get: uriPath: {}", uriPath);
114 NormalizedNodeContext readData;
115 final SimpleUriInfo uriInfo = new SimpleUriInfo(uriPath);
116 if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
117 readData = RestconfImpl.getInstance().readConfigurationData(uriPath, uriInfo);
119 readData = RestconfImpl.getInstance().readOperationalData(uriPath, uriInfo);
122 final Optional<String> result = Optional.of(toJson(readData));
124 LOG.debug("get returning: {}", result.get());
127 } catch (final Exception e) {
128 if (!isDataMissing(e)) {
129 propagateExceptionAs(uriPath, e, "GET");
132 LOG.debug("Data missing - returning absent");
133 return Optional.absent();
137 @SuppressWarnings("checkstyle:IllegalCatch")
139 public Optional<String> invokeRpc(final String uriPath, final Optional<String> input)
140 throws OperationFailedException {
141 Preconditions.checkNotNull(uriPath, "uriPath can't be null");
143 final String actualInput = input.isPresent() ? input.get() : null;
145 LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
147 String output = null;
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);
155 LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
156 .getInstanceIdentifier());
157 LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
159 outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, inputContext, null);
161 outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, "", null);
164 if (outputContext.getData() != null) {
165 output = toJson(outputContext);
167 } catch (final Exception e) {
168 propagateExceptionAs(uriPath, e, "RPC");
171 return Optional.fromNullable(output);
175 public void close() {
178 private static String toJson(final NormalizedNodeContext readData) throws IOException {
179 final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
180 final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
181 writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
182 MediaType.APPLICATION_JSON_TYPE, null, outputStream);
183 return outputStream.toString(StandardCharsets.UTF_8.name());
186 private static boolean isDataMissing(final Exception exception) {
187 boolean dataMissing = false;
188 if (exception instanceof RestconfDocumentedException) {
189 final RestconfDocumentedException rde = (RestconfDocumentedException)exception;
190 if (!rde.getErrors().isEmpty()) {
191 if (rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
200 private static void propagateExceptionAs(final String uriPath, final Exception exception, final String operation)
201 throws OperationFailedException {
202 LOG.debug("Error for uriPath: {}", uriPath, exception);
204 if (exception instanceof RestconfDocumentedException) {
205 throw new OperationFailedException(String.format(
206 "%s failed for URI %s", operation, uriPath), exception.getCause(),
207 toRpcErrors(((RestconfDocumentedException)exception).getErrors()));
210 throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), exception);
213 private static RpcError[] toRpcErrors(final List<RestconfError> from) {
214 final RpcError[] to = new RpcError[from.size()];
216 for (final RestconfError e: from) {
217 to[index++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
218 e.getErrorMessage());
224 private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
227 return ErrorType.TRANSPORT;
230 return ErrorType.RPC;
233 return ErrorType.PROTOCOL;
236 return ErrorType.APPLICATION;
241 private static class SimpleUriInfo implements UriInfo {
242 private final String path;
243 private final MultivaluedMap<String, String> queryParams;
245 SimpleUriInfo(String path) {
246 this(path, new MultivaluedHashMap<>());
249 SimpleUriInfo(String path, MultivaluedMap<String, String> queryParams) {
251 this.queryParams = queryParams;
255 public String getPath() {
260 public String getPath(boolean decode) {
265 public List<PathSegment> getPathSegments() {
266 throw new UnsupportedOperationException();
270 public List<PathSegment> getPathSegments(boolean decode) {
271 throw new UnsupportedOperationException();
275 public URI getRequestUri() {
276 return URI.create(path);
280 public UriBuilder getRequestUriBuilder() {
281 return UriBuilder.fromUri(getRequestUri());
285 public URI getAbsolutePath() {
286 return getRequestUri();
290 public UriBuilder getAbsolutePathBuilder() {
291 return UriBuilder.fromUri(getAbsolutePath());
295 public URI getBaseUri() {
296 return URI.create("");
300 public UriBuilder getBaseUriBuilder() {
301 return UriBuilder.fromUri(getBaseUri());
305 public MultivaluedMap<String, String> getPathParameters() {
306 return new MultivaluedHashMap<>();
310 public MultivaluedMap<String, String> getPathParameters(boolean decode) {
311 return getPathParameters();
315 public MultivaluedMap<String, String> getQueryParameters() {
320 public MultivaluedMap<String, String> getQueryParameters(boolean decode) {
321 return getQueryParameters();
325 public List<String> getMatchedURIs() {
326 return Collections.emptyList();
330 public List<String> getMatchedURIs(boolean decode) {
331 return getMatchedURIs();
335 public List<Object> getMatchedResources() {
336 return Collections.emptyList();
340 public URI resolve(URI uri) {
345 public URI relativize(URI uri) {