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