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.devicemanager.base.internalTypes;
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;
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;
43 public class Resources {
45 private static final Logger LOG = LoggerFactory.getLogger(Resources.class);
47 private static final String RESSOURCEROOT = "src/main/resources";
49 private static URL getFileURL(String resFile) {
50 Bundle b = FrameworkUtil.getBundle(Resources.class);
52 LOG.debug("try to get file {}", resFile);
54 LOG.info("Load resource as file: {}", resFile);
55 u = getUrlForRessource(resFile);
57 LOG.info("Load resource from bundle: {}", resFile);
58 u = b.getEntry(resFile);
63 private static File getFile(String resFile) {
64 Bundle b = FrameworkUtil.getBundle(Resources.class);
66 LOG.debug("try to get file {}", resFile);
68 LOG.warn("cannot load bundle resources");
69 f = new File(RESSOURCEROOT + resFile);
72 f = new File(b.getEntry(resFile).toURI());
73 } catch (URISyntaxException e) {
74 LOG.warn("Con not load file: {}",e.getMessage());
80 private static String readFile(final URL u) throws IOException {
81 return readFile(u.openStream());
84 private static String readFile(final InputStream s) throws IOException {
86 BufferedReader in = new BufferedReader(new InputStreamReader(s));
87 StringBuilder sb = new StringBuilder();
89 while ((inputLine = in.readLine()) != null) {
97 public static List<URL> getFileURLs(String folder, final String filter, final boolean recursive)
99 Bundle b = FrameworkUtil.getBundle(Resources.class);
100 List<URL> list = new ArrayList<>();
102 FileFilter ff = pathname -> {
103 if (pathname.isFile()) {
104 return pathname.getName().contains(filter);
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) {
115 list.add(f.toURI().toURL());
116 } else if (f.isDirectory() && recursive) {
117 getFileURLsRecursive(f, ff, list);
123 getResourceURLsTreeRecurse(b, filter, b.getEntryPaths(folder), recursive, list);
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) {
134 list.add(f.toURI().toURL());
135 } else if (f.isDirectory()) {
136 getFileURLsRecursive(f, ff, list);
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);
151 getResourceURLsTreeRecurse(b, filter, list, recursive, outp);
155 if (name.contains(filter)) {
156 LOG.debug("add {} to list", name);
157 outp.add(b.getEntry(name));
159 LOG.debug("filtered out {}", name);
165 public static List<JSONObject> getJSONFiles(String folder, boolean recursive) {
166 List<JSONObject> list = new ArrayList<>();
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());
176 LOG.debug("try to parse " + u.toString());
178 JSONObject o = new JSONObject(readFile(u));
180 } catch (JSONException | IOException e) {
181 LOG.warn("problem reading/parsing file {} : {}", u, e.getMessage());
187 public static JSONObject getJSONFile(String resFile) {
188 LOG.debug("loading json file {} from res", resFile);
189 URL u = getFileURL(resFile);
191 LOG.warn("cannot find resfile: {}", resFile);
196 // parse to jsonobject
197 o = new JSONObject(readFile(u));
198 } catch (Exception e) {
199 LOG.warn("problem reading/parsing file: {}", e.getMessage());
205 * Used for reading plugins from resource files /elasticsearch/plugins/head
206 * /etc/elasticsearch-plugins /elasticsearch/plugins
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
213 public static boolean copyFolderInto(String resFolder, String dstFolder, String rootDirToRemove) {
215 Enumeration<URL> urls = null;
216 Bundle b = FrameworkUtil.getBundle(Resources.class);
218 LOG.info("Running in file text.");
219 urls = getResourceFolderFiles(resFolder);
221 urls = b.findEntries(resFolder, "*", true);
224 boolean success = true;
228 while (urls.hasMoreElements()) {
229 srcUrl = urls.nextElement();
230 srcFilename = srcUrl.getFile();
232 if (srcFilename.endsWith("/")) {
233 LOG.debug("Skip directory: {}", srcFilename);
237 LOG.debug("try to copy res {} to {}", srcFilename, dstFolder);
238 if (rootDirToRemove != null) {
240 srcFilename.substring(srcFilename.indexOf(rootDirToRemove) + rootDirToRemove.length() + 1);
241 LOG.debug("dstfilename trimmed to {}", srcFilename);
243 dstFilename = dstFolder + "/" + srcFilename;
245 if (!extractFileTo(srcUrl, new File(dstFilename))) {
248 } catch (Exception e) {
249 LOG.warn("problem copying res {} to {}: {}", srcFilename, dstFilename, e.getMessage());
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<>();
265 for (File f : files) {
267 if (f.isDirectory()) {
268 urlCollection.addAll(Collections.list(getResourceFolderFiles(folder + "/" + f.getName())));
270 urlCollection.add(f.toURI().toURL());
272 } catch (MalformedURLException e) {
273 LOG.error("Can not read ressources", e);
279 Enumeration<URL> urls = Collections.enumeration(urlCollection);
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);
290 public static boolean extractFileTo(String resFile, File oFile) {
294 LOG.debug("try to copy {} from res to {}", resFile, oFile.getAbsolutePath());
295 URL u = getFileURL(resFile);
297 LOG.warn("cannot find resfile: {}", resFile);
300 return extractFileTo(u, oFile);
303 public static boolean extractFileTo(URL u, File oFile) {
305 if (oFile.isDirectory()) {
309 oFile.getParentFile().mkdirs();
312 if (!oFile.exists()) {
314 oFile.createNewFile();
315 } catch (IOException e) {
316 LOG.warn("problem creating file {}: {}", oFile.getAbsoluteFile(), e.getMessage());
319 try (InputStream in = u.openStream(); OutputStream outStream = new FileOutputStream(oFile);) {
322 while ((theInt = in.read()) >= 0) {
323 outStream.write(theInt);
328 LOG.debug("file written successfully");
329 } catch (IOException e) {
330 LOG.error("problem writing file: {}", e.getMessage());