Refactor pretty printing
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / api / InvokeParams.java
1 /*
2  * Copyright (c) 2021 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.server.api;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.restconf.server.api.EventStreamGetParams.mandatoryParam;
12
13 import java.util.Map;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.restconf.api.query.PrettyPrintParam;
16
17 /**
18  * Supported query parameters of {@code POST} HTTP operation when the request is to invoke a YANG operation, be it
19  * {@code rpc} or {@code action}. There is no such thing in RFC8040, but we support pretty-printing of the resulting
20  * {@code output} container.
21  */
22 public record InvokeParams(@NonNull PrettyPrintParam prettyPrint) implements FormatParameters {
23     public static final @NonNull InvokeParams EMPTY = new InvokeParams(PrettyPrintParam.FALSE);
24
25     public InvokeParams {
26         requireNonNull(prettyPrint);
27     }
28
29     /**
30      * Return {@link InvokeParams} for specified query parameters.
31      *
32      * @param queryParameters Parameters and their values
33      * @return A {@link InvokeParams}
34      * @throws NullPointerException if {@code queryParameters} is {@code null}
35      * @throws IllegalArgumentException if the parameters are invalid
36      */
37     public static @NonNull InvokeParams ofQueryParameters(final Map<String, String> queryParameters) {
38         if (queryParameters.isEmpty()) {
39             return EMPTY;
40         }
41
42         PrettyPrintParam prettyPrint = PrettyPrintParam.FALSE;
43
44         for (var entry : queryParameters.entrySet()) {
45             final var paramName = entry.getKey();
46             final var paramValue = entry.getValue();
47
48             prettyPrint = switch (paramName) {
49                 case PrettyPrintParam.uriName -> mandatoryParam(PrettyPrintParam::forUriValue, paramName, paramValue);
50                 default -> throw new IllegalArgumentException("Invalid parameter: " + paramName);
51             };
52         }
53
54         return new InvokeParams(requireNonNull(prettyPrint));
55     }
56 }