Coverage Report - org.owasp.dependencycheck.utils.FileUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
FileUtils
10%
8/76
12%
4/32
5.286
 
 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  0
     private FileUtils() {
 51  0
     }
 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  234
         String ret = null;
 61  234
         final int pos = fileName.lastIndexOf(".");
 62  234
         if (pos >= 0) {
 63  226
             ret = fileName.substring(pos + 1, fileName.length()).toLowerCase();
 64  
         }
 65  234
         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  
      * @throws IOException is thrown if the file could not be deleted
 73  
      */
 74  
     public static void delete(File file) throws IOException {
 75  1
         if (file.isDirectory()) {
 76  0
             for (File c : file.listFiles()) {
 77  0
                 delete(c);
 78  
             }
 79  
         }
 80  1
         if (!org.apache.commons.io.FileUtils.deleteQuietly(file)) {
 81  0
             throw new FileNotFoundException("Failed to delete file: " + file);
 82  
         }
 83  
         /* else {
 84  
          //delete on exit was a bad idea. if for some reason the file can't be deleted
 85  
          // this will cause a newly constructed file to be deleted and a subsequent run may fail.
 86  
          // still not sure why a file fails to be deleted, but can be overwritten... odd.
 87  
          file.deleteOnExit();
 88  
          }*/
 89  1
     }
 90  
 
 91  
     /**
 92  
      * Returns the data directory. If a path was specified in dependencycheck.properties or was specified using the
 93  
      * Settings object, and the path exists, that path will be returned as a File object. If it does not exist, then a
 94  
      * File object will be created based on the file location of the JAR containing the specified class.
 95  
      *
 96  
      * @param configuredFilePath the configured relative or absolute path
 97  
      * @param clazz the class to resolve the path
 98  
      * @return a File object
 99  
      * @throws IOException is thrown if the path could not be decoded
 100  
      * @deprecated This method should no longer be used. See the implementation in dependency-check-cli/App.java to see
 101  
      * how the data directory should be set.
 102  
      */
 103  
     @java.lang.Deprecated
 104  
     public static File getDataDirectory(String configuredFilePath, Class clazz) throws IOException {
 105  0
         final File file = new File(configuredFilePath);
 106  0
         if (file.isDirectory() && file.canWrite()) {
 107  0
             return new File(file.getCanonicalPath());
 108  
         } else {
 109  0
             final File exePath = getPathToJar(clazz);
 110  0
             return new File(exePath, configuredFilePath);
 111  
         }
 112  
     }
 113  
 
 114  
     /**
 115  
      * Retrieves the physical path to the parent directory containing the provided class. For example, if a JAR file
 116  
      * contained a class org.something.clazz this method would return the parent directory of the JAR file.
 117  
      *
 118  
      * @param clazz the class to determine the parent directory of
 119  
      * @return the parent directory of the file containing the specified class.
 120  
      * @throws UnsupportedEncodingException thrown if UTF-8 is not supported.
 121  
      * @deprecated this should no longer be used.
 122  
      */
 123  
     @java.lang.Deprecated
 124  
     public static File getPathToJar(Class clazz) throws UnsupportedEncodingException {
 125  0
         final String filePath = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
 126  0
         final String decodedPath = URLDecoder.decode(filePath, "UTF-8");
 127  0
         final File jarPath = new File(decodedPath);
 128  0
         return jarPath.getParentFile();
 129  
     }
 130  
 
 131  
     /**
 132  
      * Extracts the contents of an archive into the specified directory.
 133  
      *
 134  
      * @param archive an archive file such as a WAR or EAR
 135  
      * @param extractTo a directory to extract the contents to
 136  
      * @throws ExtractionException thrown if an exception occurs while extracting the files
 137  
      */
 138  
     public static void extractFiles(File archive, File extractTo) throws ExtractionException {
 139  0
         extractFiles(archive, extractTo, null);
 140  0
     }
 141  
 
 142  
     /**
 143  
      * Extracts the contents of an archive into the specified directory. The files are only extracted if they are
 144  
      * supported by the analyzers loaded into the specified engine. If the engine is specified as null then all files
 145  
      * are extracted.
 146  
      *
 147  
      * @param archive an archive file such as a WAR or EAR
 148  
      * @param extractTo a directory to extract the contents to
 149  
      * @param engine the scanning engine
 150  
      * @throws ExtractionException thrown if there is an error extracting the files
 151  
      */
 152  
     public static void extractFiles(File archive, File extractTo, Engine engine) throws ExtractionException {
 153  0
         if (archive == null || extractTo == null) {
 154  0
             return;
 155  
         }
 156  
 
 157  0
         FileInputStream fis = null;
 158  0
         ZipInputStream zis = null;
 159  
 
 160  
         try {
 161  0
             fis = new FileInputStream(archive);
 162  0
         } catch (FileNotFoundException ex) {
 163  0
             Logger.getLogger(FileUtils.class.getName()).log(Level.INFO, null, ex);
 164  0
             throw new ExtractionException("Archive file was not found.", ex);
 165  0
         }
 166  0
         zis = new ZipInputStream(new BufferedInputStream(fis));
 167  
         ZipEntry entry;
 168  
         try {
 169  0
             while ((entry = zis.getNextEntry()) != null) {
 170  0
                 if (entry.isDirectory()) {
 171  0
                     final File d = new File(extractTo, entry.getName());
 172  0
                     if (!d.exists() && !d.mkdirs()) {
 173  0
                         final String msg = String.format("Unable to create '%s'.", d.getAbsolutePath());
 174  0
                         throw new ExtractionException(msg);
 175  
                     }
 176  0
                 } else {
 177  0
                     final File file = new File(extractTo, entry.getName());
 178  0
                     final String ext = getFileExtension(file.getName());
 179  0
                     if (engine == null || engine.supportsExtension(ext)) {
 180  0
                         BufferedOutputStream bos = null;
 181  
                         FileOutputStream fos;
 182  
                         try {
 183  0
                             fos = new FileOutputStream(file);
 184  0
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 185  
                             int count;
 186  0
                             final byte data[] = new byte[BUFFER_SIZE];
 187  0
                             while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
 188  0
                                 bos.write(data, 0, count);
 189  
                             }
 190  0
                             bos.flush();
 191  0
                         } catch (FileNotFoundException ex) {
 192  0
                             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, null, ex);
 193  0
                             final String msg = String.format("Unable to find file '%s'.", file.getName());
 194  0
                             throw new ExtractionException(msg, ex);
 195  0
                         } catch (IOException ex) {
 196  0
                             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, null, ex);
 197  0
                             final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
 198  0
                             throw new ExtractionException(msg, ex);
 199  
                         } finally {
 200  0
                             if (bos != null) {
 201  
                                 try {
 202  0
                                     bos.close();
 203  0
                                 } catch (IOException ex) {
 204  0
                                     Logger.getLogger(FileUtils.class.getName()).log(Level.FINEST, null, ex);
 205  0
                                 }
 206  
                             }
 207  
                         }
 208  
                     }
 209  0
                 }
 210  
             }
 211  0
         } catch (IOException ex) {
 212  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 213  0
             Logger.getLogger(FileUtils.class.getName()).log(Level.FINE, msg, ex);
 214  0
             throw new ExtractionException(msg, ex);
 215  
         } finally {
 216  0
             try {
 217  0
                 zis.close();
 218  0
             } catch (IOException ex) {
 219  0
                 Logger.getLogger(FileUtils.class.getName()).log(Level.FINEST, null, ex);
 220  0
             }
 221  0
         }
 222  0
     }
 223  
 }