Remove RestconfInvokeOperationsUtil
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / services / impl / RestconfInvokeOperationsServiceImpl.java
1 /*
2  * Copyright (c) 2016 Cisco 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.restconf.nb.rfc8040.rests.services.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.Optional;
19 import java.util.concurrent.CancellationException;
20 import java.util.concurrent.ExecutionException;
21 import javax.ws.rs.Path;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.core.Response;
24 import javax.ws.rs.core.UriInfo;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
27 import org.opendaylight.mdsal.dom.api.DOMRpcException;
28 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
29 import org.opendaylight.mdsal.dom.api.DOMRpcService;
30 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
31 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
32 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
33 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
34 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
36 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfInvokeOperationsService;
37 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
38 import org.opendaylight.yangtools.yang.common.ErrorTag;
39 import org.opendaylight.yangtools.yang.common.ErrorType;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.RpcError;
42 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
43 import org.opendaylight.yangtools.yang.common.XMLNamespace;
44 import org.opendaylight.yangtools.yang.common.YangConstants;
45 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
48 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * Implementation of {@link RestconfInvokeOperationsService}.
55  *
56  */
57 @Path("/")
58 public class RestconfInvokeOperationsServiceImpl implements RestconfInvokeOperationsService {
59     private static final Logger LOG = LoggerFactory.getLogger(RestconfInvokeOperationsServiceImpl.class);
60
61     // FIXME: at some point we do not want to have this here
62     private static final XMLNamespace SAL_REMOTE_NAMESPACE =
63         XMLNamespace.of("urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote");
64
65     private final DOMRpcService rpcService;
66     private final SchemaContextHandler schemaContextHandler;
67
68     public RestconfInvokeOperationsServiceImpl(final DOMRpcService rpcService,
69             final SchemaContextHandler schemaContextHandler) {
70         this.rpcService = requireNonNull(rpcService);
71         this.schemaContextHandler = requireNonNull(schemaContextHandler);
72     }
73
74     @Override
75     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload,
76             final UriInfo uriInfo) {
77         final QName schemaPath = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
78         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
79         final XMLNamespace namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
80
81         final DOMRpcResult response;
82         final EffectiveModelContext schemaContextRef;
83         if (mountPoint == null) {
84             schemaContextRef = schemaContextHandler.get();
85             // FIXME: this really should be a normal RPC invocation service which has its own interface with JAX-RS
86             if (SAL_REMOTE_NAMESPACE.equals(namespace)) {
87                 if (identifier.contains(RestconfStreamsConstants.CREATE_DATA_SUBSCRIPTION)) {
88                     response = CreateStreamUtil.createDataChangeNotifiStream(payload, schemaContextRef);
89                 } else {
90                     throw new RestconfDocumentedException("Not supported operation", ErrorType.RPC,
91                             ErrorTag.OPERATION_NOT_SUPPORTED);
92                 }
93             } else {
94                 response = invokeRpc(payload.getData(), schemaPath, rpcService);
95             }
96         } else {
97             response = invokeRpc(payload.getData(), schemaPath, mountPoint);
98             schemaContextRef = modelContext(mountPoint);
99         }
100
101         final DOMRpcResult result = checkResponse(response);
102
103         RpcDefinition resultNodeSchema = null;
104         NormalizedNode resultData = null;
105         if (result != null && result.getResult() != null) {
106             resultData = result.getResult();
107             resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
108         }
109
110         if (resultData != null && ((ContainerNode) resultData).isEmpty()) {
111             throw new WebApplicationException(Response.Status.NO_CONTENT);
112         } else {
113             return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint,
114                     schemaContextRef), resultData);
115         }
116     }
117
118     /**
119      * Invoking rpc via mount point.
120      *
121      * @param mountPoint mount point
122      * @param data input data
123      * @param rpc RPC type
124      * @return {@link DOMRpcResult}
125      */
126     // FIXME: NETCONF-718: we should be returning a future here
127     @VisibleForTesting
128     static DOMRpcResult invokeRpc(final NormalizedNode data, final QName rpc, final DOMMountPoint mountPoint) {
129         return invokeRpc(data, rpc, mountPoint.getService(DOMRpcService.class).orElseThrow(() -> {
130             final String errmsg = "RPC service is missing.";
131             LOG.debug(errmsg);
132             return new RestconfDocumentedException(errmsg);
133         }));
134     }
135
136     /**
137      * Invoke rpc.
138      *
139      * @param data input data
140      * @param rpc RPC type
141      * @param rpcService rpc service to invoke rpc
142      * @return {@link DOMRpcResult}
143      */
144     // FIXME: NETCONF-718: we should be returning a future here
145     @VisibleForTesting
146     static DOMRpcResult invokeRpc(final NormalizedNode data, final QName rpc, final DOMRpcService rpcService) {
147         return checkedGet(Futures.catching(
148             rpcService.invokeRpc(rpc, nonnullInput(rpc, data)), DOMRpcException.class,
149             cause -> new DefaultDOMRpcResult(ImmutableList.of(RpcResultBuilder.newError(
150                 RpcError.ErrorType.RPC, "operation-failed", cause.getMessage()))),
151             MoreExecutors.directExecutor()));
152     }
153
154     private static @NonNull NormalizedNode nonnullInput(final QName type, final NormalizedNode input) {
155         return input != null ? input
156                 : ImmutableNodes.containerNode(YangConstants.operationInputQName(type.getModule()));
157     }
158
159     /**
160      * Check the validity of the result.
161      *
162      * @param response response of rpc
163      * @return {@link DOMRpcResult} result
164      */
165     @VisibleForTesting
166     static DOMRpcResult checkResponse(final DOMRpcResult response) {
167         if (response == null) {
168             return null;
169         }
170         try {
171             if (response.getErrors().isEmpty()) {
172                 return response;
173             }
174             LOG.debug("RpcError message {}", response.getErrors());
175             throw new RestconfDocumentedException("RPCerror message ", null, response.getErrors());
176         } catch (final CancellationException e) {
177             final String errMsg = "The operation was cancelled while executing.";
178             LOG.debug("Cancel RpcExecution: {}", errMsg, e);
179             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, e);
180         }
181     }
182
183     @Deprecated
184     static <T> T checkedGet(final ListenableFuture<T> future) {
185         try {
186             return future.get();
187         } catch (InterruptedException e) {
188             throw new RestconfDocumentedException("Interrupted while waiting for result of invocation", e);
189         } catch (ExecutionException e) {
190             Throwables.throwIfInstanceOf(e.getCause(), RestconfDocumentedException.class);
191             throw new RestconfDocumentedException("Invocation failed", e);
192         }
193     }
194
195     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
196         return mountPoint.getService(DOMSchemaService.class)
197             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
198             .orElse(null);
199     }
200 }