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