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
10 * http://www.apache.org/licenses/LICENSE-2.0
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
16 * ============LICENSE_END==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.common;
20 import java.io.BufferedReader;
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;
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;
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;
44 public class ResourcesFromDeviceManager {
46 private static final Logger LOG = LoggerFactory.getLogger(ResourcesFromDeviceManager.class);
48 private static final String RESSOURCEROOT = "src/main/resources";
50 private static URL getFileURL(String resFile) {
51 Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
53 LOG.debug("try to get file {}", resFile);
55 LOG.info("Load resource as file: {}", resFile);
56 u = getUrlForRessource(resFile);
58 LOG.info("Load resource from bundle: {}", resFile);
59 u = b.getEntry(resFile);
64 private static File getFile(String resFile) {
65 Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
67 LOG.debug("try to get file {}", resFile);
69 LOG.warn("cannot load bundle resources");
70 f = new File(RESSOURCEROOT + resFile);
73 f = new File(b.getEntry(resFile).toURI());
74 } catch (URISyntaxException e) {
75 LOG.warn("Con not load file: {}",e.getMessage());
81 private static String readFile(final URL u) throws IOException {
82 return readFile(u.openStream());
85 private static String readFile(final InputStream s) throws IOException {
87 BufferedReader in = new BufferedReader(new InputStreamReader(s));
88 StringBuilder sb = new StringBuilder();
90 while ((inputLine = in.readLine()) != null) {
98 public static List<URL> getFileURLs(String folder, final String filter, final boolean recursive)
100 Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
101 List<URL> list = new ArrayList<>();
103 FileFilter ff = pathname -> {
104 if (pathname.isFile()) {
105 return pathname.getName().contains(filter);
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) {
116 list.add(f.toURI().toURL());
117 } else if (f.isDirectory() && recursive) {
118 getFileURLsRecursive(f, ff, list);
124 getResourceURLsTreeRecurse(b, filter, b.getEntryPaths(folder), recursive, list);
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) {
135 list.add(f.toURI().toURL());
136 } else if (f.isDirectory()) {
137 getFileURLsRecursive(f, ff, list);
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);
152 getResourceURLsTreeRecurse(b, filter, list, recursive, outp);
156 if (name.contains(filter)) {
157 LOG.debug("add {} to list", name);
158 outp.add(b.getEntry(name));
160 LOG.debug("filtered out {}", name);
166 public static List<JSONObject> getJSONFiles(String folder, boolean recursive) {
167 List<JSONObject> list = new ArrayList<>();
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());
177 LOG.debug("try to parse " + u.toString());
179 JSONObject o = new JSONObject(readFile(u));
181 } catch (JSONException | IOException e) {
182 LOG.warn("problem reading/parsing file {} : {}", u, e.getMessage());
188 public static JSONObject getJSONFile(String resFile) {
189 LOG.debug("loading json file {} from res", resFile);
190 URL u = getFileURL(resFile);
192 LOG.warn("cannot find resfile: {}", resFile);
197 // parse to jsonobject
198 o = new JSONObject(readFile(u));
199 } catch (Exception e) {
200 LOG.warn("problem reading/parsing file: {}", e.getMessage());
206 * Used for reading plugins from resource files /elasticsearch/plugins/head
207 * /etc/elasticsearch-plugins /elasticsearch/plugins
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
214 public static boolean copyFolderInto(String resFolder, String dstFolder, String rootDirToRemove) {
216 Enumeration<URL> urls = null;
217 Bundle b = FrameworkUtil.getBundle(ResourcesFromDeviceManager.class);
219 LOG.info("Running in file text.");
220 urls = getResourceFolderFiles(resFolder);
222 urls = b.findEntries(resFolder, "*", true);
225 boolean success = true;
229 while (urls.hasMoreElements()) {
230 srcUrl = urls.nextElement();
231 srcFilename = srcUrl.getFile();
233 if (srcFilename.endsWith("/")) {
234 LOG.debug("Skip directory: {}", srcFilename);
238 LOG.debug("try to copy res {} to {}", srcFilename, dstFolder);
239 if (rootDirToRemove != null) {
241 srcFilename.substring(srcFilename.indexOf(rootDirToRemove) + rootDirToRemove.length() + 1);
242 LOG.debug("dstfilename trimmed to {}", srcFilename);
244 dstFilename = dstFolder + "/" + srcFilename;
246 if (!extractFileTo(srcUrl, new File(dstFilename))) {
249 } catch (Exception e) {
250 LOG.warn("problem copying res {} to {}: {}", srcFilename, dstFilename, e.getMessage());
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<>();
266 for (File f : files) {
268 if (f.isDirectory()) {
269 urlCollection.addAll(Collections.list(getResourceFolderFiles(folder + "/" + f.getName())));
271 urlCollection.add(f.toURI().toURL());
273 } catch (MalformedURLException e) {
274 LOG.error("Can not read ressources", e);
280 Enumeration<URL> urls = Collections.enumeration(urlCollection);
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));
294 public static boolean extractFileTo(String resFile, File oFile) {
298 LOG.debug("try to copy {} from res to {}", resFile, oFile.getAbsolutePath());
299 URL u = getFileURL(resFile);
301 LOG.warn("cannot find resfile: {}", resFile);
304 return extractFileTo(u, oFile);
307 public static boolean extractFileTo(URL u, File oFile) {
309 if (oFile.isDirectory()) {
313 oFile.getParentFile().mkdirs();
316 if (!oFile.exists()) {
318 oFile.createNewFile();
319 } catch (IOException e) {
320 LOG.warn("problem creating file {}: {}", oFile.getAbsoluteFile(), e.getMessage());
323 try (InputStream in = u.openStream(); OutputStream outStream = new FileOutputStream(oFile);) {
326 while ((theInt = in.read()) >= 0) {
327 outStream.write(theInt);
332 LOG.debug("file written successfully");
333 } catch (IOException e) {
334 LOG.error("problem writing file: {}", e.getMessage());