Removing blueprints-processor
[ccsdk/features.git] / sdnr / wt / common / src / main / java / org / onap / ccsdk / features / sdnr / wt / common / ResourcesFromDeviceManager.java
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.common;
19
20 import java.io.BufferedReader;
21 import java.io.File;
22 import java.io.FileFilter;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.OutputStream;
28 import java.net.MalformedURLException;
29 import java.net.URISyntaxException;
30 import java.net.URL;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.List;
36
37 import org.json.JSONException;
38 import org.json.JSONObject;
39 import org.osgi.framework.Bundle;
40 import org.osgi.framework.FrameworkUtil;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class ResourcesFromDeviceManager {
45
46     private static final Logger LOG = LoggerFactory.getLogger(ResourcesFromDeviceManager.class);
47
48     private static final String RESSOURCEROOT = "src/main/resources";
49
50     private static URL getFileURL(String resFile) {
51         Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
52         URL u = null;
53         LOG.debug("try to get file {}", resFile);
54         if (b == null) {
55             LOG.info("Load resource as file: {}", resFile);
56             u = getUrlForRessource(resFile);
57         } else {
58             LOG.info("Load resource from bundle: {}", resFile);
59             u = b.getEntry(resFile);
60         }
61         return u;
62     }
63
64     private static File getFile(String resFile) {
65         Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
66         File f = null;
67         LOG.debug("try to get file {}", resFile);
68         if (b == null) {
69             LOG.warn("cannot load bundle resources");
70             f = new File(RESSOURCEROOT + resFile);
71         } else {
72             try {
73                 f = new File(b.getEntry(resFile).toURI());
74             } catch (URISyntaxException e) {
75                 LOG.warn("Con not load file: {}",e.getMessage());
76             }
77         }
78         return f;
79     }
80
81     private static String readFile(final URL u) throws IOException {
82         return readFile(u.openStream());
83     }
84
85     private static String readFile(final InputStream s) throws IOException {
86         // read file
87         BufferedReader in = new BufferedReader(new InputStreamReader(s));
88         StringBuilder sb = new StringBuilder();
89         String inputLine;
90         while ((inputLine = in.readLine()) != null) {
91             sb.append(inputLine);
92         }
93         in.close();
94         s.close();
95         return sb.toString();
96     }
97
98     public static List<URL> getFileURLs(String folder, final String filter, final boolean recursive)
99             throws IOException {
100         Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
101         List<URL> list = new ArrayList<>();
102         if (b == null) {
103             FileFilter ff = pathname -> {
104                 if (pathname.isFile()) {
105                     return pathname.getName().contains(filter);
106                 } else {
107                     return true;
108                 }
109             };
110             File ffolder = getFile(folder);
111             if (ffolder != null && ffolder.isDirectory()) {
112                 File[] files = ffolder.listFiles(ff);
113                 if (files != null && files.length > 0) {
114                     for (File f : files) {
115                         if (f.isFile()) {
116                             list.add(f.toURI().toURL());
117                         } else if (f.isDirectory() && recursive) {
118                             getFileURLsRecursive(f, ff, list);
119                         }
120                     }
121                 }
122             }
123         } else {
124             getResourceURLsTreeRecurse(b, filter, b.getEntryPaths(folder), recursive, list);
125         }
126         return list;
127     }
128
129     private static void getFileURLsRecursive(File root, FileFilter ff, List<URL> list) throws MalformedURLException {
130         if (root != null && root.isDirectory()) {
131             File[] files = root.listFiles(ff);
132             if (files != null && files.length > 0) {
133                 for (File f : files) {
134                     if (f.isFile()) {
135                         list.add(f.toURI().toURL());
136                     } else if (f.isDirectory()) {
137                         getFileURLsRecursive(f, ff, list);
138                     }
139                 }
140             }
141         }
142
143     }
144
145     private static void getResourceURLsTreeRecurse(Bundle b, String filter, Enumeration<String> resource,
146             boolean recursive, List<URL> outp) throws IOException {
147         while (resource.hasMoreElements()) {
148             String name = resource.nextElement();
149             Enumeration<String> list = b.getEntryPaths(name);
150             if (list != null) {
151                 if (recursive) {
152                     getResourceURLsTreeRecurse(b, filter, list, recursive, outp);
153                 }
154             } else {
155                 // Read
156                 if (name.contains(filter)) {
157                     LOG.debug("add {} to list", name);
158                     outp.add(b.getEntry(name));
159                 } else {
160                     LOG.debug("filtered out {}", name);
161                 }
162             }
163         }
164     }
165
166     public static List<JSONObject> getJSONFiles(String folder, boolean recursive) {
167         List<JSONObject> list = new ArrayList<>();
168         List<URL> urls;
169         try {
170             urls = getFileURLs(folder, ".json", recursive);
171             LOG.debug("found {} files", urls.size());
172         } catch (IOException e1) {
173             urls = new ArrayList<>();
174             LOG.warn("failed to get urls from resfolder {} : {}", folder, e1.getMessage());
175         }
176         for (URL u : urls) {
177             LOG.debug("try to parse " + u.toString());
178             try {
179                 JSONObject o = new JSONObject(readFile(u));
180                 list.add(o);
181             } catch (JSONException | IOException e) {
182                 LOG.warn("problem reading/parsing file {} : {}", u, e.getMessage());
183             }
184         }
185         return list;
186     }
187
188     public static JSONObject getJSONFile(String resFile) {
189         LOG.debug("loading json file {} from res", resFile);
190         URL u = getFileURL(resFile);
191         if (u == null) {
192             LOG.warn("cannot find resfile: {}", resFile);
193             return null;
194         }
195         JSONObject o = null;
196         try {
197             // parse to jsonobject
198             o = new JSONObject(readFile(u));
199         } catch (Exception e) {
200             LOG.warn("problem reading/parsing file: {}", e.getMessage());
201         }
202         return o;
203     }
204
205     /**
206      * Used for reading plugins from resource files /elasticsearch/plugins/head
207      * /etc/elasticsearch-plugins /elasticsearch/plugins
208      *
209      * @param resFolder resource folder pointing to the related files
210      * @param dstFolder destination
211      * @param rootDirToRemove part from full path to remove
212      * @return true if files could be extracted
213      */
214     public static boolean copyFolderInto(String resFolder, String dstFolder, String rootDirToRemove) {
215
216         Enumeration<URL> urls = null;
217         Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
218         if (b == null) {
219             LOG.info("Running in file text.");
220             urls = getResourceFolderFiles(resFolder);
221         } else {
222             urls = b.findEntries(resFolder, "*", true);
223         }
224
225         boolean success = true;
226         URL srcUrl;
227         String srcFilename;
228         String dstFilename;
229         while (urls.hasMoreElements()) {
230             srcUrl = urls.nextElement();
231             srcFilename = srcUrl.getFile();
232
233             if (srcFilename.endsWith("/")) {
234                 LOG.debug("Skip directory: {}", srcFilename);
235                 continue;
236             }
237
238             LOG.debug("try to copy res {} to {}", srcFilename, dstFolder);
239             if (rootDirToRemove != null) {
240                 srcFilename =
241                         srcFilename.substring(srcFilename.indexOf(rootDirToRemove) + rootDirToRemove.length() + 1);
242                 LOG.debug("dstfilename trimmed to {}", srcFilename);
243             }
244             dstFilename = dstFolder + "/" + srcFilename;
245             try {
246                 if (!extractFileTo(srcUrl, new File(dstFilename))) {
247                     success = false;
248                 }
249             } catch (Exception e) {
250                 LOG.warn("problem copying res {} to {}: {}", srcFilename, dstFilename, e.getMessage());
251             }
252         }
253
254         return success;
255
256     }
257
258     private static Enumeration<URL> getResourceFolderFiles(String folder) {
259         LOG.debug("Get resource: {}", folder);
260         URL url = getUrlForRessource(folder);
261         String path = url.getPath();
262         File[] files = new File(path).listFiles();
263         Collection<URL> urlCollection = new ArrayList<>();
264
265         if (files != null) {
266             for (File f : files) {
267                 try {
268                     if (f.isDirectory()) {
269                         urlCollection.addAll(Collections.list(getResourceFolderFiles(folder + "/" + f.getName())));
270                     } else {
271                         urlCollection.add(f.toURI().toURL());
272                     }
273                 } catch (MalformedURLException e) {
274                     LOG.error("Can not read ressources", e);
275                     break;
276                 }
277             }
278         }
279
280         Enumeration<URL> urls = Collections.enumeration(urlCollection);
281         return urls;
282     }
283
284     private static URL getUrlForRessource(String fileOrDirectory) {
285         //ClassLoader loader = Thread.currentThread().getContextClassLoader();
286         ClassLoader loader = ResourcesFromDeviceManager.class.getClassLoader();
287         URL url = loader.getResource(fileOrDirectory);
288         if(url==null && fileOrDirectory.startsWith("/")) {
289                 url = loader.getResource(fileOrDirectory.substring(1));
290         }
291         return url;
292     }
293
294     public static boolean extractFileTo(String resFile, File oFile) {
295         if (oFile == null) {
296             return false;
297         }
298         LOG.debug("try to copy {} from res to {}", resFile, oFile.getAbsolutePath());
299         URL u = getFileURL(resFile);
300         if (u == null) {
301             LOG.warn("cannot find resfile: {}", resFile);
302             return false;
303         }
304         return extractFileTo(u, oFile);
305     }
306
307     public static boolean extractFileTo(URL u, File oFile) {
308
309         if (oFile.isDirectory()) {
310             oFile.mkdirs();
311             return true;
312         } else {
313             oFile.getParentFile().mkdirs();
314         }
315
316         if (!oFile.exists()) {
317             try {
318                 oFile.createNewFile();
319             } catch (IOException e) {
320                 LOG.warn("problem creating file {}: {}", oFile.getAbsoluteFile(), e.getMessage());
321             }
322         }
323         try (InputStream in = u.openStream(); OutputStream outStream = new FileOutputStream(oFile);) {
324
325             int theInt;
326             while ((theInt = in.read()) >= 0) {
327                 outStream.write(theInt);
328             }
329             in.close();
330             outStream.flush();
331             outStream.close();
332             LOG.debug("file written successfully");
333         } catch (IOException e) {
334             LOG.error("problem writing file: {}", e.getMessage());
335             return false;
336         }
337         return true;
338     }
339
340 }