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