57457519f6717818d05fc286d22c86e896f18298
[netconf.git] / restconf / sal-rest-connector / 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 java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.lang.annotation.Annotation;
17 import java.nio.charset.StandardCharsets;
18 import java.util.List;
19 import javax.ws.rs.core.MediaType;
20 import javax.ws.rs.core.UriInfo;
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.NormalizedNodeJsonBodyWriter;
24 import org.opendaylight.netconf.sal.restconf.api.JSONRestconfService;
25 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
26 import org.opendaylight.yangtools.yang.common.OperationFailedException;
27 import org.opendaylight.yangtools.yang.common.RpcError;
28 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
29 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * Implementation of the JSONRestconfService interface.
35  *
36  * @author Thomas Pantelis
37  */
38 @Deprecated
39 public class JSONRestconfServiceImpl implements JSONRestconfService, AutoCloseable {
40     private final static Logger LOG = LoggerFactory.getLogger(JSONRestconfServiceImpl.class);
41
42     private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
43
44     @Override
45     public void put(final String uriPath, final String payload, final UriInfo uriInfo) throws OperationFailedException {
46         Preconditions.checkNotNull(payload, "payload can't be null");
47
48         LOG.debug("put: uriPath: {}, payload: {}", uriPath, payload);
49
50         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
51         final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, false);
52
53         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
54         LOG.debug("Parsed NormalizedNode: {}", context.getData());
55
56         try {
57             RestconfImpl.getInstance().updateConfigurationData(uriPath, context, uriInfo);
58         } catch (final Exception e) {
59             propagateExceptionAs(uriPath, e, "PUT");
60         }
61     }
62
63     @Override
64     public void post(final String uriPath, final String payload, final UriInfo uriInfo)
65             throws OperationFailedException {
66         Preconditions.checkNotNull(payload, "payload can't be null");
67
68         LOG.debug("post: uriPath: {}, payload: {}", uriPath, payload);
69
70         final InputStream entityStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
71         final NormalizedNodeContext context = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
72
73         LOG.debug("Parsed YangInstanceIdentifier: {}", context.getInstanceIdentifierContext().getInstanceIdentifier());
74         LOG.debug("Parsed NormalizedNode: {}", context.getData());
75
76         try {
77             RestconfImpl.getInstance().createConfigurationData(uriPath, context, uriInfo);
78         } catch (final Exception e) {
79             propagateExceptionAs(uriPath, e, "POST");
80         }
81     }
82
83     @Override
84     public void delete(final String uriPath) throws OperationFailedException {
85         LOG.debug("delete: uriPath: {}", uriPath);
86
87         try {
88             RestconfImpl.getInstance().deleteConfigurationData(uriPath);
89         } catch (final Exception e) {
90             propagateExceptionAs(uriPath, e, "DELETE");
91         }
92     }
93
94     @Override
95     public Optional<String> get(final String uriPath, final LogicalDatastoreType datastoreType) throws OperationFailedException {
96         LOG.debug("get: uriPath: {}", uriPath);
97
98         try {
99             NormalizedNodeContext readData;
100             if(datastoreType == LogicalDatastoreType.CONFIGURATION) {
101                 readData = RestconfImpl.getInstance().readConfigurationData(uriPath, null);
102             } else {
103                 readData = RestconfImpl.getInstance().readOperationalData(uriPath, null);
104             }
105
106             final Optional<String> result = Optional.of(toJson(readData));
107
108             LOG.debug("get returning: {}", result.get());
109
110             return result;
111         } catch (final Exception e) {
112             if(!isDataMissing(e)) {
113                 propagateExceptionAs(uriPath, e, "GET");
114             }
115
116             LOG.debug("Data missing - returning absent");
117             return Optional.absent();
118         }
119     }
120
121     @Override
122     public Optional<String> invokeRpc(final String uriPath, final Optional<String> input) throws OperationFailedException {
123         Preconditions.checkNotNull(uriPath, "uriPath can't be null");
124
125         final String actualInput = input.isPresent() ? input.get() : null;
126
127         LOG.debug("invokeRpc: uriPath: {}, input: {}", uriPath, actualInput);
128
129         String output = null;
130         try {
131             NormalizedNodeContext outputContext;
132             if(actualInput != null) {
133                 final InputStream entityStream = new ByteArrayInputStream(actualInput.getBytes(StandardCharsets.UTF_8));
134                 final NormalizedNodeContext inputContext = JsonNormalizedNodeBodyReader.readFrom(uriPath, entityStream, true);
135
136                 LOG.debug("Parsed YangInstanceIdentifier: {}", inputContext.getInstanceIdentifierContext()
137                         .getInstanceIdentifier());
138                 LOG.debug("Parsed NormalizedNode: {}", inputContext.getData());
139
140                 outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, inputContext, null);
141             } else {
142                 outputContext = RestconfImpl.getInstance().invokeRpc(uriPath, "", null);
143             }
144
145             if(outputContext.getData() != null) {
146                 output = toJson(outputContext);
147             }
148         } catch (final Exception e) {
149             propagateExceptionAs(uriPath, e, "RPC");
150         }
151
152         return Optional.fromNullable(output);
153     }
154
155     @Override
156     public void close() {
157     }
158
159     private String toJson(final NormalizedNodeContext readData) throws IOException {
160         final NormalizedNodeJsonBodyWriter writer = new NormalizedNodeJsonBodyWriter();
161         final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
162         writer.writeTo(readData, NormalizedNodeContext.class, null, EMPTY_ANNOTATIONS,
163                 MediaType.APPLICATION_JSON_TYPE, null, outputStream );
164         return outputStream.toString(StandardCharsets.UTF_8.name());
165     }
166
167     private boolean isDataMissing(final Exception e) {
168         boolean dataMissing = false;
169         if(e instanceof RestconfDocumentedException) {
170             final RestconfDocumentedException rde = (RestconfDocumentedException)e;
171             if(!rde.getErrors().isEmpty()) {
172                 if(rde.getErrors().get(0).getErrorTag() == ErrorTag.DATA_MISSING) {
173                     dataMissing = true;
174                 }
175             }
176         }
177
178         return dataMissing;
179     }
180
181     private static void propagateExceptionAs(final String uriPath, final Exception e, final String operation) throws OperationFailedException {
182         LOG.debug("Error for uriPath: {}", uriPath, e);
183
184         if(e instanceof RestconfDocumentedException) {
185             throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), e.getCause(),
186                     toRpcErrors(((RestconfDocumentedException)e).getErrors()));
187         }
188
189         throw new OperationFailedException(String.format("%s failed for URI %s", operation, uriPath), e);
190     }
191
192     private static RpcError[] toRpcErrors(final List<RestconfError> from) {
193         final RpcError[] to = new RpcError[from.size()];
194         int i = 0;
195         for(final RestconfError e: from) {
196             to[i++] = RpcResultBuilder.newError(toRpcErrorType(e.getErrorType()), e.getErrorTag().getTagValue(),
197                     e.getErrorMessage());
198         }
199
200         return to;
201     }
202
203     private static ErrorType toRpcErrorType(final RestconfError.ErrorType errorType) {
204         switch(errorType) {
205             case TRANSPORT: {
206                 return ErrorType.TRANSPORT;
207             }
208             case RPC: {
209                 return ErrorType.RPC;
210             }
211             case PROTOCOL: {
212                 return ErrorType.PROTOCOL;
213             }
214             default: {
215                 return ErrorType.APPLICATION;
216             }
217         }
218     }
219 }