Coverage Report - org.owasp.dependencycheck.utils.FileUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
FileUtils
0%
0/87
0%
0/38
4.778
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 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
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 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.
 15  
  *
 16  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.utils;
 19  
 
 20  
 import java.io.BufferedInputStream;
 21  
 import java.io.BufferedOutputStream;
 22  
 import java.io.File;
 23  
 import java.io.FileInputStream;
 24  
 import java.io.FileNotFoundException;
 25  
 import java.io.FileOutputStream;
 26  
 import java.io.IOException;
 27  
 import java.io.UnsupportedEncodingException;
 28  
 import java.net.URLDecoder;
 29  
 import java.util.UUID;
 30  
 import java.util.logging.Level;
 31  
 import java.util.logging.Logger;
 32  
 import java.util.zip.ZipEntry;
 33  
 import java.util.zip.ZipInputStream;
 34  
 import org.owasp.dependencycheck.Engine;
 35  
 
 36  
 /**
 37  
  * A collection of utilities for processing information about files.
 38  
  *
 39  
  * @author Jeremy Long <jeremy.long@owasp.org>
 40  
  */
 41  
 public final class FileUtils {
 42  
 
 43  
     /**
 44  
      * Bit bucket for non-Windows systems
 45  
      */
 46  
     private static final String BIT_BUCKET_UNIX = "/dev/null";
 47  
 
 48  
     /**
 49  
      * Bit bucket for Windows systems (yes, only one 'L')
 50  
      */
 51  
     private static final String BIT_BUCKET_WIN = "NUL";
 52  
 
 53  
     /**
 54  
      * The buffer size to use when extracting files from the archive.
 55  
      */
 56  
     private static final int BUFFER_SIZE = 4096;
 57  
 
 58  
     /**
 59  
      * Private constructor for a utility class.
 60  
      */
 61  
     private FileUtils() {
 62  
     }
 63  
 
 64  
     /**
 65  
      * Returns the (lowercase) file extension for a specified file.
 66  
      *
 67  
      * @param fileName the file name to retrieve the file extension from.
 68  
      * @return the file extension.
 69  
      */
 70  
     public static String getFileExtension(String fileName) {
 71  0
         String ret = null;
 72  0
         final int pos = fileName.lastIndexOf(".");
 73  0
         if (pos >= 0) {
 74  0
             ret = fileName.substring(pos + 1, fileName.length()).toLowerCase();
 75  
         }
 76  0
         return ret;
 77  
     }
 78  
 
 79  
     /**
 80  
      * Deletes a file. If the File is a directory it will recursively delete the contents.
 81  
      *
 82  
      * @param file the File to delete
 83  
      * @return true if the file was deleted successfully, otherwise false
 84  
      */
 85  
     public static boolean delete(File file) {
 86  0
         boolean success = true;
 87  0
         if (!org.apache.commons.io.FileUtils.deleteQuietly(file)) {
 88  0
             success = false;
 89  0
             final String msg = String.format("Failed to delete file: %s; attempting to delete on exit.", file.getPath());
 90  0
             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, msg);
 91  0
             file.deleteOnExit();
 92  
         }
 93  0
         return success;
 94  
     }
 95  
 
 96  
     /**
 97  
      * Generates a new temporary file name that is guaranteed to be unique.
 98  
      *
 99  
      * @param prefix the prefix for the file name to generate
 100  
      * @param extension the extension of the generated file name
 101  
      * @return a temporary File
 102  
      * @throws java.io.IOException thrown if the temporary folder could not be created
 103  
      */
 104  
     public static File getTempFile(String prefix, String extension) throws IOException {
 105  0
         final File dir = Settings.getTempDirectory();
 106  0
         if (!dir.exists()) {
 107  0
             if (!dir.mkdirs()) {
 108  0
                 throw new IOException("Unable to create temporary folder");
 109  
             }
 110  
         }
 111  0
         final String tempFileName = String.format("%s%s.%s", prefix, UUID.randomUUID().toString(), extension);
 112  0
         final File tempFile = new File(dir, tempFileName);
 113  0
         if (tempFile.exists()) {
 114  0
             return getTempFile(prefix, extension);
 115  
         }
 116  0
         return tempFile;
 117  
     }
 118  
 
 119  
     /**
 120  
      * Returns the data directory. If a path was specified in dependencycheck.properties or was specified using the
 121  
      * Settings object, and the path exists, that path will be returned as a File object. If it does not exist, then a
 122  
      * File object will be created based on the file location of the JAR containing the specified class.
 123  
      *
 124  
      * @param configuredFilePath the configured relative or absolute path
 125  
      * @param clazz the class to resolve the path
 126  
      * @return a File object
 127  
      * @throws IOException is thrown if the path could not be decoded
 128  
      * @deprecated This method should no longer be used. See the implementation in dependency-check-cli/App.java to see
 129  
      * how the data directory should be set.
 130  
      */
 131  
     @java.lang.Deprecated
 132  
     public static File getDataDirectory(String configuredFilePath, Class clazz) throws IOException {
 133  0
         final File file = new File(configuredFilePath);
 134  0
         if (file.isDirectory() && file.canWrite()) {
 135  0
             return new File(file.getCanonicalPath());
 136  
         } else {
 137  0
             final File exePath = getPathToJar(clazz);
 138  0
             return new File(exePath, configuredFilePath);
 139  
         }
 140  
     }
 141  
 
 142  
     /**
 143  
      * Retrieves the physical path to the parent directory containing the provided class. For example, if a JAR file
 144  
      * contained a class org.something.clazz this method would return the parent directory of the JAR file.
 145  
      *
 146  
      * @param clazz the class to determine the parent directory of
 147  
      * @return the parent directory of the file containing the specified class.
 148  
      * @throws UnsupportedEncodingException thrown if UTF-8 is not supported.
 149  
      * @deprecated this should no longer be used.
 150  
      */
 151  
     @java.lang.Deprecated
 152  
     public static File getPathToJar(Class clazz) throws UnsupportedEncodingException {
 153  0
         final String filePath = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
 154  0
         final String decodedPath = URLDecoder.decode(filePath, "UTF-8");
 155  0
         final File jarPath = new File(decodedPath);
 156  0
         return jarPath.getParentFile();
 157  
     }
 158  
 
 159  
     /**
 160  
      * Extracts the contents of an archive into the specified directory.
 161  
      *
 162  
      * @param archive an archive file such as a WAR or EAR
 163  
      * @param extractTo a directory to extract the contents to
 164  
      * @throws ExtractionException thrown if an exception occurs while extracting the files
 165  
      */
 166  
     public static void extractFiles(File archive, File extractTo) throws ExtractionException {
 167  0
         extractFiles(archive, extractTo, null);
 168  0
     }
 169  
 
 170  
     /**
 171  
      * Extracts the contents of an archive into the specified directory. The files are only extracted if they are
 172  
      * supported by the analyzers loaded into the specified engine. If the engine is specified as null then all files
 173  
      * are extracted.
 174  
      *
 175  
      * @param archive an archive file such as a WAR or EAR
 176  
      * @param extractTo a directory to extract the contents to
 177  
      * @param engine the scanning engine
 178  
      * @throws ExtractionException thrown if there is an error extracting the files
 179  
      */
 180  
     public static void extractFiles(File archive, File extractTo, Engine engine) throws ExtractionException {
 181  0
         if (archive == null || extractTo == null) {
 182  0
             return;
 183  
         }
 184  
 
 185  0
         FileInputStream fis = null;
 186  0
         ZipInputStream zis = null;
 187  
 
 188  
         try {
 189  0
             fis = new FileInputStream(archive);
 190  0
         } catch (FileNotFoundException ex) {
 191  0
             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, null, ex);
 192  0
             throw new ExtractionException("Archive file was not found.", ex);
 193  0
         }
 194  0
         zis = new ZipInputStream(new BufferedInputStream(fis));
 195  
         ZipEntry entry;
 196  
         try {
 197  0
             while ((entry = zis.getNextEntry()) != null) {
 198  0
                 if (entry.isDirectory()) {
 199  0
                     final File d = new File(extractTo, entry.getName());
 200  0
                     if (!d.exists() && !d.mkdirs()) {
 201  0
                         final String msg = String.format("Unable to create '%s'.", d.getAbsolutePath());
 202  0
                         throw new ExtractionException(msg);
 203  
                     }
 204  0
                 } else {
 205  0
                     final File file = new File(extractTo, entry.getName());
 206  0
                     final String ext = getFileExtension(file.getName());
 207  0
                     if (engine == null || engine.supportsExtension(ext)) {
 208  0
                         BufferedOutputStream bos = null;
 209  
                         FileOutputStream fos;
 210  
                         try {
 211  0
                             fos = new FileOutputStream(file);
 212  0
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 213  
                             int count;
 214  0
                             final byte data[] = new byte[BUFFER_SIZE];
 215  0
                             while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
 216  0
                                 bos.write(data, 0, count);
 217  
                             }
 218  0
                             bos.flush();
 219  0
                         } catch (FileNotFoundException ex) {
 220  0
                             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, null, ex);
 221  0
                             final String msg = String.format("Unable to find file '%s'.", file.getName());
 222  0
                             throw new ExtractionException(msg, ex);
 223  0
                         } catch (IOException ex) {
 224  0
                             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, null, ex);
 225  0
                             final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
 226  0
                             throw new ExtractionException(msg, ex);
 227  
                         } finally {
 228  0
                             if (bos != null) {
 229  
                                 try {
 230  0
                                     bos.close();
 231  0
                                 } catch (IOException ex) {
 232  0
                                     Logger.getLogger(FileUtils.class.getName()).log(Level.FINEST, null, ex);
 233  0
                                 }
 234  
                             }
 235  
                         }
 236  
                     }
 237  0
                 }
 238  
             }
 239  0
         } catch (IOException ex) {
 240  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 241  0
             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, msg, ex);
 242  0
             throw new ExtractionException(msg, ex);
 243  
         } finally {
 244  0
             try {
 245  0
                 zis.close();
 246  0
             } catch (IOException ex) {
 247  0
                 Logger.getLogger(FileUtils.class.getName()).log(Level.FINEST, null, ex);
 248  0
             }
 249  0
         }
 250  0
     }
 251  
 
 252  
     /**
 253  
      * Return the bit bucket for the OS. '/dev/null' for Unix and 'NUL' for Windows
 254  
      *
 255  
      * @return a String containing the bit bucket
 256  
      */
 257  
     public static String getBitBucket() {
 258  0
         if (System.getProperty("os.name").startsWith("Windows")) {
 259  0
             return BIT_BUCKET_WIN;
 260  
         } else {
 261  0
             return BIT_BUCKET_UNIX;
 262  
         }
 263  
     }
 264  
 }