d22c3707aa60d6f27ec99b47c5bb5dd687a8f303
[ccsdk/sli.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6  *
7  * Modifications Copyright © 2018 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.ccsdk.sli.plugins.restconfapicall;
24
25 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.getParameters;
26 import static org.onap.ccsdk.sli.plugins.restapicall.RestapiCallNode.parseParam;
27 import static org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode.DEFAULT_MODE;
28 import static org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource.forFile;
29 import static org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors.defaultReactor;
30 import static org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource.create;
31 import java.io.File;
32 import java.io.IOException;
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.LinkedList;
40 import java.util.List;
41 import java.util.Map;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43 import org.onap.ccsdk.sli.plugins.restapicall.HttpMethod;
44 import org.onap.ccsdk.sli.plugins.yangserializers.dfserializer.YangParameters;
45 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
46 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
49 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
50
51 /**
52  * Utilities for restconf api call node.
53  */
54 public final class RestconfApiUtils {
55
56     static final String RES_CODE = "response-code";
57
58     static final String HTTP_REQ ="httpRequest";
59
60     static final String RES_PRE = "responsePrefix";
61
62     static final String RES_MSG = "response-message";
63
64     static final String HEADER = "header.";
65
66     static final String COMMA = ",";
67
68     static final String COLON = ":";
69
70     static final String HTTP_RES = "httpResponse";
71
72     static final String REST_API_URL = "restapiUrl";
73
74     static final String UPDATED_URL = "URL was set to";
75
76     static final String COMM_FAIL = "Failed to communicate with host %s." +
77             "Request will be re-attempted using the host %s.";
78
79     static final String RETRY_COUNT = "This is retry attempt %d out of %d";
80
81     static final String RETRY_FAIL = "Retry attempt has failed. No further " +
82             "retry shall be attempted, calling setFailureResponseStatus";
83
84     static final String NO_MORE_RETRY = "Could not attempt retry";
85
86     static final String MAX_RETRY_ERR = "Maximum retries reached, calling " +
87             "setFailureResponseStatus";
88
89     static final String ATTEMPTS_MSG = "%d attempts were made out of %d " +
90             "maximum retries";
91
92     static final String REQ_ERR = "Error sending the request: ";
93
94     private static final String SLASH = "/";
95
96     private static final String DIR_PATH = "dirPath";
97
98     private static final String URL_SYNTAX = "The following URL cannot be " +
99             "parsed into URI : ";
100
101     private static final String YANG = ".yang";
102
103     private static final String YANG_FILE_ERR = "Unable to parse the YANG " +
104             "file provided";
105
106     //No instantiation.
107     private RestconfApiUtils() {
108     }
109
110     /**
111      * Returns the YANG parameters after parsing it from the map.
112      *
113      * @param paramMap parameters map
114      * @return YANG parameters
115      * @throws SvcLogicException when parsing of parameters map fail
116      */
117     static YangParameters getYangParameters(Map<String, String> paramMap)
118             throws SvcLogicException {
119         YangParameters param = (YangParameters) getParameters(
120                 paramMap, new YangParameters());
121         param.dirPath = parseParam(paramMap, DIR_PATH, false, null);
122         return param;
123     }
124
125     /**
126      * Parses the restconf URL and gives the YANG path from it, which can be
127      * used to get schema node. If it is a PUT operation, then a node must be
128      * reduced from the url to make it always point to the parent.
129      *
130      * @param url    restconf URL
131      * @param method HTTP operation
132      * @return YANG path pointing to parent
133      * @throws SvcLogicException when parsing the URL fails
134      */
135     public static String parseUrl(String url, HttpMethod method)
136             throws SvcLogicException {
137         URI uri;
138         try {
139             uri = new URI(url);
140         } catch (URISyntaxException e) {
141             throw new SvcLogicException(URL_SYNTAX + url, e);
142         }
143
144         String path = uri.getPath();
145         path = getParsedPath(path);
146         return path;
147     }
148
149     /**
150      * Returns the path which contains only the schema nodes.
151      *
152      * @param path path
153      * @return path representing schema
154      */
155     private static String getParsedPath(String path) {
156         String firstHalf;
157         String secondHalf;
158         if (path.contains(COLON)) {
159             String[] p = path.split(COLON);
160             if (p[0].contains(SLASH)) {
161                 int slash = p[0].lastIndexOf(SLASH);
162                 firstHalf = p[0].substring(slash + 1);
163             } else {
164                 firstHalf = p[0];
165             }
166             secondHalf = path.substring(p[0].length() + 1);
167             return firstHalf + COLON + secondHalf;
168         } else if (path.contains(SLASH)) {
169             String[] p = path.split(SLASH);
170             if (p.length > 4) {
171                 String actual = p[3] + COLON + p[4];
172                 if (p.length > 5) {
173                     secondHalf = path.substring(
174                            p[1].length() + p[2].length() + actual.length() + 3);
175                     path = actual + secondHalf;
176                 } else {
177                     path = actual;
178                 }
179             }
180         }
181         return path;
182     }
183
184     /**
185      * Returns the schema context of the YANG files present in a directory.
186      *
187      * @param di directory path
188      * @return YANG schema context
189      * @throws SvcLogicException when YANG file reading fails
190      */
191     static EffectiveModelContext getSchemaCtxFromDir(String di)
192             throws SvcLogicException {
193         Path d = Paths.get(di);
194         File dir = d.toFile();
195         List<File> yangFiles = new LinkedList<>();
196         getYangFiles(dir, yangFiles);
197         final Collection<YangStatementStreamSource> sources =
198                 new ArrayList<>(yangFiles.size());
199         for (File file : yangFiles) {
200             try {
201                 sources.add(create(forFile(file)));
202             } catch (IOException | YangSyntaxErrorException e) {
203                 throw new SvcLogicException(YANG_FILE_ERR + e.getMessage(), e);
204             }
205         }
206
207         final CrossSourceStatementReactor.BuildAction reactor = defaultReactor()
208                 .newBuild(DEFAULT_MODE).addSources(sources);
209         try {
210             return reactor.buildEffective();
211         } catch (ReactorException e) {
212             throw new SvcLogicException(YANG_FILE_ERR + e.getMessage(), e);
213         }
214     }
215
216     /**
217      * Returns all the YANG files present in a directory recursively.
218      *
219      * @param dir       path of the directory
220      * @param yangFiles list of YANG files
221      */
222     private static void getYangFiles(File dir, List<File> yangFiles) {
223         if (dir.exists()) {
224             File[] files = dir.listFiles();
225             if (files != null) {
226                 processFiles(files, yangFiles);
227             }
228         }
229     }
230
231     /**
232      * Processes all the obtained files by isolating all the YANG files from
233      * all the directory of the given path recursively.
234      *
235      * @param files     files in the given path
236      * @param yangFiles YANG files list
237      */
238     private static void processFiles(File[] files, List<File> yangFiles) {
239         for (File file : files) {
240             if (file.isFile() && file.getName().endsWith(YANG)) {
241                 yangFiles.add(file);
242             } else if (file.isDirectory()) {
243                 getYangFiles(file, yangFiles);
244             }
245         }
246     }
247
248     /**
249      * Returns the updated XML request message by adding root node to it.
250      *
251      * @param req      XML request
252      * @param nodeName root node name
253      * @param modNs    module namespace of the root node
254      * @return updated XML request message
255      */
256     static String getUpdatedXmlReq(String req, String nodeName, String modNs) {
257         String rootNode = "\n<" + nodeName + " xmlns=\"" + modNs +
258                 "\">\n";
259         req = req.replaceFirst("\n", rootNode);
260         req = req + "</" + nodeName + ">";
261         return req.replaceAll(">\\s+<", "><");
262     }
263 }