115ff4f4057387b983195b6969196f9d0921a836
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.http;
23
24 import java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.UnsupportedEncodingException;
29 import java.net.URLDecoder;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import javax.servlet.ServletException;
35 import javax.servlet.http.HttpServlet;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38 import org.json.JSONObject;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
40 import org.onap.ccsdk.features.sdnr.wt.dataprovider.impl.DataTreeProviderImpl;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.data.provider.rev201110.Entity;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * @author Michael Dürre
47  *
48  */
49 public class DataTreeHttpServlet extends HttpServlet {
50
51     private static final long serialVersionUID = 1L;
52     private final DataTreeProviderImpl dataTreeProvider;
53     private static final Logger LOG = LoggerFactory.getLogger(DataTreeHttpServlet.class);
54
55     public DataTreeHttpServlet() {
56         super();
57         this.dataTreeProvider = new DataTreeProviderImpl();
58     }
59
60     /**
61      * @param client
62      */
63     public void setDatabaseClient(HtDatabaseClient client) {
64         this.dataTreeProvider.setDatabaseClient(client);
65
66     }
67
68     public static String readPayload(HttpServletRequest request) throws IOException {
69
70         String body = null;
71         StringBuilder stringBuilder = new StringBuilder();
72         BufferedReader bufferedReader = null;
73
74         try {
75             InputStream inputStream = request.getInputStream();
76             if (inputStream != null) {
77                 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
78                 char[] charBuffer = new char[128];
79                 int bytesRead = -1;
80                 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
81                     stringBuilder.append(charBuffer, 0, bytesRead);
82                 }
83             } else {
84                 stringBuilder.append("");
85             }
86         } catch (IOException ex) {
87             throw ex;
88         } finally {
89             if (bufferedReader != null) {
90                 try {
91                     bufferedReader.close();
92                 } catch (IOException ex) {
93                     throw ex;
94                 }
95             }
96         }
97
98         body = stringBuilder.toString();
99         return body;
100     }
101
102     @Override
103     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
104         final String uri = req.getRequestURI();
105         LOG.debug("GET request for {}", uri);
106         final EntityWithTree e = getEntity(uri);
107         if (e != null) {
108             LOG.info("GET request for {} to e={} with tree={}", uri, e.entity, e.tree);
109             switch (e.entity) {
110                 case Inventoryequipment:
111                     DataTreeObject o = this.dataTreeProvider.readInventoryTree(e.tree, null);
112                     this.doJsonResponse(resp, o);
113                     break;
114                 default:
115                     this.notAvailble(resp);
116                     break;
117             }
118         } else {
119             LOG.debug("unable to find entity for uri {}", uri);
120         }
121     }
122
123     @Override
124     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
125         final String uri = req.getRequestURI();
126         String filter = null;
127         try {
128             final String body = readPayload(req);
129             JSONObject data = new JSONObject(body);
130             if (data.has("query")) {
131                 filter = data.getString("query");
132             }
133
134         } catch (Exception e) {
135             LOG.warn("problem reading payload: {}", e);
136         }
137         LOG.debug("POST request for {}", uri);
138         final EntityWithTree e = getEntity(uri);
139         if (e != null) {
140             switch (e.entity) {
141                 case Inventoryequipment:
142                     DataTreeObject o = this.dataTreeProvider.readInventoryTree(e.tree, filter);
143                     this.doJsonResponse(resp, o);
144                     break;
145                 default:
146                     this.notAvailble(resp);
147                     break;
148             }
149         }
150     }
151
152     /**
153      * @param resp
154      */
155     private void notAvailble(HttpServletResponse resp) {
156         try {
157             resp.sendError(HttpServletResponse.SC_NOT_FOUND);
158         } catch (IOException e) {
159
160         }
161     }
162
163     public static EntityWithTree getEntity(String uri) {
164         final String regex = "^\\/tree\\/read-(.*)-tree\\/?(.*)$";
165         final Pattern pattern = Pattern.compile(regex);
166         final Matcher matcher = pattern.matcher(uri);
167         Entity e = null;
168         if (matcher.find() && matcher.groupCount() > 0) {
169             try {
170                 e = Entity.forName(matcher.group(1)).get();
171                 return new EntityWithTree(e, matcher.groupCount() > 1 ? matcher.group(2) : null);
172             } catch (Exception e2) {
173                 LOG.warn("unable to parse {} into entity: {}", matcher.group(2), e2);
174             }
175         }
176         return null;
177
178     }
179
180     private void doJsonResponse(HttpServletResponse resp, DataTreeObject data) {
181         resp.setHeader("Content-Type", "application/json");
182         try {
183             resp.getWriter().write(data.toJSON());
184         } catch (IOException e) {
185             LOG.warn("problem sending response: {}", e);
186         }
187     }
188
189     public static class EntityWithTree {
190         public final Entity entity;
191         public final List<String> tree;
192
193         @Override
194         public String toString() {
195             return "EntityWithTree [entity=" + entity + ", tree=" + tree + "]";
196         }
197
198         /**
199          *
200          * @param e database enttity to access
201          * @param tree tree description
202          *   e.g. nodeA           => tree entry for node-id=nodeA
203          *        nodeA/key0      => tree entry for node-id=nodeA and uuid=key0 and tree-level=0
204          *        nodeA/key0/key1 => tree entry for node-id=nodeA and uuid=key1 and tree-level=1
205          *
206          */
207         public EntityWithTree(Entity e, String tree) {
208             this.entity = e;
209             if (tree != null) {
210                 if (tree.startsWith("/")) {
211                     tree = tree.substring(1);
212                 }
213                 if (tree.endsWith("/")) {
214                     tree = tree.substring(0, tree.length() - 1);
215                 }
216                 String[] tmp = tree.split("\\/");
217                 this.tree = new ArrayList<>();
218                 for (int i = 0; i < tmp.length; i++) {
219                     try {
220                         String s = URLDecoder.decode(tmp[i], "utf-8");
221                         if (s != null && s.length() > 0) {
222                             this.tree.add(s);
223                         }
224                     } catch (UnsupportedEncodingException e1) {
225                         LOG.warn("problem urldecode {}: {}", tmp[i], e);
226                     }
227                 }
228             } else {
229                 this.tree = null;
230             }
231         }
232     }
233 }