Refactor ServerRequest
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / jaxrs / JaxRsServerRequest.java
1 /*
2  * Copyright (c) 2024 PANTHEON.tech, s.r.o. 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.jaxrs;
9
10 import static java.util.Objects.requireNonNull;
11
12 import javax.ws.rs.BadRequestException;
13 import javax.ws.rs.container.AsyncResponse;
14 import javax.ws.rs.core.Response;
15 import javax.ws.rs.core.UriInfo;
16 import org.eclipse.jdt.annotation.NonNullByDefault;
17 import org.opendaylight.restconf.api.QueryParameters;
18 import org.opendaylight.restconf.api.query.PrettyPrintParam;
19 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
20 import org.opendaylight.restconf.server.api.AbstractServerRequest;
21 import org.opendaylight.restconf.server.api.ServerException;
22 import org.opendaylight.restconf.server.api.ServerRequest;
23
24 /**
25  * A {@link ServerRequest} originating in {@link JaxRsRestconf}.
26  *
27  * @param T type of reported result
28  */
29 @NonNullByDefault
30 abstract class JaxRsServerRequest<T> extends AbstractServerRequest<T> {
31     private final AsyncResponse ar;
32
33     private JaxRsServerRequest(final PrettyPrintParam defaultPrettyPrint, final AsyncResponse ar,
34             final QueryParameters queryParameters) {
35         super(queryParameters, defaultPrettyPrint);
36         this.ar = requireNonNull(ar);
37     }
38
39     JaxRsServerRequest(final PrettyPrintParam defaultPrettyPrint, final AsyncResponse ar) {
40         this(defaultPrettyPrint, ar, QueryParameters.of());
41     }
42
43     JaxRsServerRequest(final PrettyPrintParam defaultPrettyPrint, final AsyncResponse ar, final UriInfo uriInfo) {
44         this(defaultPrettyPrint, ar, queryParamsOf(uriInfo));
45     }
46
47     private static QueryParameters queryParamsOf(final UriInfo uriInfo) {
48         try {
49             return QueryParameters.ofMultiValue(uriInfo.getQueryParameters());
50         } catch (IllegalArgumentException e) {
51             throw new BadRequestException(e.getMessage(), e);
52         }
53     }
54
55     @Override
56     protected final void onSuccess(final T result) {
57         final Response response;
58         try {
59             response = transform(result);
60         } catch (ServerException e) {
61             onFailure(e.toLegacy());
62             return;
63         }
64         ar.resume(response);
65     }
66
67     @Override
68     protected void onFailure(final RestconfDocumentedException ex) {
69         ar.resume(ex);
70     }
71
72     abstract Response transform(T result) throws ServerException;
73 }