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