2  * Copyright © 2016-2018 European Support Limited
 
   4  * Licensed under the Apache License, Version 2.0 (the "License");
 
   5  * you may not use this file except in compliance with the License.
 
   6  * You may obtain a copy of the License at
 
   8  *      http://www.apache.org/licenses/LICENSE-2.0
 
  10  * Unless required by applicable law or agreed to in writing, software
 
  11  * distributed under the License is distributed on an "AS IS" BASIS,
 
  12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  13  * See the License for the specific language governing permissions and
 
  14  * limitations under the License.
 
  17 package org.openecomp.core.utilities.file;
 
  19 import org.apache.commons.io.FilenameUtils;
 
  20 import org.apache.commons.io.IOUtils;
 
  21 import org.openecomp.core.utilities.json.JsonUtil;
 
  22 import org.openecomp.sdc.tosca.services.YamlUtil;
 
  24 import java.io.ByteArrayInputStream;
 
  26 import java.io.FileOutputStream;
 
  27 import java.io.IOException;
 
  28 import java.io.InputStream;
 
  30 import java.nio.file.Files;
 
  31 import java.nio.file.Path;
 
  32 import java.nio.file.Paths;
 
  33 import java.util.Collections;
 
  34 import java.util.Enumeration;
 
  35 import java.util.HashMap;
 
  36 import java.util.LinkedList;
 
  37 import java.util.List;
 
  39 import java.util.Objects;
 
  40 import java.util.function.Function;
 
  41 import java.util.zip.ZipEntry;
 
  42 import java.util.zip.ZipInputStream;
 
  45  * The type File utils.
 
  47 public class FileUtils {
 
  50    * Allows to consume an input stream open against a resource with a given file name.
 
  52    * @param fileName the file name
 
  53    * @param function logic to be applied to the input stream
 
  55   public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
 
  57     Objects.requireNonNull(fileName);
 
  59     // the leading slash doesn't make sense and doesn't work when used with a class loader
 
  60     URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/")
 
  61         ? fileName.substring(1) : fileName);
 
  62     if (resource == null) {
 
  63       throw new IllegalArgumentException("Resource not found: " + fileName);
 
  66     return readViaInputStream(resource, function);
 
  70    * Allows to consume an input stream open against a resource with a given URL.
 
  72    * @param urlFile the url file
 
  73    * @param function logic to be applied to the input stream
 
  75   public static <T> T readViaInputStream(URL urlFile, Function<InputStream, T> function) {
 
  77     Objects.requireNonNull(urlFile);
 
  78     try (InputStream is = urlFile.openStream()) {
 
  79       return function.apply(is);
 
  80     } catch (IOException exception) {
 
  81       throw new RuntimeException(exception);
 
  86    * Gets file input streams.
 
  88    * @param fileName the file name
 
  89    * @return the file input streams
 
  91   public static List<URL> getAllLocations(String fileName) {
 
  93     List<URL> urls = new LinkedList<>();
 
  94     Enumeration<URL> urlFiles;
 
  97       urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
 
  98       while (urlFiles.hasMoreElements()) {
 
  99         urls.add(urlFiles.nextElement());
 
 103     } catch (IOException exception) {
 
 104       throw new RuntimeException(exception);
 
 107     return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
 
 111    * Convert to bytes byte [ ].
 
 113    * @param object    the object
 
 114    * @param extension the extension
 
 115    * @return the byte [ ]
 
 117   public static byte[] convertToBytes(Object object, FileExtension extension) {
 
 118     if (object != null) {
 
 119       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
 
 120         return new YamlUtil().objectToYaml(object).getBytes();
 
 122         return JsonUtil.object2Json(object).getBytes();
 
 130    * Convert to input stream input stream.
 
 132    * @param object    the object
 
 133    * @param extension the extension
 
 134    * @return the input stream
 
 136   public static InputStream convertToInputStream(Object object, FileExtension extension) {
 
 137     if (object != null) {
 
 141       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
 
 142         content = new YamlUtil().objectToYaml(object).getBytes();
 
 144         content = JsonUtil.object2Json(object).getBytes();
 
 147       return new ByteArrayInputStream(content);
 
 154    * Load file to input stream input stream.
 
 156    * @param fileName the file name
 
 157    * @return the input stream
 
 159   public static InputStream loadFileToInputStream(String fileName) {
 
 160     URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
 
 162       Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
 
 163       while (en.hasMoreElements()) {
 
 164         urlFile = en.nextElement();
 
 166     } catch (IOException | NullPointerException exception) {
 
 167       throw new RuntimeException(exception);
 
 170       if (urlFile != null) {
 
 171         return urlFile.openStream();
 
 173         throw new RuntimeException();
 
 175     } catch (IOException | NullPointerException exception) {
 
 176       throw new RuntimeException(exception);
 
 182    * To byte array byte [ ].
 
 184    * @param input the input
 
 185    * @return the byte [ ]
 
 187   public static byte[] toByteArray(InputStream input) {
 
 192       return IOUtils.toByteArray(input);
 
 193     } catch (IOException exception) {
 
 194       throw new RuntimeException(
 
 195           "error while converting input stream to byte array", exception);
 
 200    * Gets file without extention.
 
 202    * @param fileName the file name
 
 203    * @return the file without extention
 
 205   public static String getFileWithoutExtention(String fileName) {
 
 206     if (!fileName.contains(".")) {
 
 209     return fileName.substring(0, fileName.lastIndexOf('.'));
 
 212   public static String getFileExtension(String filename) {
 
 213       return FilenameUtils.getExtension(filename);
 
 216   public static String getNetworkPackageName(String filename) {
 
 217     String[] split = filename.split("\\.");
 
 219     if (split.length > 1) {
 
 226    * Gets file content map from zip.
 
 228    * @param zipData the zip data
 
 229    * @return the file content map from zip
 
 230    * @throws IOException the io exception
 
 232   public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException {
 
 234     try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData))) {
 
 236       FileContentHandler mapFileContent = new FileContentHandler();
 
 240       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
 
 241         mapFileContent.addFile(zipEntry.getName(), FileUtils.toByteArray(inputZipStream));
 
 244       return mapFileContent;
 
 246     } catch (RuntimeException exception) {
 
 247       throw new IOException(exception);
 
 253    * The enum File extension.
 
 255   public enum FileExtension {
 
 258      * Json file extension.
 
 262      * Yaml file extension.
 
 266      * Yml file extension.
 
 270     private final String displayName;
 
 272     FileExtension(String displayName) {
 
 273       this.displayName = displayName;
 
 279      * @return the display name
 
 281     public String getDisplayName() {
 
 288    * Write files and folders map to disk in the given path
 
 290    * @param fileContentHandler the file content handler
 
 292    * @return a map containing file names and their absolute paths
 
 293    * @throws IOException the io exception
 
 295   public static Map<String, String> writeFilesFromFileContentHandler(FileContentHandler
 
 301     File dirFile = dir.toFile();
 
 302     Map<String, String> filePaths = new HashMap<>();
 
 303     for (Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
 
 304       file = new File(dirFile, fileEntry.getKey());
 
 305       file.getParentFile().mkdirs();
 
 306       filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
 
 307       try (FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
 
 308         fop.write(fileEntry.getValue());
 
 317    * Verify whether the provided extension is valid Yaml/Yml extension or not.
 
 319    * @param fileExtension the file extension
 
 320    * @return the boolean
 
 322   public static boolean isValidYamlExtension(String fileExtension){
 
 323     return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) ||
 
 324         fileExtension.equalsIgnoreCase(FileExtension.YAML.getDisplayName());